Search code examples
google-compute-enginegoogle-cloud-platformjclouds

Starting and stopping instances on google compute engine


I want to start/resume and stop/suspend instances on google compute engine, but it gives "java.lang.UnsupportedOperationException".Is there any alternative way to perform these operations?

public class Example {

     public static void main(String[] args) 
     {
      String provider = "google-compute-engine";
      String identity = "****@developer.gserviceaccount.com";
      String credential = "path to private key";
      String groupName = "newgroup";
      credential = getCredentialFromJsonKeyFile(credential);
      Iterable<Module> modules = ImmutableSet.<Module> of(
              new SshjSshClientModule(),
              new SLF4JLoggingModule(),
              new EnterpriseConfigurationModule());
      ContextBuilder builder = ContextBuilder.newBuilder(provider)
              .credentials(identity, credential)
              .modules(modules);
      ComputeService compute=builder.buildView(ComputeServiceContext.class).getComputeService();

      compute.suspendNode("Instance id");
      //compute.suspendNodesMatching(Predicates.<NodeMetadata> and(inGroup(groupName)));
      System.out.println("suspended");
      compute.getContext().close();     
}

   private static String getCredentialFromJsonKeyFile(String filename) {
      try {
         String fileContents = Files.toString(new File(filename), UTF_8);
         Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(fileContents);
         String credential = credentialSupplier.get().credential;
         return credential;
      } catch (IOException e) {
         System.err.println("Exception reading private key from '%s': " + filename);
         e.printStackTrace();
         System.exit(1);
         return null;
      }
   }
}

Output:

suspending node(node id)

Exception in thread "main" java.lang.UnsupportedOperationException: suspend is not supported by GCE

at org.jclouds.googlecomputeengine.compute.GoogleComputeEngineServiceAdapter.suspendNode(GoogleComputeEngineServiceAdapter.java:251)

at org.jclouds.compute.strategy.impl.AdaptingComputeServiceStrategies.suspendNode(AdaptingComputeServiceStrategies.java:171)

at org.jclouds.compute.internal.BaseComputeService.suspendNode(BaseComputeService.java:503)

at org.jclouds.examples.compute.basics.Example.main(Example.java:79)


Solution

  • It is not directly supported in the portable jclouds ComputeService, but from the ComputeServiceContext you can get the GoogleComputeEngineApi and the InstanceApi, and use the start/stop methods in there.

    FYI, there is an ongoing patch to add support for the start/stop operations in the ComputeService: https://github.com/jclouds/jclouds-labs-google/pull/141