Search in sources :

Example 11 with Operation

use of com.google.api.services.compute.model.Operation in project cloudbreak by hortonworks.

the class GcpReservedIpResourceBuilder method build.

@Override
public List<CloudResource> build(GcpContext context, long privateId, AuthenticatedContext auth, Group group, Image image, List<CloudResource> buildableResource, Map<String, String> tags) 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, String> customTags = new HashMap<>();
        customTags.putAll(tags);
        customTags.putAll(defaultCostTaggingService.prepareIpTagging());
        address.setLabels(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;
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Address(com.google.api.services.compute.model.Address) HashMap(java.util.HashMap) GcpResourceException(com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException) CloudResource(com.sequenceiq.cloudbreak.cloud.model.CloudResource) Operation(com.google.api.services.compute.model.Operation) Insert(com.google.api.services.compute.Compute.Addresses.Insert)

Example 12 with Operation

use of com.google.api.services.compute.model.Operation in project cloudbreak by hortonworks.

the class GcpFirewallInResourceBuilder method build.

@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;
    firewallRequest = StringUtils.isNotBlank(security.getCloudSecurityId()) && isExistingNetwork(network) ? updateExistingFirewallForNewTargets(context, auth, group, security) : createNewFirewallRule(context, auth, group, 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());
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) GcpResourceException(com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException) Operation(com.google.api.services.compute.model.Operation)

Example 13 with Operation

use of com.google.api.services.compute.model.Operation in project cloudbreak by hortonworks.

the class GcpFirewallInResourceBuilder method createNewFirewallRule.

private ComputeRequest<Operation> createNewFirewallRule(GcpContext context, AuthenticatedContext auth, Group group, Security security, CloudResource buildableResource, String projectId) throws IOException {
    ComputeRequest<Operation> firewallRequest;
    List<String> sourceRanges = getSourceRanges(security);
    Firewall firewall = new Firewall();
    firewall.setSourceRanges(sourceRanges);
    List<Allowed> allowedRules = new ArrayList<>();
    allowedRules.add(new Allowed().setIPProtocol("icmp"));
    allowedRules.addAll(createRule(security));
    firewall.setTargetTags(Collections.singletonList(GcpStackUtil.getGroupClusterTag(auth.getCloudContext(), group)));
    firewall.setAllowed(allowedRules);
    firewall.setName(buildableResource.getName());
    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);
}
Also used : ArrayList(java.util.ArrayList) Operation(com.google.api.services.compute.model.Operation) Allowed(com.google.api.services.compute.model.Firewall.Allowed) Firewall(com.google.api.services.compute.model.Firewall)

Example 14 with Operation

use of com.google.api.services.compute.model.Operation in project java-docs-samples by GoogleCloudPlatform.

the class ComputeEngineSample method main.

public static void main(String[] args) {
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        // Authenticate using Google Application Default Credentials.
        GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
        if (credential.createScopedRequired()) {
            List<String> scopes = new ArrayList<>();
            // Set Google Cloud Storage scope to Full Control.
            scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
            // Set Google Compute Engine scope to Read-write.
            scopes.add(ComputeScopes.COMPUTE);
            credential = credential.createScoped(scopes);
        }
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
        // Create Compute Engine object for listing instances.
        Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, requestInitializer).setApplicationName(APPLICATION_NAME).build();
        // List out instances, looking for the one created by this sample app.
        boolean foundOurInstance = printInstances(compute);
        Operation op;
        if (foundOurInstance) {
            op = deleteInstance(compute, SAMPLE_INSTANCE_NAME);
        } else {
            op = startInstance(compute, SAMPLE_INSTANCE_NAME);
        }
        // Call Compute Engine API operation and poll for operation completion status
        System.out.println("Waiting for operation completion...");
        Operation.Error error = blockUntilComplete(compute, op, OPERATION_TIMEOUT_MILLIS);
        if (error == null) {
            System.out.println("Success!");
        } else {
            System.out.println(error.toPrettyString());
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}
Also used : HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) ArrayList(java.util.ArrayList) Operation(com.google.api.services.compute.model.Operation) IOException(java.io.IOException) Compute(com.google.api.services.compute.Compute) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 15 with Operation

use of com.google.api.services.compute.model.Operation in project halyard by spinnaker.

the class GoogleDistributedService method ensureRunning.

@Override
default void ensureRunning(AccountDeploymentDetails<GoogleAccount> details, ResolvedConfiguration resolvedConfiguration, List<ConfigSource> configSources, boolean recreate) {
    DaemonTaskHandler.newStage("Deploying " + getServiceName() + " via GCE API");
    Integer version = 0;
    ServiceSettings settings = resolvedConfiguration.getServiceSettings(getService());
    SpinnakerRuntimeSettings runtimeSettings = resolvedConfiguration.getRuntimeSettings();
    RunningServiceDetails runningServiceDetails = getRunningServiceDetails(details, runtimeSettings);
    GoogleAccount account = details.getAccount();
    Compute compute = GoogleProviderUtils.getCompute(details);
    String project = account.getProject();
    String zone = settings.getLocation();
    boolean exists = runningServiceDetails.getInstances().containsKey(version);
    if (!recreate && exists) {
        DaemonTaskHandler.message("Service " + getServiceName() + " is already deployed and not safe to restart");
        return;
    } else if (exists) {
        DaemonTaskHandler.message("Recreating existing " + getServiceName() + "...");
        deleteVersion(details, settings, version);
    }
    InstanceGroupManager manager = new InstanceGroupManager();
    InstanceTemplate template = new InstanceTemplate().setName(getServiceName() + "-hal-" + System.currentTimeMillis()).setDescription("Halyard-generated instance template for deploying Spinnaker");
    Metadata metadata = new Metadata().setItems(getMetadata(details, runtimeSettings, configSources, version));
    AccessConfig accessConfig = new AccessConfig().setName("External NAT").setType("ONE_TO_ONE_NAT");
    NetworkInterface networkInterface = new NetworkInterface().setNetwork(GoogleProviderUtils.ensureSpinnakerNetworkExists(details)).setAccessConfigs(Collections.singletonList(accessConfig));
    ServiceAccount sa = new ServiceAccount().setEmail(GoogleProviderUtils.defaultServiceAccount(details)).setScopes(getScopes());
    InstanceProperties properties = new InstanceProperties().setMachineType(getDefaultInstanceType()).setMetadata(metadata).setServiceAccounts(Collections.singletonList(sa)).setNetworkInterfaces(Collections.singletonList(networkInterface));
    AttachedDisk disk = new AttachedDisk().setBoot(true).setAutoDelete(true).setType("PERSISTENT");
    AttachedDiskInitializeParams diskParams = new AttachedDiskInitializeParams().setDiskSizeGb(20L).setDiskType(GCEUtil.buildDiskTypeUrl(project, zone, GoogleDiskType.PD_SSD)).setSourceImage(getArtifactId(details.getDeploymentName()));
    disk.setInitializeParams(diskParams);
    List<AttachedDisk> disks = new ArrayList<>();
    disks.add(disk);
    properties.setDisks(disks);
    template.setProperties(properties);
    String instanceTemplateUrl;
    Operation operation;
    try {
        DaemonTaskHandler.message("Creating an instance template");
        operation = compute.instanceTemplates().insert(project, template).execute();
        instanceTemplateUrl = operation.getTargetLink();
        GoogleProviderUtils.waitOnGlobalOperation(compute, project, operation);
    } catch (IOException e) {
        throw new HalException(FATAL, "Failed to create instance template for " + settings.getArtifactId() + ": " + e.getMessage(), e);
    }
    String migName = getVersionedName(version);
    manager.setInstanceTemplate(instanceTemplateUrl);
    manager.setBaseInstanceName(migName);
    manager.setTargetSize(settings.getTargetSize());
    manager.setName(migName);
    try {
        DaemonTaskHandler.message("Deploying the instance group manager");
        operation = compute.instanceGroupManagers().insert(project, settings.getLocation(), manager).execute();
        GoogleProviderUtils.waitOnZoneOperation(compute, project, settings.getLocation(), operation);
    } catch (IOException e) {
        throw new HalException(FATAL, "Failed to create instance group to run artifact " + settings.getArtifactId() + ": " + e.getMessage(), e);
    }
    boolean ready = false;
    DaemonTaskHandler.message("Waiting for all instances to become healthy.");
    while (!ready) {
        Integer runningVersion = getRunningServiceDetails(details, runtimeSettings).getLatestEnabledVersion();
        ready = version.equals(runningVersion);
        DaemonTaskHandler.safeSleep(TimeUnit.SECONDS.toMillis(2));
    }
}
Also used : GoogleAccount(com.netflix.spinnaker.halyard.config.model.v1.providers.google.GoogleAccount) ServiceAccount(com.google.api.services.compute.model.ServiceAccount) InstanceGroupManager(com.google.api.services.compute.model.InstanceGroupManager) InstanceProperties(com.google.api.services.compute.model.InstanceProperties) HalException(com.netflix.spinnaker.halyard.core.error.v1.HalException) ServiceSettings(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ServiceSettings) Metadata(com.google.api.services.compute.model.Metadata) ArrayList(java.util.ArrayList) NetworkInterface(com.google.api.services.compute.model.NetworkInterface) AttachedDisk(com.google.api.services.compute.model.AttachedDisk) SpinnakerRuntimeSettings(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings) AttachedDiskInitializeParams(com.google.api.services.compute.model.AttachedDiskInitializeParams) Operation(com.google.api.services.compute.model.Operation) IOException(java.io.IOException) AccessConfig(com.google.api.services.compute.model.AccessConfig) RunningServiceDetails(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.RunningServiceDetails) Compute(com.google.api.services.compute.Compute) InstanceTemplate(com.google.api.services.compute.model.InstanceTemplate)

Aggregations

Operation (com.google.api.services.compute.model.Operation)94 Compute (com.google.api.services.compute.Compute)38 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)37 IOException (java.io.IOException)35 GcpResourceException (com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)23 CloudResource (com.sequenceiq.cloudbreak.cloud.model.CloudResource)21 Test (org.junit.Test)19 ArrayList (java.util.ArrayList)17 CloudInstance (com.sequenceiq.cloudbreak.cloud.model.CloudInstance)15 Instance (com.google.api.services.compute.model.Instance)14 AutoScalingData (org.apache.druid.indexing.overlord.autoscaling.AutoScalingData)14 GcpContext (com.sequenceiq.cloudbreak.cloud.gcp.context.GcpContext)12 InstanceGroupManagersListManagedInstancesResponse (com.google.api.services.compute.model.InstanceGroupManagersListManagedInstancesResponse)10 Location (com.sequenceiq.cloudbreak.cloud.model.Location)10 HashMap (java.util.HashMap)10 InstanceTemplate (com.sequenceiq.cloudbreak.cloud.model.InstanceTemplate)9 Disk (com.google.api.services.compute.model.Disk)8 InstanceGroupManagersDeleteInstancesRequest (com.google.api.services.compute.model.InstanceGroupManagersDeleteInstancesRequest)8 AuthenticatedContext (com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext)8 CloudContext (com.sequenceiq.cloudbreak.cloud.context.CloudContext)8