com.google.api.services.compute.model.Operation Java Examples

The following examples show how to use com.google.api.services.compute.model.Operation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleProviderUtils.java    From halyard with Apache License 2.0 6 votes vote down vote up
private static void waitOnOperation(Supplier<Operation> operationSupplier) {
  Operation operation = operationSupplier.get();
  while (!operation.getStatus().equals("DONE")) {
    if (operation.getError() != null) {
      throw new HalException(
          FATAL,
          String.join(
              "\n",
              operation.getError().getErrors().stream()
                  .map(e -> e.getCode() + ": " + e.getMessage())
                  .collect(Collectors.toList())));
    }
    operation = operationSupplier.get();
    DaemonTaskHandler.safeSleep(TimeUnit.SECONDS.toMillis(1));
  }
}
 
Example #2
Source File: GcpNetworkResourceBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public CloudResource build(GcpContext context, AuthenticatedContext auth, Network network, Security security, CloudResource resource) throws Exception {
    if (!isExistingNetwork(network)) {
        Compute compute = context.getCompute();
        String projectId = context.getProjectId();

        com.google.api.services.compute.model.Network gcpNetwork = new com.google.api.services.compute.model.Network();
        gcpNetwork.setName(resource.getName());
        gcpNetwork.setAutoCreateSubnetworks(false);
        Insert networkInsert = compute.networks().insert(projectId, gcpNetwork);
        try {
            Operation operation = networkInsert.execute();
            if (operation.getHttpErrorStatusCode() != null) {
                throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), resource.getName());
            }
            context.putParameter(NETWORK_NAME, resource.getName());
            return createOperationAwareCloudResource(resource, operation);
        } catch (GoogleJsonResponseException e) {
            throw new GcpResourceException(checkException(e), resourceType(), resource.getName());
        }
    }
    context.putParameter(NETWORK_NAME, resource.getName());
    return new Builder().cloudResource(resource).persistent(false).build();
}
 
Example #3
Source File: AbstractGcpResourceBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
protected List<CloudResourceStatus> checkResources(ResourceType type, GcpContext context, AuthenticatedContext auth, Iterable<CloudResource> resources) {
    List<CloudResourceStatus> result = new ArrayList<>();
    for (CloudResource resource : resources) {
        LOGGER.debug("Check {} resource: {}", type, resource);
        try {
            String operationId = resource.getStringParameter(OPERATION_ID);
            Operation operation = gcpResourceChecker.check(context, operationId);
            boolean finished = operation == null || GcpStackUtil.isOperationFinished(operation);
            ResourceStatus successStatus = context.isBuild() ? ResourceStatus.CREATED : ResourceStatus.DELETED;
            result.add(new CloudResourceStatus(resource, finished ? successStatus : ResourceStatus.IN_PROGRESS));
            if (finished) {
                if (successStatus == ResourceStatus.CREATED) {
                    LOGGER.debug("Creation of {} was successful", resource);
                } else {
                    LOGGER.debug("Deletion of {} was successful", resource);
                }
            }
        } catch (Exception e) {
            CloudContext cloudContext = auth.getCloudContext();
            throw new GcpResourceException("Error during status check", type,
                    cloudContext.getName(), cloudContext.getId(), resource.getName(), e);
        }
    }
    return result;
}
 
Example #4
Source File: GcpStackUtil.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private static String checkForErrors(Operation operation) {
    if (operation == null) {
        LOGGER.info("Operation is null!");
        return null;
    }
    String msg = null;
    if (operation.getError() != null) {
        StringBuilder error = new StringBuilder();
        if (operation.getError().getErrors() != null) {
            for (Errors errors : operation.getError().getErrors()) {
                error.append(String.format("code: %s -> message: %s %s", errors.getCode(), errors.getMessage(), System.lineSeparator()));
            }
            msg = error.toString();
        } else {
            LOGGER.debug("No errors found, Error: {}", operation.getError());
        }
    }
    if (operation.getHttpErrorStatusCode() != null) {
        msg += String.format(" HTTP error message: %s, HTTP error status code: %s", operation.getHttpErrorMessage(), operation.getHttpErrorStatusCode());
    }
    return msg;
}
 
Example #5
Source File: GcpFirewallInResourceBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public CloudResource build(GcpContext context, AuthenticatedContext auth, Group group, Network network, Security security, CloudResource buildableResource)
        throws Exception {
    String projectId = context.getProjectId();

    ComputeRequest<Operation> firewallRequest = StringUtils.isNotBlank(security.getCloudSecurityId()) && isExistingNetwork(network)
            ? updateExistingFirewallForNewTargets(context, auth, group, security)
            : createNewFirewallRule(context, auth, group, network, security, buildableResource, projectId);
    try {
        Operation operation = firewallRequest.execute();
        if (operation.getHttpErrorStatusCode() != null) {
            throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), buildableResource.getName());
        }
        return createOperationAwareCloudResource(buildableResource, operation);
    } catch (GoogleJsonResponseException e) {
        throw new GcpResourceException(checkException(e), resourceType(), buildableResource.getName());
    }
}
 
Example #6
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private CloudVmInstanceStatus stopStart(GcpContext context, AuthenticatedContext auth, CloudInstance instance, boolean stopRequest) {
    String projectId = GcpStackUtil.getProjectId(auth.getCloudCredential());
    String availabilityZone = context.getLocation().getAvailabilityZone().value();
    Compute compute = context.getCompute();
    String instanceId = instance.getInstanceId();
    try {
        Get get = compute.instances().get(projectId, availabilityZone, instanceId);
        String state = stopRequest ? "RUNNING" : "TERMINATED";
        Instance instanceResponse = get.execute();
        if (state.equals(instanceResponse.getStatus())) {
            Operation operation = stopRequest ? compute.instances().stop(projectId, availabilityZone, instanceId).setPrettyPrint(true).execute()
                    : executeStartOperation(projectId, availabilityZone, compute, instanceId, instance.getTemplate(), instanceResponse.getDisks());
            CloudInstance operationAwareCloudInstance = createOperationAwareCloudInstance(instance, operation);
            return new CloudVmInstanceStatus(operationAwareCloudInstance, InstanceStatus.IN_PROGRESS);
        } else {
            LOGGER.debug("Instance {} is not in {} state - won't start it.", state, instanceId);
            return null;
        }
    } catch (IOException e) {
        throw new GcpResourceException(String.format("An error occurred while stopping the vm '%s'", instanceId), e);
    }
}
 
Example #7
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private Operation executeStartOperation(String projectId, String availabilityZone, Compute compute, String instanceId, InstanceTemplate template,
        List<AttachedDisk> disks) throws IOException {

    if (gcpDiskEncryptionService.hasCustomEncryptionRequested(template)) {
        CustomerEncryptionKey customerEncryptionKey = gcpDiskEncryptionService.createCustomerEncryptionKey(template);
        List<CustomerEncryptionKeyProtectedDisk> protectedDisks = disks
                .stream()
                .map(AttachedDisk::getSource)
                .map(toCustomerEncryptionKeyProtectedDisk(customerEncryptionKey))
                .collect(Collectors.toList());
        InstancesStartWithEncryptionKeyRequest request = new InstancesStartWithEncryptionKeyRequest();
        request.setDisks(protectedDisks);
        return compute.instances().startWithEncryptionKey(projectId, availabilityZone, instanceId, request).setPrettyPrint(true).execute();
    } else {
        return compute.instances().start(projectId, availabilityZone, instanceId).setPrettyPrint(true).execute();
    }
}
 
Example #8
Source File: GcpFirewallInResourceBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public CloudResourceStatus update(GcpContext context, AuthenticatedContext auth, Group group, Network network, Security security, CloudResource resource) {
    String projectId = context.getProjectId();
    Compute compute = context.getCompute();
    String resourceName = resource.getName();
    try {
        Firewall fireWall = compute.firewalls().get(projectId, resourceName).execute();
        List<String> sourceRanges = getSourceRanges(security);
        fireWall.setSourceRanges(sourceRanges);
        Operation operation = compute.firewalls().update(projectId, resourceName, fireWall).execute();
        CloudResource cloudResource = createOperationAwareCloudResource(resource, operation);
        return checkResources(context, auth, Collections.singletonList(cloudResource)).get(0);
    } catch (IOException e) {
        throw new GcpResourceException("Failed to update resource!", GCP_FIREWALL_IN, resourceName, e);
    }
}
 
Example #9
Source File: GcpFirewallInResourceBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private ComputeRequest<Operation> createNewFirewallRule(GcpContext context, AuthenticatedContext auth, Group group, Network network, Security security,
        CloudResource buildableResource, String projectId) throws IOException {
    List<String> sourceRanges = getSourceRanges(security);

    Firewall firewall = new Firewall();
    firewall.setSourceRanges(sourceRanges);

    List<Allowed> allowedRules = new ArrayList<>(createAllowedRules(security));

    firewall.setTargetTags(Collections.singletonList(GcpStackUtil.getGroupClusterTag(auth.getCloudContext(), group)));
    firewall.setAllowed(allowedRules);
    firewall.setName(buildableResource.getName());
    if (isNotEmpty(getSharedProjectId(network))) {
        firewall.setNetwork(String.format("https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s",
                getSharedProjectId(network),
                context.getParameter(GcpNetworkResourceBuilder.NETWORK_NAME, String.class)));
    } else {
        firewall.setNetwork(String.format("https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s", projectId,
                context.getParameter(GcpNetworkResourceBuilder.NETWORK_NAME, String.class)));
    }

    return context.getCompute().firewalls().insert(projectId, firewall);
}
 
Example #10
Source File: GcpSubnetResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource, Network network) throws Exception {
    if (isNewNetworkAndSubnet(network) || isNewSubnetInExistingNetwork(network)) {
        Compute compute = context.getCompute();
        String projectId = context.getProjectId();
        try {
            Operation operation = compute.subnetworks().delete(projectId, context.getLocation().getRegion().value(), resource.getName()).execute();
            return createOperationAwareCloudResource(resource, operation);
        } catch (GoogleJsonResponseException e) {
            exceptionHandler(e, resource.getName(), resourceType());
            return null;
        }
    }
    return null;
}
 
Example #11
Source File: GoogleProviderUtils.java    From halyard with Apache License 2.0 5 votes vote down vote up
static void waitOnGlobalOperation(Compute compute, String project, Operation operation)
    throws IOException {
  waitOnOperation(
      () -> {
        try {
          return compute.globalOperations().get(project, operation.getName()).execute();
        } catch (IOException e) {
          throw new HalException(FATAL, "Operation failed: " + e);
        }
      });
}
 
Example #12
Source File: GcpNetworkResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource, Network network) throws Exception {
    if (!isExistingNetwork(network)) {
        Compute compute = context.getCompute();
        String projectId = context.getProjectId();
        try {
            Operation operation = compute.networks().delete(projectId, resource.getName()).execute();
            return createOperationAwareCloudResource(resource, operation);
        } catch (GoogleJsonResponseException e) {
            exceptionHandler(e, resource.getName(), resourceType());
            return null;
        }
    }
    return null;
}
 
Example #13
Source File: GcpFirewallInternalResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource, Network network) throws Exception {
    try {
        Operation operation = context.getCompute().firewalls().delete(context.getProjectId(), resource.getName()).execute();
        return createOperationAwareCloudResource(resource, operation);
    } catch (GoogleJsonResponseException e) {
        exceptionHandler(e, resource.getName(), resourceType());
        return null;
    }
}
 
Example #14
Source File: GcpFirewallInResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource, Network network) throws Exception {
    try {
        Operation operation = context.getCompute().firewalls().delete(context.getProjectId(), resource.getName()).execute();
        return createOperationAwareCloudResource(resource, operation);
    } catch (GoogleJsonResponseException e) {
        exceptionHandler(e, resource.getName(), resourceType());
        return null;
    }
}
 
Example #15
Source File: GcpStackUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static boolean isOperationFinished(Operation operation) throws Exception {
    String errorMessage = checkForErrors(operation);
    if (errorMessage != null) {
        throw new Exception(errorMessage);
    } else {
        Integer progress = operation.getProgress();
        return FINISHED == progress;
    }
}
 
Example #16
Source File: GcpResourceChecker.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void checkError(Operation execute) {
    if (execute.getError() != null) {
        String msg = null;
        StringBuilder error = new StringBuilder();
        if (execute.getError().getErrors() != null) {
            for (Operation.Error.Errors errors : execute.getError().getErrors()) {
                error.append(String.format("code: %s -> message: %s %s", errors.getCode(), errors.getMessage(), System.lineSeparator()));
            }
            msg = error.toString();
        }
        throw new CloudConnectorException(msg);
    }
}
 
Example #17
Source File: AbstractGcpResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
protected CloudResource createOperationAwareCloudResource(CloudResource resource, Operation operation) {
    return new Builder()
            .cloudResource(resource)
            .params(Collections.singletonMap(OPERATION_ID, operation.getName()))
            .persistent(false)
            .build();
}
 
Example #18
Source File: GcpInstanceResourceBuilderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    privateId = 0L;
    privateCrn = "crn";
    name = "master";
    flavor = "m1.medium";
    instanceId = "SOME_ID";
    volumes = Arrays.asList(new Volume("/hadoop/fs1", "HDD", 1), new Volume("/hadoop/fs2", "HDD", 1));
    List<SecurityRule> rules = Collections.singletonList(new SecurityRule("0.0.0.0/0",
            new PortDefinition[]{new PortDefinition("22", "22"), new PortDefinition("443", "443")}, "tcp"));
    security = new Security(rules, emptyList());
    Location location = Location.location(Region.region("region"), AvailabilityZone.availabilityZone("az"));
    Map<InstanceGroupType, String> userData = ImmutableMap.of(InstanceGroupType.CORE, "CORE", InstanceGroupType.GATEWAY, "GATEWAY");
    image = new Image("cb-centos66-amb200-2015-05-25", userData, "redhat6", "redhat6", "", "default", "default-id", new HashMap<>());
    CloudContext cloudContext = new CloudContext(privateId, "testname", "GCP", USER_ID, WORKSPACE_ID);
    CloudCredential cloudCredential = new CloudCredential(privateCrn, "credentialname");
    cloudCredential.putParameter("projectId", "projectId");
    String projectId = GcpStackUtil.getProjectId(cloudCredential);
    String serviceAccountId = GcpStackUtil.getServiceAccountId(cloudCredential);
    authenticatedContext = new AuthenticatedContext(cloudContext, cloudCredential);
    context = new GcpContext(cloudContext.getName(), location, projectId, serviceAccountId, compute, false, 30, false);
    List<CloudResource> networkResources = Collections.singletonList(new Builder().type(ResourceType.GCP_NETWORK).name("network-test").build());
    context.addNetworkResources(networkResources);
    operation = new Operation();
    operation.setName("operation");
    operation.setHttpErrorStatusCode(null);
    operation.setError(new Operation.Error());
    GcpResourceNameService resourceNameService = new GcpResourceNameService();
    ReflectionTestUtils.setField(resourceNameService, "maxResourceNameLength", 50);
    ReflectionTestUtils.setField(builder, "resourceNameService", resourceNameService);
    Network network = new Network(null);
    cloudStack = new CloudStack(Collections.emptyList(), network, image, emptyMap(), emptyMap(), null,
            null, null, null, null);
}
 
Example #19
Source File: GcpSubnetResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudResource build(GcpContext context, AuthenticatedContext auth, Network network, Security security, CloudResource resource) throws Exception {
    if (isNewNetworkAndSubnet(network) || isNewSubnetInExistingNetwork(network)) {
        Compute compute = context.getCompute();
        String projectId = context.getProjectId();

        Subnetwork gcpSubnet = new Subnetwork();
        gcpSubnet.setName(resource.getName());
        gcpSubnet.setIpCidrRange(network.getSubnet().getCidr());

        String networkName = context.getStringParameter(GcpNetworkResourceBuilder.NETWORK_NAME);
        if (isNotEmpty(getSharedProjectId(network))) {
            gcpSubnet.setNetwork(String.format("https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s",
                    getSharedProjectId(network), networkName));
        } else {
            gcpSubnet.setNetwork(String.format("https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s", projectId, networkName));
        }

        Insert snInsert = compute.subnetworks().insert(projectId, auth.getCloudContext().getLocation().getRegion().value(), gcpSubnet);
        try {
            Operation operation = snInsert.execute();
            if (operation.getHttpErrorStatusCode() != null) {
                throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), resource.getName());
            }
            context.putParameter(SUBNET_NAME, resource.getName());
            return createOperationAwareCloudResource(resource, operation);
        } catch (GoogleJsonResponseException e) {
            throw new GcpResourceException(checkException(e), resourceType(), resource.getName());
        }
    }
    context.putParameter(SUBNET_NAME, resource.getName());
    return new Builder().cloudResource(resource).persistent(false).build();
}
 
Example #20
Source File: GcpAttachedDiskResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public List<CloudResourceStatus> checkResources(GcpContext context, AuthenticatedContext auth, List<CloudResource> resources) {
    List<CloudResourceStatus> result = new ArrayList<>();
    for (CloudResource resource : resources) {
        LOGGER.debug("Check {} resource: {}", resourceType(), resource);
        List<String> operationIds = Optional.ofNullable(resource.getParameter(OPERATION_ID, List.class)).orElse(List.of());

        boolean finished = operationIds.isEmpty() || operationIds.stream()
                .allMatch(operationId -> {
                    try {
                        Operation operation = getGcpResourceChecker().check(context, operationId);
                        return operation == null || GcpStackUtil.isOperationFinished(operation);
                    } catch (Exception e) {
                        CloudContext cloudContext = auth.getCloudContext();
                        throw new GcpResourceException("Error during status check", resourceType(),
                                cloudContext.getName(), cloudContext.getId(), resource.getName(), e);
                    }
                });
        ResourceStatus successStatus = context.isBuild() ? ResourceStatus.CREATED : ResourceStatus.DELETED;
        result.add(new CloudResourceStatus(resource, finished ? successStatus : ResourceStatus.IN_PROGRESS));
        if (finished) {
            if (successStatus == ResourceStatus.CREATED) {
                LOGGER.debug("Creation of {} was successful", resource);
            } else {
                LOGGER.debug("Deletion of {} was successful", resource);
            }
        }
    }
    return result;
}
 
Example #21
Source File: GcpReservedIpResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource) throws Exception {
    Compute compute = context.getCompute();
    String projectId = context.getProjectId();
    String region = context.getLocation().getRegion().value();
    try {
        Operation operation = compute.addresses().delete(projectId, region, resource.getName()).execute();
        return createOperationAwareCloudResource(resource, operation);
    } catch (GoogleJsonResponseException e) {
        exceptionHandler(e, resource.getName(), resourceType());
        return null;
    }
}
 
Example #22
Source File: GcpReservedIpResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public List<CloudResource> build(GcpContext context, long privateId, AuthenticatedContext auth, Group group,
        List<CloudResource> buildableResource, CloudStack cloudStack) throws Exception {
    List<CloudResource> result = buildableResource;
    if (!buildableResource.isEmpty()) {
        CloudResource resource = buildableResource.get(0);
        String projectId = context.getProjectId();
        String region = context.getLocation().getRegion().value();

        Address address = new Address();
        address.setName(resource.getName());

        Map<String, Object> customTags = new HashMap<>();
        customTags.putAll(cloudStack.getTags());
        address.setUnknownKeys(customTags);
        Insert networkInsert = context.getCompute().addresses().insert(projectId, region, address);
        try {
            Operation operation = networkInsert.execute();
            if (operation.getHttpErrorStatusCode() != null) {
                throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), resource.getName());
            }
            result = Collections.singletonList(createOperationAwareCloudResource(resource, operation));
        } catch (GoogleJsonResponseException e) {
            throw new GcpResourceException(checkException(e), resourceType(), resource.getName());
        }
    }
    return result;
}
 
Example #23
Source File: GcpDiskResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource) throws Exception {
    String resourceName = resource.getName();
    try {
        Operation operation = context.getCompute().disks()
                .delete(context.getProjectId(), context.getLocation().getAvailabilityZone().value(), resourceName).execute();
        return createOperationAwareCloudResource(resource, operation);
    } catch (GoogleJsonResponseException e) {
        exceptionHandler(e, resourceName, resourceType());
    }
    return null;
}
 
Example #24
Source File: GcpDiskResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public List<CloudResource> build(GcpContext context, long privateId, AuthenticatedContext auth, Group group,
        List<CloudResource> buildableResources, CloudStack cloudStack) throws Exception {
    String projectId = context.getProjectId();
    Location location = context.getLocation();

    Disk disk = new Disk();
    disk.setSizeGb((long) group.getRootVolumeSize());
    disk.setName(buildableResources.get(0).getName());
    disk.setKind(GcpDiskType.HDD.getUrl(projectId, location.getAvailabilityZone()));

    InstanceTemplate template = group.getReferenceInstanceConfiguration().getTemplate();
    gcpDiskEncryptionService.addEncryptionKeyToDisk(template, disk);

    Map<String, String> customTags = new HashMap<>();
    customTags.putAll(cloudStack.getTags());
    disk.setLabels(customTags);

    Insert insDisk = context.getCompute().disks().insert(projectId, location.getAvailabilityZone().value(), disk);
    insDisk.setSourceImage(GcpStackUtil.getAmbariImage(projectId, cloudStack.getImage().getImageName()));
    try {
        Operation operation = insDisk.execute();
        if (operation.getHttpErrorStatusCode() != null) {
            throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), buildableResources.get(0).getName());
        }
        return Collections.singletonList(createOperationAwareCloudResource(buildableResources.get(0), operation));
    } catch (GoogleJsonResponseException e) {
        throw new GcpResourceException(checkException(e), resourceType(), buildableResources.get(0).getName());
    }
}
 
Example #25
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudResource delete(GcpContext context, AuthenticatedContext auth, CloudResource resource) throws Exception {
    String resourceName = resource.getName();
    try {
        Operation operation = context.getCompute().instances()
                .delete(context.getProjectId(), context.getLocation().getAvailabilityZone().value(), resourceName).execute();
        return createOperationAwareCloudResource(resource, operation);
    } catch (GoogleJsonResponseException e) {
        exceptionHandler(e, resourceName, resourceType());
    }
    return null;
}
 
Example #26
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void verifyOperation(Operation operation, List<CloudResource> buildableResource) {
    if (operation.getHttpErrorStatusCode() != null) {
        throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), buildableResource.get(0).getName());
    }
    if (operation.getError() != null && !operation.getError().isEmpty()) {
        throw new GcpResourceException(operation.getError().getErrors().stream()
                .map(Operation.Error.Errors::getMessage).collect(Collectors.joining(",")), resourceType(), buildableResource.get(0).getName());
    }
}
 
Example #27
Source File: ComputeEngineSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static Operation deleteInstance(Compute compute, String instanceName) throws Exception {
  System.out.println(
      "================== Deleting Instance " + instanceName + " ==================");
  Compute.Instances.Delete delete =
      compute.instances().delete(PROJECT_ID, ZONE_NAME, instanceName);
  return delete.execute();
}
 
Example #28
Source File: GoogleProviderUtils.java    From halyard with Apache License 2.0 5 votes vote down vote up
static void waitOnZoneOperation(Compute compute, String project, String zone, Operation operation)
    throws IOException {
  waitOnOperation(
      () -> {
        try {
          return compute.zoneOperations().get(project, zone, operation.getName()).execute();
        } catch (IOException e) {
          throw new HalException(FATAL, "Operation failed: " + e);
        }
      });
}
 
Example #29
Source File: GcpAttachedDiskResourceBuilder.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public List<CloudResource> build(GcpContext context, long privateId, AuthenticatedContext auth, Group group,
        List<CloudResource> resources, CloudStack cloudStack) throws Exception {
    CloudInstance instance = group.getReferenceInstanceConfiguration();
    InstanceTemplate template = instance.getTemplate();

    List<String> operations = new ArrayList<>();
    List<String> syncedOperations = Collections.synchronizedList(operations);
    String projectId = context.getProjectId();
    Compute compute = context.getCompute();
    Collection<Future<Void>> futures = new ArrayList<>();

    List<CloudResource> buildableResource = resources.stream()
            .filter(cloudResource -> CommonStatus.REQUESTED.equals(cloudResource.getStatus()))
            .collect(Collectors.toList());

    List<CloudResource> result = new ArrayList<>();
    for (CloudResource volumeSetResource : buildableResource) {
        VolumeSetAttributes volumeSetAttributes = volumeSetResource.getParameter(CloudResource.ATTRIBUTES, VolumeSetAttributes.class);

        for (VolumeSetAttributes.Volume volume : volumeSetAttributes.getVolumes()) {
            Disk disk = createDisk(projectId, volume, cloudStack.getTags(), volumeSetAttributes);

            gcpDiskEncryptionService.addEncryptionKeyToDisk(template, disk);
            Future<Void> submit = intermediateBuilderExecutor.submit(() -> {
                Insert insDisk = compute.disks().insert(projectId, volumeSetAttributes.getAvailabilityZone(), disk);
                try {
                    Operation operation = insDisk.execute();
                    syncedOperations.add(operation.getName());
                    if (operation.getHttpErrorStatusCode() != null) {
                        throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), disk.getName());
                    }
                } catch (GoogleJsonResponseException e) {
                    throw new GcpResourceException(checkException(e), resourceType(), disk.getName());
                }
                return null;
            });
            futures.add(submit);
        }
        volumeSetResource.putParameter(OPERATION_ID, operations);
        result.add(new Builder().cloudResource(volumeSetResource)
                .status(CommonStatus.CREATED)
                .params(volumeSetResource.getParameters())
                .build());
    }

    for (Future<Void> future : futures) {
        future.get();
    }

    result.addAll(resources.stream().filter(cloudResource -> CommonStatus.CREATED.equals(cloudResource.getStatus())).collect(Collectors.toList()));
    return result;
}
 
Example #30
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public List<CloudResource> build(GcpContext context, long privateId, AuthenticatedContext auth, Group group, List<CloudResource> buildableResource,
        CloudStack cloudStack) throws Exception {
    InstanceTemplate template = group.getReferenceInstanceConfiguration().getTemplate();
    String projectId = context.getProjectId();
    Location location = context.getLocation();
    Compute compute = context.getCompute();

    List<CloudResource> computeResources = context.getComputeResources(privateId);
    List<AttachedDisk> listOfDisks = new ArrayList<>();

    listOfDisks.addAll(getBootDiskList(computeResources, projectId, location.getAvailabilityZone()));
    listOfDisks.addAll(getAttachedDisks(computeResources, projectId));

    listOfDisks.forEach(disk -> gcpDiskEncryptionService.addEncryptionKeyToDisk(template, disk));

    Instance instance = new Instance();
    instance.setMachineType(String.format("https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/%s",
            projectId, location.getAvailabilityZone().value(), template.getFlavor()));
    instance.setName(buildableResource.get(0).getName());
    instance.setCanIpForward(Boolean.TRUE);
    instance.setNetworkInterfaces(getNetworkInterface(context, computeResources, group, cloudStack));
    instance.setDisks(listOfDisks);
    instance.setServiceAccounts(extractServiceAccounts(cloudStack));
    Scheduling scheduling = new Scheduling();
    boolean preemptible = false;
    if (template.getParameter(PREEMPTIBLE, Boolean.class) != null) {
        preemptible = template.getParameter(PREEMPTIBLE, Boolean.class);
    }
    scheduling.setPreemptible(preemptible);
    instance.setScheduling(scheduling);

    Tags tags = new Tags();
    List<String> tagList = new ArrayList<>();
    Map<String, String> labels = new HashMap<>();
    String groupname = group.getName().toLowerCase().replaceAll("[^A-Za-z0-9 ]", "");
    tagList.add(groupname);

    tagList.add(GcpStackUtil.getClusterTag(auth.getCloudContext()));
    tagList.add(GcpStackUtil.getGroupClusterTag(auth.getCloudContext(), group));
    cloudStack.getTags().forEach((key, value) -> tagList.add(key + '-' + value));

    labels.putAll(cloudStack.getTags());
    tags.setItems(tagList);

    instance.setTags(tags);
    instance.setLabels(labels);

    Metadata metadata = new Metadata();
    metadata.setItems(new ArrayList<>());

    Items sshMetaData = new Items();
    sshMetaData.setKey("ssh-keys");
    sshMetaData.setValue(group.getInstanceAuthentication().getLoginUserName() + ':' + group.getInstanceAuthentication().getPublicKey());

    Items blockProjectWideSsh = new Items();
    blockProjectWideSsh.setKey("block-project-ssh-keys");
    blockProjectWideSsh.setValue("TRUE");

    Items startupScript = new Items();
    startupScript.setKey("startup-script");
    startupScript.setValue(cloudStack.getImage().getUserDataByType(group.getType()));

    metadata.getItems().add(sshMetaData);
    metadata.getItems().add(startupScript);
    metadata.getItems().add(blockProjectWideSsh);
    instance.setMetadata(metadata);

    Insert insert = compute.instances().insert(projectId, location.getAvailabilityZone().value(), instance);
    insert.setPrettyPrint(Boolean.TRUE);
    try {
        Operation operation = insert.execute();
        verifyOperation(operation, buildableResource);
        updateDiskSetWithInstanceName(auth, computeResources, instance);
        return singletonList(createOperationAwareCloudResource(buildableResource.get(0), operation));
    } catch (GoogleJsonResponseException e) {
        throw new GcpResourceException(checkException(e), resourceType(), buildableResource.get(0).getName());
    }
}