You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@whirr.apache.org by to...@apache.org on 2010/06/09 22:13:21 UTC

svn commit: r953141 [2/2] - in /incubator/whirr/trunk: ./ core/ core/src/ core/src/main/ core/src/main/java/ core/src/main/java/org/ core/src/main/java/org/apache/ core/src/main/java/org/apache/whirr/ core/src/main/java/org/apache/whirr/service/ script...

Added: incubator/whirr/trunk/services/hadoop/src/main/java/org/apache/whirr/service/hadoop/HadoopService.java
URL: http://svn.apache.org/viewvc/incubator/whirr/trunk/services/hadoop/src/main/java/org/apache/whirr/service/hadoop/HadoopService.java?rev=953141&view=auto
==============================================================================
--- incubator/whirr/trunk/services/hadoop/src/main/java/org/apache/whirr/service/hadoop/HadoopService.java (added)
+++ incubator/whirr/trunk/services/hadoop/src/main/java/org/apache/whirr/service/hadoop/HadoopService.java Wed Jun  9 20:13:19 2010
@@ -0,0 +1,174 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.whirr.service.hadoop;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.jclouds.compute.options.TemplateOptions.Builder.runScript;
+
+import com.google.common.base.Charsets;
+import com.google.common.base.Function;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Sets;
+import com.google.common.io.Files;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.Map.Entry;
+
+import org.apache.whirr.service.ClusterSpec;
+import org.apache.whirr.service.ComputeServiceBuilder;
+import org.apache.whirr.service.RunUrlBuilder;
+import org.apache.whirr.service.Service;
+import org.apache.whirr.service.ServiceSpec;
+import org.apache.whirr.service.Cluster.Instance;
+import org.apache.whirr.service.ClusterSpec.InstanceTemplate;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.RunNodesException;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.OsFamily;
+import org.jclouds.compute.domain.Template;
+
+public class HadoopService extends Service {
+  
+  public static final Set<String> MASTER_ROLE = Sets.newHashSet("nn", "jt");
+  public static final Set<String> WORKER_ROLE = Sets.newHashSet("dn", "tt");
+
+  public HadoopService(ServiceSpec serviceSpec) {
+    super(serviceSpec);
+  }
+
+  @Override
+  public HadoopCluster launchCluster(ClusterSpec clusterSpec) throws IOException {
+    ComputeService computeService = ComputeServiceBuilder.build(serviceSpec);
+
+    String privateKey = serviceSpec.readPrivateKey();
+    String publicKey = serviceSpec.readPublicKey();
+    
+    // deal with user packages and autoshutdown with extra runurls
+    byte[] nnjtBootScript = RunUrlBuilder.runUrls(
+      "sun/java/install",
+      String.format("apache/hadoop/install nn,jt -c %s", serviceSpec.getProvider()));
+    
+    Template template = computeService.templateBuilder()
+    .osFamily(OsFamily.UBUNTU)
+    .options(runScript(nnjtBootScript)
+        .installPrivateKey(privateKey)
+	      .authorizePublicKey(publicKey)
+	      .inboundPorts(22, 80, 8020, 8021, 50030)) // TODO: restrict further
+    .build();
+    
+    InstanceTemplate instanceTemplate = clusterSpec.getInstanceTemplate(MASTER_ROLE);
+    checkNotNull(instanceTemplate);
+    checkArgument(instanceTemplate.getNumberOfInstances() == 1);
+    Set<? extends NodeMetadata> nodes;
+    try {
+      nodes = computeService.runNodesWithTag(
+      serviceSpec.getClusterName(), 1, template);
+    } catch (RunNodesException e) {
+      // TODO: can we do better here (retry?)
+      throw new IOException(e);
+    }
+    NodeMetadata node = Iterables.getOnlyElement(nodes);
+    InetAddress namenodePublicAddress = Iterables.getOnlyElement(node.getPublicAddresses());
+    InetAddress jobtrackerPublicAddress = Iterables.getOnlyElement(node.getPublicAddresses());
+    
+    byte[] slaveBootScript = RunUrlBuilder.runUrls(
+      "sun/java/install",
+      String.format("apache/hadoop/install dn,tt -n %s -j %s",
+	      namenodePublicAddress.getHostName(),
+	      jobtrackerPublicAddress.getHostName()));
+
+    template = computeService.templateBuilder()
+    .osFamily(OsFamily.UBUNTU)
+    .options(runScript(slaveBootScript)
+        .installPrivateKey(privateKey)
+	      .authorizePublicKey(publicKey))
+    .build();
+
+    instanceTemplate = clusterSpec.getInstanceTemplate(WORKER_ROLE);
+    checkNotNull(instanceTemplate);
+
+    Set<? extends NodeMetadata> workerNodes;
+    try {
+      workerNodes = computeService.runNodesWithTag(serviceSpec.getClusterName(),
+	instanceTemplate.getNumberOfInstances(), template);
+    } catch (RunNodesException e) {
+      // TODO: don't bail out if only a few have failed to start
+      throw new IOException(e);
+    }
+    
+    // TODO: wait for TTs to come up (done in test for the moment)
+    
+    Set<Instance> instances = Sets.union(getInstances(MASTER_ROLE, Collections.singleton(node)),
+	getInstances(WORKER_ROLE, workerNodes));
+    
+    Properties config = createClientSideProperties(namenodePublicAddress, jobtrackerPublicAddress);
+    return new HadoopCluster(instances, config);
+  }
+  
+  private Set<Instance> getInstances(final Set<String> roles, Set<? extends NodeMetadata> nodes) {
+    return Sets.newHashSet(Collections2.transform(Sets.newHashSet(nodes),
+	new Function<NodeMetadata, Instance>() {
+      @Override
+      public Instance apply(NodeMetadata node) {
+	return new Instance(roles,
+	    Iterables.get(node.getPublicAddresses(), 0),
+	    Iterables.get(node.getPrivateAddresses(), 0));
+      }
+    }));
+  }
+  
+  private Properties createClientSideProperties(InetAddress namenode, InetAddress jobtracker) throws IOException {
+      Properties config = new Properties();
+      config.setProperty("hadoop.job.ugi", "root,root");
+      config.setProperty("fs.default.name", String.format("hdfs://%s:8020/", namenode.getHostName()));
+      config.setProperty("mapred.job.tracker", String.format("%s:8021", jobtracker.getHostName()));
+      config.setProperty("hadoop.socks.server", "localhost:6666");
+      config.setProperty("hadoop.rpc.socket.factory.class.default", "org.apache.hadoop.net.SocksSocketFactory");
+      return config;
+  }
+
+  private void createClientSideHadoopSiteFile(InetAddress namenode, InetAddress jobtracker) throws IOException {
+    File file = new File("/tmp/hadoop-site.xml");
+    Files.write(generateHadoopConfigurationFile(createClientSideProperties(namenode, jobtracker)), file, Charsets.UTF_8);
+  }
+  
+  private CharSequence generateHadoopConfigurationFile(Properties config) {
+    StringBuilder sb = new StringBuilder();
+    sb.append("<?xml version=\"1.0\"?>\n");
+    sb.append("<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>\n");
+    sb.append("<configuration>\n");
+    for (Entry<Object, Object> entry : config.entrySet()) {
+      sb.append("<property>\n");
+      sb.append("<name>").append(entry.getKey()).append("</name>\n");
+      sb.append("<value>").append(entry.getValue()).append("</value>\n");
+      sb.append("</property>\n");
+    }
+    sb.append("</configuration>\n");
+    return sb;
+  }
+  
+}

Propchange: incubator/whirr/trunk/services/hadoop/src/main/java/org/apache/whirr/service/hadoop/HadoopService.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/whirr/trunk/services/hadoop/src/test/java/org/apache/whirr/service/hadoop/HadoopServiceTest.java
URL: http://svn.apache.org/viewvc/incubator/whirr/trunk/services/hadoop/src/test/java/org/apache/whirr/service/hadoop/HadoopServiceTest.java?rev=953141&view=auto
==============================================================================
--- incubator/whirr/trunk/services/hadoop/src/test/java/org/apache/whirr/service/hadoop/HadoopServiceTest.java (added)
+++ incubator/whirr/trunk/services/hadoop/src/test/java/org/apache/whirr/service/hadoop/HadoopServiceTest.java Wed Jun  9 20:13:19 2010
@@ -0,0 +1,149 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.whirr.service.hadoop;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNull;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.Map.Entry;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.LongWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.mapred.ClusterStatus;
+import org.apache.hadoop.mapred.FileInputFormat;
+import org.apache.hadoop.mapred.FileOutputFormat;
+import org.apache.hadoop.mapred.JobClient;
+import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapred.lib.LongSumReducer;
+import org.apache.hadoop.mapred.lib.TokenCountMapper;
+import org.apache.whirr.service.ClusterSpec;
+import org.apache.whirr.service.ServiceSpec;
+import org.apache.whirr.service.ClusterSpec.InstanceTemplate;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class HadoopServiceTest {
+  
+  private String clusterName = "hadoopclustertest";
+  
+  private HadoopService service;
+  private HadoopProxy proxy;
+  private HadoopCluster cluster;
+  
+  @Before
+  public void setUp() throws IOException {
+    String secretKeyFile;
+    try {
+       secretKeyFile = checkNotNull(System.getProperty("whirr.test.ssh.keyfile"));
+    } catch (NullPointerException e) {
+       secretKeyFile = System.getProperty("user.home") + "/.ssh/id_rsa";
+    }
+    ServiceSpec serviceSpec = new ServiceSpec();
+    serviceSpec.setProvider(checkNotNull(System.getProperty("whirr.test.provider", "ec2")));
+    serviceSpec.setAccount(checkNotNull(System.getProperty("whirr.test.user")));
+    serviceSpec.setKey(checkNotNull(System.getProperty("whirr.test.key")));
+    serviceSpec.setSecretKeyFile(secretKeyFile);
+    serviceSpec.setClusterName(clusterName);
+    service = new HadoopService(serviceSpec);
+    
+    ClusterSpec clusterSpec = new ClusterSpec(
+	new InstanceTemplate(1, HadoopService.MASTER_ROLE),
+	new InstanceTemplate(1, HadoopService.WORKER_ROLE));
+
+    cluster = service.launchCluster(clusterSpec);
+    proxy = new HadoopProxy(serviceSpec, cluster);
+    proxy.start();
+  }
+  
+  @Test
+  public void test() throws Exception {
+    Configuration conf = getConfiguration();
+    
+    JobConf job = new JobConf(conf, HadoopServiceTest.class);
+    JobClient client = new JobClient(job);
+    waitForTaskTrackers(client);
+
+    FileSystem fs = FileSystem.get(conf);
+    
+    OutputStream os = fs.create(new Path("input"));
+    Writer wr = new OutputStreamWriter(os);
+    wr.write("b a\n");
+    wr.close();
+    
+    job.setMapperClass(TokenCountMapper.class);
+    job.setReducerClass(LongSumReducer.class);
+    job.setOutputKeyClass(Text.class);
+    job.setOutputValueClass(LongWritable.class);
+    FileInputFormat.setInputPaths(job, new Path("input"));
+    FileOutputFormat.setOutputPath(job, new Path("output"));
+    
+    JobClient.runJob(job);
+
+    FSDataInputStream in = fs.open(new Path("output/part-00000"));
+    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+    assertEquals("a\t1", reader.readLine());
+    assertEquals("b\t1", reader.readLine());
+    assertNull(reader.readLine());
+    reader.close();
+    
+  }
+  
+  private Configuration getConfiguration() {
+    Configuration conf = new Configuration();
+    for (Entry<Object, Object> entry : cluster.getConfiguration().entrySet()) {
+      conf.set(entry.getKey().toString(), entry.getValue().toString());
+    }
+    return conf;
+  }
+  
+  private static void waitForTaskTrackers(JobClient client) throws IOException {
+    while (true) {
+      ClusterStatus clusterStatus = client.getClusterStatus();
+      int taskTrackerCount = clusterStatus.getTaskTrackers();
+      if (taskTrackerCount > 0) {
+	break;
+      }
+      try {
+	System.out.print(".");
+	Thread.sleep(1000);
+      } catch (InterruptedException e) {
+        break;
+      }
+    }
+  }
+  
+  @After
+  public void tearDown() throws IOException {
+    proxy.stop();
+    service.destroyCluster();
+  }
+
+}

Propchange: incubator/whirr/trunk/services/hadoop/src/test/java/org/apache/whirr/service/hadoop/HadoopServiceTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/whirr/trunk/services/zookeeper/pom.xml
URL: http://svn.apache.org/viewvc/incubator/whirr/trunk/services/zookeeper/pom.xml?rev=953141&view=auto
==============================================================================
--- incubator/whirr/trunk/services/zookeeper/pom.xml (added)
+++ incubator/whirr/trunk/services/zookeeper/pom.xml Wed Jun  9 20:13:19 2010
@@ -0,0 +1,111 @@
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.apache.whirr</groupId>
+  <artifactId>whirr-zookeeper</artifactId>
+  <packaging>jar</packaging>
+  <version>0.1.0-SNAPSHOT</version>
+  <name>Whirr ZooKeeper</name>
+  <dependencies>
+    <dependency>
+      <groupId>${project.groupId}</groupId>
+      <artifactId>whirr-core</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.jclouds</groupId>
+      <artifactId>jclouds-aws</artifactId>
+      <version>1.0-beta-5</version>
+    </dependency>
+    <dependency>
+      <groupId>org.jclouds</groupId>
+      <artifactId>jclouds-compute</artifactId>
+      <version>1.0-beta-5</version>
+    </dependency>
+    <dependency>
+      <groupId>org.jclouds</groupId>
+      <artifactId>jclouds-enterprise</artifactId>
+      <version>1.0-beta-5</version>
+    </dependency>
+    <dependency>
+      <groupId>org.jclouds</groupId>
+      <artifactId>jclouds-jsch</artifactId>
+      <version>1.0-beta-5</version>
+    </dependency>
+    <dependency>
+      <groupId>org.jclouds</groupId>
+      <artifactId>jclouds-log4j</artifactId>
+      <version>1.0-beta-5</version>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <version>4.8.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>zookeeper</artifactId>
+      <version>3.3.0</version>
+    </dependency>
+
+    <dependency>
+      <groupId>log4j</groupId>
+      <artifactId>log4j</artifactId>
+      <version>1.2.15</version>
+      <scope>provided</scope>
+      <exclusions>
+        <exclusion>
+          <groupId>javax.mail</groupId>
+          <artifactId>mail</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>javax.jms</groupId>
+          <artifactId>jms</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>com.sun.jdmk</groupId>
+          <artifactId>jmxtools</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>com.sun.jmx</groupId>
+          <artifactId>jmxri</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+
+  </dependencies>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <configuration>
+          <source>1.6</source>
+          <target>1.6</target>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+  <repositories>
+    <repository>
+      <id>jclouds</id>
+      <url>http://jclouds.googlecode.com/svn/repo</url>
+    </repository>
+  </repositories>
+</project>

Propchange: incubator/whirr/trunk/services/zookeeper/pom.xml
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperCluster.java
URL: http://svn.apache.org/viewvc/incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperCluster.java?rev=953141&view=auto
==============================================================================
--- incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperCluster.java (added)
+++ incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperCluster.java Wed Jun  9 20:13:19 2010
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.whirr.service.zookeeper;
+
+import java.util.Set;
+
+import org.apache.whirr.service.Cluster;
+
+public class ZooKeeperCluster extends Cluster {
+  
+  private String hosts;
+
+  public ZooKeeperCluster(Set<Instance> instances, String hosts) {
+    super(instances);
+    this.hosts = hosts;
+  }
+  
+  public String getHosts() {
+    return hosts;
+  }
+
+}

Propchange: incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperCluster.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperService.java
URL: http://svn.apache.org/viewvc/incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperService.java?rev=953141&view=auto
==============================================================================
--- incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperService.java (added)
+++ incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperService.java Wed Jun  9 20:13:19 2010
@@ -0,0 +1,139 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.whirr.service.zookeeper;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.jclouds.compute.options.TemplateOptions.Builder.runScript;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.whirr.service.ClusterSpec;
+import org.apache.whirr.service.ComputeServiceBuilder;
+import org.apache.whirr.service.RunUrlBuilder;
+import org.apache.whirr.service.Service;
+import org.apache.whirr.service.ServiceSpec;
+import org.apache.whirr.service.Cluster.Instance;
+import org.apache.whirr.service.ClusterSpec.InstanceTemplate;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.RunNodesException;
+import org.jclouds.compute.RunScriptOnNodesException;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.OsFamily;
+import org.jclouds.compute.domain.Template;
+
+public class ZooKeeperService extends Service {
+    
+  public static final String ZOOKEEPER_ROLE = "zk";
+  private static final int CLIENT_PORT = 2181;
+  
+  public ZooKeeperService(ServiceSpec serviceSpec) {
+    super(serviceSpec);
+  }
+
+  @Override
+  public ZooKeeperCluster launchCluster(ClusterSpec clusterSpec) throws IOException {
+      
+    ComputeService computeService = ComputeServiceBuilder.build(serviceSpec);
+
+    byte[] bootScript = RunUrlBuilder.runUrls(
+	"sun/java/install",
+	"apache/zookeeper/install");
+    Template template = computeService.templateBuilder()
+      .osFamily(OsFamily.UBUNTU)
+      .options(runScript(bootScript)
+	  .installPrivateKey(serviceSpec.readPrivateKey())
+	  .authorizePublicKey(serviceSpec.readPublicKey())
+	  .inboundPorts(22, CLIENT_PORT))
+      .build();
+    
+    InstanceTemplate instanceTemplate = clusterSpec.getInstanceTemplate(ZOOKEEPER_ROLE);
+    checkNotNull(instanceTemplate);
+    int ensembleSize = instanceTemplate.getNumberOfInstances();
+    Set<? extends NodeMetadata> nodeMap;
+    try {
+      nodeMap = computeService.runNodesWithTag(serviceSpec.getClusterName(), ensembleSize,
+	  template);
+    } catch (RunNodesException e) {
+      // TODO: can we do better here - proceed if ensemble is big enough?
+      throw new IOException(e);
+    }
+    List<NodeMetadata> nodes = Lists.newArrayList(nodeMap);
+    
+    // Pass list of all servers in ensemble to configure script.
+    // Position is significant: i-th server has id i.
+    String servers = Joiner.on(' ').join(getPrivateIps(nodes));
+    byte[] configureScript = RunUrlBuilder.runUrls(
+	"apache/zookeeper/post-configure " + servers);
+    try {
+      computeService.runScriptOnNodesWithTag(serviceSpec.getClusterName(), configureScript);
+    } catch (RunScriptOnNodesException e) {
+      // TODO: retry
+      throw new IOException(e);
+    }
+    
+    String hosts = Joiner.on(',').join(getHosts(nodes));
+    return new ZooKeeperCluster(getInstances(nodes), hosts);
+  }
+
+  private List<String> getPrivateIps(List<NodeMetadata> nodes) {
+    return Lists.transform(Lists.newArrayList(nodes),
+	new Function<NodeMetadata, String>() {
+      @Override
+      public String apply(NodeMetadata node) {
+	return Iterables.get(node.getPrivateAddresses(), 0).getHostAddress();
+      }
+    });
+  }
+  
+  private Set<Instance> getInstances(List<NodeMetadata> nodes) {
+    return Sets.newHashSet(Collections2.transform(Sets.newHashSet(nodes),
+	new Function<NodeMetadata, Instance>() {
+      @Override
+      public Instance apply(NodeMetadata node) {
+	return new Instance(Collections.singleton(ZOOKEEPER_ROLE),
+	    Iterables.get(node.getPublicAddresses(), 0),
+	    Iterables.get(node.getPrivateAddresses(), 0));
+      }
+    }));
+  }
+  
+  private List<String> getHosts(List<NodeMetadata> nodes) {
+    return Lists.transform(Lists.newArrayList(nodes),
+	new Function<NodeMetadata, String>() {
+      @Override
+      public String apply(NodeMetadata node) {
+	String publicIp =  Iterables.get(node.getPublicAddresses(), 0)
+	  .getHostName();
+	return String.format("%s:%d", publicIp, CLIENT_PORT);
+      }
+    });
+  }
+
+}

Propchange: incubator/whirr/trunk/services/zookeeper/src/main/java/org/apache/whirr/service/zookeeper/ZooKeeperService.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/whirr/trunk/services/zookeeper/src/test/java/org/apache/whirr/service/zookeeper/ZooKeeperServiceTest.java
URL: http://svn.apache.org/viewvc/incubator/whirr/trunk/services/zookeeper/src/test/java/org/apache/whirr/service/zookeeper/ZooKeeperServiceTest.java?rev=953141&view=auto
==============================================================================
--- incubator/whirr/trunk/services/zookeeper/src/test/java/org/apache/whirr/service/zookeeper/ZooKeeperServiceTest.java (added)
+++ incubator/whirr/trunk/services/zookeeper/src/test/java/org/apache/whirr/service/zookeeper/ZooKeeperServiceTest.java Wed Jun  9 20:13:19 2010
@@ -0,0 +1,120 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.whirr.service.zookeeper;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static junit.framework.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+
+import org.apache.whirr.service.ClusterSpec;
+import org.apache.whirr.service.ClusterSpec.InstanceTemplate;
+import org.apache.whirr.service.ServiceSpec;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.Watcher.Event.KeeperState;
+import org.apache.zookeeper.ZooDefs.Ids;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class ZooKeeperServiceTest {
+  
+  private String clusterName = "zkclustertest";
+  
+  private ZooKeeperService service;
+  private ZooKeeperCluster cluster;
+  
+  @Before
+  public void setUp() throws IOException {
+    String secretKeyFile;
+    try {
+       secretKeyFile = checkNotNull(System.getProperty("whirr.test.ssh.keyfile"));
+    } catch (NullPointerException e) {
+       secretKeyFile = System.getProperty("user.home") + "/.ssh/id_rsa";
+    }
+    ServiceSpec serviceSpec = new ServiceSpec();
+    serviceSpec.setProvider(checkNotNull(System.getProperty("whirr.test.provider", "ec2")));
+    serviceSpec.setAccount(checkNotNull(System.getProperty("whirr.test.user")));
+    serviceSpec.setKey(checkNotNull(System.getProperty("whirr.test.key")));
+    serviceSpec.setSecretKeyFile(secretKeyFile);
+    serviceSpec.setClusterName(clusterName);
+    service = new ZooKeeperService(serviceSpec);
+    
+    ClusterSpec clusterSpec = new ClusterSpec(
+	new InstanceTemplate(2, ZooKeeperService.ZOOKEEPER_ROLE));
+    cluster = service.launchCluster(clusterSpec);
+    System.out.println(cluster.getHosts());
+  }
+  
+  @Test
+  public void test() throws Exception {
+    class ConnectionWatcher implements Watcher {
+
+      private ZooKeeper zk;
+      private CountDownLatch latch = new CountDownLatch(1);
+      
+      public void connect(String hosts) throws IOException, InterruptedException {
+	zk = new ZooKeeper(hosts, 5000, this);
+	latch.await();
+      }
+      
+      public ZooKeeper getZooKeeper() {
+	return zk;
+      }
+      
+      @Override
+      public void process(WatchedEvent event) {
+	if (event.getState() == KeeperState.SyncConnected) {
+	  latch.countDown();
+	}
+      }
+      
+      public void close() throws InterruptedException {
+	if (zk != null) {
+	  zk.close();
+	}
+      }
+      
+    }
+    
+    String path = "/data";
+    String data = "Hello";
+    ConnectionWatcher watcher = new ConnectionWatcher();
+    watcher.connect(cluster.getHosts());
+    watcher.getZooKeeper().create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE,
+      CreateMode.PERSISTENT);
+    watcher.close();
+    
+    watcher = new ConnectionWatcher();
+    watcher.connect(cluster.getHosts());
+    byte[] actualData = watcher.getZooKeeper().getData(path, false, null);
+    assertEquals(data, new String(actualData));
+    watcher.close();
+  }
+  
+  @After
+  public void tearDown() throws IOException {
+    service.destroyCluster();
+  }
+  
+}

Propchange: incubator/whirr/trunk/services/zookeeper/src/test/java/org/apache/whirr/service/zookeeper/ZooKeeperServiceTest.java
------------------------------------------------------------------------------
    svn:eol-style = native