Search in sources :

Example 1 with NetworkInterface

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

the class ComputeEngineSample method startInstance.

// [END list_instances]
// [START create_instances]
public static Operation startInstance(Compute compute, String instanceName) throws IOException {
    System.out.println("================== Starting New Instance ==================");
    // Create VM Instance object with the required properties.
    Instance instance = new Instance();
    instance.setName(instanceName);
    instance.setMachineType("https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/zones/" + ZONE_NAME + "/machineTypes/n1-standard-1");
    // Add Network Interface to be used by VM Instance.
    NetworkInterface ifc = new NetworkInterface();
    ifc.setNetwork("https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/global/networks/default");
    List<AccessConfig> configs = new ArrayList<>();
    AccessConfig config = new AccessConfig();
    config.setType(NETWORK_INTERFACE_CONFIG);
    config.setName(NETWORK_ACCESS_CONFIG);
    configs.add(config);
    ifc.setAccessConfigs(configs);
    instance.setNetworkInterfaces(Collections.singletonList(ifc));
    // Add attached Persistent Disk to be used by VM Instance.
    AttachedDisk disk = new AttachedDisk();
    disk.setBoot(true);
    disk.setAutoDelete(true);
    disk.setType("PERSISTENT");
    AttachedDiskInitializeParams params = new AttachedDiskInitializeParams();
    // Assign the Persistent Disk the same name as the VM Instance.
    params.setDiskName(instanceName);
    // Specify the source operating system machine image to be used by the VM Instance.
    params.setSourceImage(SOURCE_IMAGE_PREFIX + SOURCE_IMAGE_PATH);
    // Specify the disk type as Standard Persistent Disk
    params.setDiskType("https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/zones/" + ZONE_NAME + "/diskTypes/pd-standard");
    disk.setInitializeParams(params);
    instance.setDisks(Collections.singletonList(disk));
    // Initialize the service account to be used by the VM Instance and set the API access scopes.
    ServiceAccount account = new ServiceAccount();
    account.setEmail("default");
    List<String> scopes = new ArrayList<>();
    scopes.add("https://www.googleapis.com/auth/devstorage.full_control");
    scopes.add("https://www.googleapis.com/auth/compute");
    account.setScopes(scopes);
    instance.setServiceAccounts(Collections.singletonList(account));
    // Optional - Add a startup script to be used by the VM Instance.
    Metadata meta = new Metadata();
    Metadata.Items item = new Metadata.Items();
    item.setKey("startup-script-url");
    // If you put a script called "vm-startup.sh" in this Google Cloud Storage
    // bucket, it will execute on VM startup.  This assumes you've created a
    // bucket named the same as your PROJECT_ID.
    // For info on creating buckets see: https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets
    item.setValue("gs://" + PROJECT_ID + "/vm-startup.sh");
    meta.setItems(Collections.singletonList(item));
    instance.setMetadata(meta);
    System.out.println(instance.toPrettyString());
    Compute.Instances.Insert insert = compute.instances().insert(PROJECT_ID, ZONE_NAME, instance);
    return insert.execute();
}
Also used : ServiceAccount(com.google.api.services.compute.model.ServiceAccount) Instance(com.google.api.services.compute.model.Instance) ArrayList(java.util.ArrayList) Metadata(com.google.api.services.compute.model.Metadata) NetworkInterface(com.google.api.services.compute.model.NetworkInterface) AttachedDisk(com.google.api.services.compute.model.AttachedDisk) AttachedDiskInitializeParams(com.google.api.services.compute.model.AttachedDiskInitializeParams) AccessConfig(com.google.api.services.compute.model.AccessConfig)

Example 2 with NetworkInterface

use of com.google.api.services.compute.model.NetworkInterface 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)

Example 3 with NetworkInterface

use of com.google.api.services.compute.model.NetworkInterface in project photon-model by vmware.

the class GCPTestUtil method createInstanceTemplate.

/**
 * Create an instance template for later provisioning.
 * @param userEmail The service account's client email.
 * @param projectId The project id.
 * @param zoneId The zone id.
 * @param scopes The priority scopes.
 * @return The instance template.
 */
private static Instance createInstanceTemplate(String userEmail, String projectId, String zoneId, List<String> scopes) {
    Instance instance = new Instance();
    instance.setMachineType(String.format(ENUMERATION_TEST_MACHINE_TYPE, projectId, zoneId));
    NetworkInterface ifc = new NetworkInterface();
    ifc.setNetwork(String.format(NETWORK_INTERFACE, projectId));
    List<AccessConfig> configs = new ArrayList<>();
    AccessConfig config = new AccessConfig();
    config.setType(NETWORK_INTERFACE_CONFIG);
    config.setName(NETWORK_ACCESS_CONFIG);
    configs.add(config);
    ifc.setAccessConfigs(configs);
    instance.setNetworkInterfaces(Collections.singletonList(ifc));
    AttachedDisk disk = new AttachedDisk();
    disk.setBoot(true);
    disk.setAutoDelete(true);
    disk.setType(DISK_TYPE_PERSISTENT);
    AttachedDiskInitializeParams params = new AttachedDiskInitializeParams();
    params.setSourceImage(SOURCE_IMAGE);
    params.setDiskType(String.format(DISK_TYPE, projectId, zoneId));
    disk.setInitializeParams(params);
    instance.setDisks(Collections.singletonList(disk));
    ServiceAccount account = new ServiceAccount();
    account.setEmail(userEmail);
    account.setScopes(scopes);
    instance.setServiceAccounts(Collections.singletonList(account));
    return instance;
}
Also used : ServiceAccount(com.google.api.services.compute.model.ServiceAccount) Instance(com.google.api.services.compute.model.Instance) ArrayList(java.util.ArrayList) NetworkInterface(com.google.api.services.compute.model.NetworkInterface) AttachedDisk(com.google.api.services.compute.model.AttachedDisk) AttachedDiskInitializeParams(com.google.api.services.compute.model.AttachedDiskInitializeParams) AccessConfig(com.google.api.services.compute.model.AccessConfig)

Example 4 with NetworkInterface

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

the class GcpInstanceResourceBuilder method getNetworkInterface.

private List<NetworkInterface> getNetworkInterface(Iterable<CloudResource> networkResources, Iterable<CloudResource> computeResources, Region region, Group group, Compute compute, String projectId, boolean noPublicIp) throws IOException {
    NetworkInterface networkInterface = new NetworkInterface();
    List<CloudResource> subnet = filterResourcesByType(networkResources, ResourceType.GCP_SUBNET);
    String networkName = subnet.isEmpty() ? filterResourcesByType(networkResources, ResourceType.GCP_NETWORK).get(0).getName() : subnet.get(0).getName();
    networkInterface.setName(networkName);
    if (!noPublicIp) {
        AccessConfig accessConfig = new AccessConfig();
        accessConfig.setName(networkName);
        accessConfig.setType("ONE_TO_ONE_NAT");
        List<CloudResource> reservedIp = filterResourcesByType(computeResources, ResourceType.GCP_RESERVED_IP);
        if (InstanceGroupType.GATEWAY == group.getType() && !reservedIp.isEmpty()) {
            Addresses.Get getReservedIp = compute.addresses().get(projectId, region.value(), reservedIp.get(0).getName());
            accessConfig.setNatIP(getReservedIp.execute().getAddress());
        }
        networkInterface.setAccessConfigs(Collections.singletonList(accessConfig));
    }
    if (subnet.isEmpty()) {
        networkInterface.setNetwork(String.format("https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s", projectId, networkName));
    } else {
        networkInterface.setSubnetwork(String.format("https://www.googleapis.com/compute/v1/projects/%s/regions/%s/subnetworks/%s", projectId, region.value(), networkName));
    }
    return Collections.singletonList(networkInterface);
}
Also used : Addresses(com.google.api.services.compute.Compute.Addresses) NetworkInterface(com.google.api.services.compute.model.NetworkInterface) CloudResource(com.sequenceiq.cloudbreak.cloud.model.CloudResource) AccessConfig(com.google.api.services.compute.model.AccessConfig)

Example 5 with NetworkInterface

use of com.google.api.services.compute.model.NetworkInterface in project platformlayer by platformlayer.

the class GoogleComputeClient method findPublicIps.

public static List<String> findPublicIps(Instance instance) {
    List<String> ips = Lists.newArrayList();
    List<NetworkInterface> networkInterfaces = instance.getNetworkInterfaces();
    if (networkInterfaces == null) {
        networkInterfaces = Collections.emptyList();
    }
    for (NetworkInterface networkInterface : networkInterfaces) {
        List<AccessConfig> accessConfigList = networkInterface.getAccessConfigs();
        if (accessConfigList == null) {
            continue;
        }
        for (AccessConfig accessConfig : accessConfigList) {
            if (!Objects.equal(accessConfig.getType(), "ONE_TO_ONE_NAT")) {
                throw new IllegalStateException();
            }
            String natIp = accessConfig.getNatIP();
            if (!Strings.isNullOrEmpty(natIp)) {
                ips.add(natIp);
            }
        }
    }
    return ips;
}
Also used : NetworkInterface(com.google.api.services.compute.model.NetworkInterface) AccessConfig(com.google.api.services.compute.model.AccessConfig)

Aggregations

NetworkInterface (com.google.api.services.compute.model.NetworkInterface)9 AccessConfig (com.google.api.services.compute.model.AccessConfig)7 Instance (com.google.api.services.compute.model.Instance)6 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 AttachedDisk (com.google.api.services.compute.model.AttachedDisk)3 AttachedDiskInitializeParams (com.google.api.services.compute.model.AttachedDiskInitializeParams)3 Metadata (com.google.api.services.compute.model.Metadata)3 ServiceAccount (com.google.api.services.compute.model.ServiceAccount)3 Compute (com.google.api.services.compute.Compute)2 ManagedInstance (com.google.api.services.compute.model.ManagedInstance)2 Operation (com.google.api.services.compute.model.Operation)2 Addresses (com.google.api.services.compute.Compute.Addresses)1 Image (com.google.api.services.compute.model.Image)1 InstanceGroupManager (com.google.api.services.compute.model.InstanceGroupManager)1 InstanceList (com.google.api.services.compute.model.InstanceList)1 InstanceProperties (com.google.api.services.compute.model.InstanceProperties)1 InstanceTemplate (com.google.api.services.compute.model.InstanceTemplate)1 MachineType (com.google.api.services.compute.model.MachineType)1 Items (com.google.api.services.compute.model.Metadata.Items)1