Search in sources :

Example 21 with Compute

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

the class RetryHttpInitializerWrapperTests method testRetryWaitTooLong.

public void testRetryWaitTooLong() throws Exception {
    TimeValue maxWaitTime = TimeValue.timeValueMillis(10);
    int maxRetryTimes = 50;
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, maxRetryTimes);
    JsonFactory jsonFactory = new JacksonFactory();
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper oneTimeSleeper = new MockSleeper() {

        @Override
        public void sleep(long millis) throws InterruptedException {
            Thread.sleep(maxWaitTime.getMillis());
            // important number, use this to get count
            super.sleep(0);
        }
    };
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, oneTimeSleeper, maxWaitTime);
    Compute client = new Compute.Builder(fakeTransport, jsonFactory, null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request1 = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    try {
        request1.execute();
        fail("Request should fail if wait too long");
    } catch (HttpResponseException e) {
        assertThat(e.getStatusCode(), equalTo(HttpStatusCodes.STATUS_CODE_SERVER_ERROR));
        // should only retry once.
        assertThat(oneTimeSleeper.getCount(), lessThan(maxRetryTimes));
    }
}
Also used : LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) JsonFactory(com.google.api.client.json.JsonFactory) MockGoogleCredential(com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) Compute(com.google.api.services.compute.Compute) TimeValue(org.elasticsearch.common.unit.TimeValue) MockSleeper(com.google.api.client.testing.util.MockSleeper)

Example 22 with Compute

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

the class RetryHttpInitializerWrapperTests method testSimpleRetry.

public void testSimpleRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3);
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueSeconds(5));
    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(3));
    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 23 with Compute

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

the class GoogleDistributedService method deleteVersion.

@Override
default void deleteVersion(AccountDeploymentDetails<GoogleAccount> details, ServiceSettings settings, Integer version) {
    String migName = getVersionedName(version);
    String zone = settings.getLocation();
    String project = details.getAccount().getProject();
    Compute compute = GoogleProviderUtils.getCompute(details);
    InstanceGroupManager mig;
    try {
        mig = compute.instanceGroupManagers().get(project, zone, migName).execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == 404) {
            return;
        } else {
            throw new HalException(FATAL, "Failed to load mig " + migName + " in " + zone, e);
        }
    } catch (IOException e) {
        throw new HalException(FATAL, "Failed to load mig " + migName + " in " + zone, e);
    }
    try {
        GoogleProviderUtils.waitOnZoneOperation(compute, project, zone, compute.instanceGroupManagers().delete(project, zone, migName).execute());
    } catch (IOException e) {
        throw new HalException(FATAL, "Failed to delete mig " + migName + " in " + zone, e);
    }
    String instanceTemplateName = mig.getInstanceTemplate();
    instanceTemplateName = instanceTemplateName.substring(instanceTemplateName.lastIndexOf('/') + 1);
    try {
        GoogleProviderUtils.waitOnGlobalOperation(compute, project, compute.instanceTemplates().delete(project, instanceTemplateName).execute());
    } catch (IOException e) {
        throw new HalException(FATAL, "Failed to delete template " + instanceTemplateName + " in " + zone, e);
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) InstanceGroupManager(com.google.api.services.compute.model.InstanceGroupManager) Compute(com.google.api.services.compute.Compute) HalException(com.netflix.spinnaker.halyard.core.error.v1.HalException) IOException(java.io.IOException)

Example 24 with Compute

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

the class GoogleDistributedService method getRunningServiceDetails.

@Override
default RunningServiceDetails getRunningServiceDetails(AccountDeploymentDetails<GoogleAccount> details, SpinnakerRuntimeSettings runtimeSettings) {
    ServiceSettings settings = runtimeSettings.getServiceSettings(getService());
    RunningServiceDetails result = new RunningServiceDetails();
    // All GCE load balancing is done via consul
    result.setLoadBalancer(new RunningServiceDetails.LoadBalancer().setExists(true));
    Compute compute = GoogleProviderUtils.getCompute(details);
    GoogleAccount account = details.getAccount();
    List<InstanceGroupManager> migs;
    try {
        migs = compute.instanceGroupManagers().list(account.getProject(), settings.getLocation()).execute().getItems();
        if (migs == null) {
            migs = Collections.emptyList();
        }
    } catch (IOException e) {
        throw new HalException(FATAL, "Failed to load MIGS: " + e.getMessage(), e);
    }
    boolean consulEnabled = getSidecars(runtimeSettings).stream().anyMatch(s -> s.getService().getType().equals(SpinnakerService.Type.CONSUL_CLIENT));
    Set<String> healthyConsulInstances = consulEnabled ? getConsulServerService().connectToPrimaryService(details, runtimeSettings).serviceHealth(getService().getCanonicalName(), true).stream().map(s -> s != null && s.getNode() != null ? s.getNode().getNodeName() : null).filter(Objects::nonNull).collect(Collectors.toSet()) : new HashSet<>();
    String serviceName = getService().getServiceName();
    migs = migs.stream().filter(ig -> ig.getName().startsWith(serviceName + "-v")).collect(Collectors.toList());
    Map<Integer, List<RunningServiceDetails.Instance>> instances = migs.stream().reduce(new HashMap<>(), (map, mig) -> {
        Names names = Names.parseName(mig.getName());
        Integer version = names.getSequence();
        List<RunningServiceDetails.Instance> computeInstances;
        try {
            List<ManagedInstance> managedInstances = compute.instanceGroupManagers().listManagedInstances(account.getProject(), settings.getLocation(), mig.getName()).execute().getManagedInstances();
            if (managedInstances == null) {
                managedInstances = new ArrayList<>();
            }
            computeInstances = managedInstances.stream().map(i -> {
                String instanceUrl = i.getInstance();
                String instanceStatus = i.getInstanceStatus();
                boolean running = instanceStatus != null && instanceStatus.equalsIgnoreCase("running");
                String instanceName = instanceUrl.substring(instanceUrl.lastIndexOf('/') + 1, instanceUrl.length());
                return new RunningServiceDetails.Instance().setId(instanceName).setLocation(settings.getLocation()).setRunning(running).setHealthy(!consulEnabled || healthyConsulInstances.contains(instanceName));
            }).collect(Collectors.toList());
        } catch (IOException e) {
            throw new HalException(FATAL, "Failed to load target pools for " + serviceName, e);
        }
        map.put(version, computeInstances);
        return map;
    }, (m1, m2) -> {
        m1.putAll(m2);
        return m1;
    });
    result.setInstances(instances);
    return result;
}
Also used : HalException(com.netflix.spinnaker.halyard.core.error.v1.HalException) ManagedInstance(com.google.api.services.compute.model.ManagedInstance) ServiceAccount(com.google.api.services.compute.model.ServiceAccount) DaemonTaskHandler(com.netflix.spinnaker.halyard.core.tasks.v1.DaemonTaskHandler) AttachedDisk(com.google.api.services.compute.model.AttachedDisk) SidecarService(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.SidecarService) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Names(com.netflix.frigga.Names) Map(java.util.Map) Provider(com.netflix.spinnaker.halyard.config.model.v1.node.Provider) URI(java.net.URI) SpinnakerService(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.SpinnakerService) Path(java.nio.file.Path) InstanceTemplate(com.google.api.services.compute.model.InstanceTemplate) ServiceInterfaceFactory(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ServiceInterfaceFactory) VaultConnectionDetails(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.VaultConnectionDetails) URIBuilder(org.apache.http.client.utils.URIBuilder) Set(java.util.Set) NetworkInterface(com.google.api.services.compute.model.NetworkInterface) Operation(com.google.api.services.compute.model.Operation) Collectors(java.util.stream.Collectors) AttachedDiskInitializeParams(com.google.api.services.compute.model.AttachedDiskInitializeParams) Objects(java.util.Objects) List(java.util.List) InstanceProperties(com.google.api.services.compute.model.InstanceProperties) VaultConfigMount(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.VaultConfigMount) FATAL(com.netflix.spinnaker.halyard.core.problem.v1.Problem.Severity.FATAL) GoogleDiskType(com.netflix.spinnaker.clouddriver.google.model.GoogleDiskType) Problem(com.netflix.spinnaker.halyard.core.problem.v1.Problem) DaemonTaskInterrupted(com.netflix.spinnaker.halyard.core.tasks.v1.DaemonTaskInterrupted) ServiceSettings(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ServiceSettings) Compute(com.google.api.services.compute.Compute) Metadata(com.google.api.services.compute.model.Metadata) VaultConfigMountSet(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.VaultConfigMountSet) HashMap(java.util.HashMap) ArtifactService(com.netflix.spinnaker.halyard.deploy.services.v1.ArtifactService) RunningServiceDetails(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.RunningServiceDetails) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AccountDeploymentDetails(com.netflix.spinnaker.halyard.deploy.deployment.v1.AccountDeploymentDetails) AccessConfig(com.google.api.services.compute.model.AccessConfig) GoogleAccount(com.netflix.spinnaker.halyard.config.model.v1.providers.google.GoogleAccount) ResolvedConfiguration(com.netflix.spinnaker.halyard.deploy.services.v1.GenerateService.ResolvedConfiguration) RandomStringUtils(org.apache.commons.lang.RandomStringUtils) InstanceGroupManager(com.google.api.services.compute.model.InstanceGroupManager) IOException(java.io.IOException) SpinnakerRuntimeSettings(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings) VaultServerService(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.VaultServerService) TimeUnit(java.util.concurrent.TimeUnit) GCEUtil(com.netflix.spinnaker.clouddriver.google.deploy.GCEUtil) Profile(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.Profile) Paths(java.nio.file.Paths) DistributedService(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.DistributedService) ConfigSource(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ConfigSource) Collections(java.util.Collections) GoogleAccount(com.netflix.spinnaker.halyard.config.model.v1.providers.google.GoogleAccount) ManagedInstance(com.google.api.services.compute.model.ManagedInstance) HalException(com.netflix.spinnaker.halyard.core.error.v1.HalException) Names(com.netflix.frigga.Names) RunningServiceDetails(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.RunningServiceDetails) List(java.util.List) ArrayList(java.util.ArrayList) InstanceGroupManager(com.google.api.services.compute.model.InstanceGroupManager) ServiceSettings(com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ServiceSettings) IOException(java.io.IOException) Compute(com.google.api.services.compute.Compute) Objects(java.util.Objects) ManagedInstance(com.google.api.services.compute.model.ManagedInstance)

Example 25 with Compute

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

the class GoogleProviderUtils method ensureSpinnakerNetworkExists.

static String ensureSpinnakerNetworkExists(AccountDeploymentDetails<GoogleAccount> details) {
    String networkName = getNetworkName();
    String project = details.getAccount().getProject();
    Compute compute = getCompute(details);
    boolean exists = true;
    try {
        compute.networks().get(project, networkName).execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == 404) {
            exists = false;
        } else {
            throw new HalException(FATAL, "Google error encountered retrieving network: " + e.getMessage(), e);
        }
    } catch (IOException e) {
        throw new HalException(FATAL, "Failed to check if spinnaker network exists: " + e.getMessage(), e);
    }
    if (!exists) {
        String networkUrl;
        Network network = new Network().setAutoCreateSubnetworks(true).setName(networkName).setDescription("Spinnaker network auto-created by Halyard");
        try {
            DaemonTaskHandler.message("Creating a spinnaker network...");
            Operation operation = compute.networks().insert(project, network).execute();
            networkUrl = operation.getTargetLink();
            GoogleProviderUtils.waitOnGlobalOperation(compute, project, operation);
        } catch (IOException e) {
            throw new HalException(FATAL, "Failed to create Spinnaker network: " + e.getMessage(), e);
        }
        Firewall.Allowed allowSsh = new Firewall.Allowed().setPorts(Collections.singletonList("22")).setIPProtocol("tcp");
        Firewall firewallSsh = new Firewall().setNetwork(networkUrl).setAllowed(Collections.singletonList(allowSsh)).setName(networkName + "-allow-ssh").setSourceRanges(Collections.singletonList("0.0.0.0/0"));
        Firewall.Allowed allowInternalTcp = new Firewall.Allowed().setPorts(Collections.singletonList("1-65535")).setIPProtocol("tcp");
        Firewall.Allowed allowInternalUdp = new Firewall.Allowed().setPorts(Collections.singletonList("1-65535")).setIPProtocol("udp");
        Firewall.Allowed allowInternalIcmp = new Firewall.Allowed().setIPProtocol("icmp");
        List<Firewall.Allowed> allowInteral = new ArrayList<>();
        allowInteral.add(allowInternalTcp);
        allowInteral.add(allowInternalUdp);
        allowInteral.add(allowInternalIcmp);
        Firewall firewallInternal = new Firewall().setNetwork(networkUrl).setAllowed(allowInteral).setName(networkName + "-allow-internal").setSourceRanges(Collections.singletonList("10.0.0.0/8"));
        try {
            DaemonTaskHandler.message("Adding firewall rules...");
            compute.firewalls().insert(project, firewallSsh).execute();
            compute.firewalls().insert(project, firewallInternal).execute();
        } catch (IOException e) {
            throw new HalException(FATAL, "Failed to create Firewall rule network: " + e.getMessage(), e);
        }
    }
    return String.format("projects/%s/global/networks/%s", project, networkName);
}
Also used : HalException(com.netflix.spinnaker.halyard.core.error.v1.HalException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Compute(com.google.api.services.compute.Compute)

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