Search in sources :

Example 1 with Compute

use of com.google.api.services.compute.Compute in project elasticsearch by elastic.

the class RetryHttpInitializerWrapperTests method testIOExceptionRetry.

public void testIOExceptionRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1, true);
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueMillis(500));
    Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    HttpResponse response = request.execute();
    assertThat(mockSleeper.getCount(), equalTo(1));
    assertThat(response.getStatusCode(), equalTo(200));
}
Also used : LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Compute(com.google.api.services.compute.Compute) MockGoogleCredential(com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) HttpResponse(com.google.api.client.http.HttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockSleeper(com.google.api.client.testing.util.MockSleeper)

Example 2 with Compute

use of com.google.api.services.compute.Compute 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.
        GoogleCredential credential = GoogleCredential.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);
        }
        // Create Compute Engine object for listing instances.
        Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, credential).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 : Compute(com.google.api.services.compute.Compute) ArrayList(java.util.ArrayList) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) Operation(com.google.api.services.compute.model.Operation) IOException(java.io.IOException)

Example 3 with Compute

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

the class GoogleProviderUtils method defaultServiceAccount.

static String defaultServiceAccount(AccountDeploymentDetails<GoogleAccount> details) {
    GoogleAccount account = details.getAccount();
    String project = account.getProject();
    Compute compute = getCompute(details);
    try {
        return compute.projects().get(project).execute().getDefaultServiceAccount();
    } catch (IOException e) {
        throw new HalException(FATAL, "Unable to get default compute service account");
    }
}
Also used : GoogleAccount(com.netflix.spinnaker.halyard.config.model.v1.providers.google.GoogleAccount) Compute(com.google.api.services.compute.Compute) HalException(com.netflix.spinnaker.halyard.core.error.v1.HalException) IOException(java.io.IOException)

Example 4 with Compute

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

the class GoogleProviderUtils method getInstanceIp.

static String getInstanceIp(AccountDeploymentDetails<GoogleAccount> details, String instanceName) {
    Compute compute = getCompute(details);
    Instance instance = null;
    try {
        instance = compute.instances().get(details.getAccount().getProject(), "us-central1-f", instanceName).execute();
    } catch (IOException e) {
        throw new HalException(FATAL, "Unable to get instance " + instanceName);
    }
    return instance.getNetworkInterfaces().stream().map(i -> i.getAccessConfigs().stream().map(AccessConfig::getNatIP).filter(ip -> !StringUtils.isEmpty(ip)).findFirst()).filter(Optional::isPresent).map(Optional::get).findFirst().orElseThrow(() -> new HalException(FATAL, "No public IP associated with" + instanceName));
}
Also used : Optional(java.util.Optional) Compute(com.google.api.services.compute.Compute) HalException(com.netflix.spinnaker.halyard.core.error.v1.HalException) IOException(java.io.IOException)

Example 5 with Compute

use of com.google.api.services.compute.Compute 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).setDiskStorageType(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) {
        ready = getRunningServiceDetails(details, runtimeSettings).getLatestEnabledVersion() == version;
        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

Compute (com.google.api.services.compute.Compute)43 IOException (java.io.IOException)26 Operation (com.google.api.services.compute.model.Operation)16 ArrayList (java.util.ArrayList)13 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)12 HashMap (java.util.HashMap)9 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)8 GeneralSecurityException (java.security.GeneralSecurityException)8 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)7 GcpResourceException (com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)7 Instance (com.google.api.services.compute.model.Instance)6 HalException (com.netflix.spinnaker.halyard.core.error.v1.HalException)6 CloudCredential (com.sequenceiq.cloudbreak.cloud.model.CloudCredential)6 GoogleNetHttpTransport (com.google.api.client.googleapis.javanet.GoogleNetHttpTransport)4 HttpRequest (com.google.api.client.http.HttpRequest)4 HttpTransport (com.google.api.client.http.HttpTransport)4 AttachedDisk (com.google.api.services.compute.model.AttachedDisk)4 ManagedInstance (com.google.api.services.compute.model.ManagedInstance)4 NetworkInterface (com.google.api.services.compute.model.NetworkInterface)4 Subnetwork (com.google.api.services.compute.model.Subnetwork)4