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

The following examples show how to use com.google.api.services.compute.model.NetworkInterface. 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: GcpNetworkInterfaceProviderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testProvideShouldReturnsTheNetworkInterfaces() throws IOException {
    InstanceList gcpInstancesFirstPage = createGcpInstancesFirstPage();
    InstanceList gcpInstancesSecondPage = createGcpInstancesSecondPage();
    InstanceList gcpInstancesThirdPage = createGcpInstancesThirdPage();

    when(computeInstancesMock.execute())
            .thenReturn(gcpInstancesFirstPage)
            .thenReturn(gcpInstancesSecondPage)
            .thenReturn(gcpInstancesThirdPage);

    Map<String, Optional<NetworkInterface>> actual = underTest.provide(authenticatedContext, instances);

    assertEquals(3, actual.size());
    assertEquals(actual.get(INSTANCE_NAME_1), getNetworkForInstance(gcpInstancesFirstPage, INSTANCE_NAME_1));
    assertEquals(actual.get(INSTANCE_NAME_2), getNetworkForInstance(gcpInstancesSecondPage, INSTANCE_NAME_2));
    assertEquals(actual.get(INSTANCE_NAME_3), getNetworkForInstance(gcpInstancesThirdPage, INSTANCE_NAME_3));
}
 
Example #2
Source File: GcpMetadataCollector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public List<CloudVmMetaDataStatus> collect(AuthenticatedContext authenticatedContext, List<CloudResource> resources, List<CloudInstance> vms,
        List<CloudInstance> knownInstances) {

    List<CloudVmMetaDataStatus> instanceMetaData = new ArrayList<>();
    Map<String, CloudResource> instanceNameMap = groupByInstanceName(resources);
    Map<Long, CloudResource> privateIdMap = groupByPrivateId(resources);
    Map<String, Optional<NetworkInterface>> networkInterfacesByInstance = getNetworkInterfaceByInstance(authenticatedContext, instanceNameMap);

    for (CloudInstance cloudInstance : vms) {
        String instanceId = cloudInstance.getInstanceId();
        CloudResource cloudResource;
        cloudResource = instanceId != null ? instanceNameMap.get(instanceId) : privateIdMap.get(cloudInstance.getTemplate().getPrivateId());
        CloudVmMetaDataStatus cloudVmMetaDataStatus = getCloudVmMetaDataStatus(cloudResource, cloudInstance, networkInterfacesByInstance);
        instanceMetaData.add(cloudVmMetaDataStatus);
    }
    return instanceMetaData;
}
 
Example #3
Source File: GcpMetadataCollectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCollectShouldReturnsWithTheVmMetadataListWithoutError() {
    List<CloudInstance> vms = createVms();
    Map<String, Optional<NetworkInterface>> networkInterfaces = createNetworkInterfaces();
    when(gcpNetworkInterfaceProvider.provide(eq(authenticatedContext), any())).thenReturn(networkInterfaces);

    List<CloudVmMetaDataStatus> actual = underTest.collect(authenticatedContext, resources, vms, KNOWN_INSTANCES);

    CloudVmMetaDataStatus vm1 = getVm(INSTANCE_NAME_1, actual);
    assertEquals(InstanceStatus.CREATED, vm1.getCloudVmInstanceStatus().getStatus());
    assertEquals(PUBLIC_IP, vm1.getMetaData().getPublicIp());
    assertEquals(PRIVATE_IP, vm1.getMetaData().getPrivateIp());

    CloudVmMetaDataStatus vm2 = getVm(INSTANCE_NAME_2, actual);
    assertEquals(InstanceStatus.CREATED, vm2.getCloudVmInstanceStatus().getStatus());
    assertEquals(PUBLIC_IP, vm2.getMetaData().getPublicIp());
    assertEquals(PRIVATE_IP, vm2.getMetaData().getPrivateIp());

    CloudVmMetaDataStatus vm3 = getVm(INSTANCE_NAME_3, actual);
    assertEquals(InstanceStatus.CREATED, vm3.getCloudVmInstanceStatus().getStatus());
    assertEquals(PUBLIC_IP, vm3.getMetaData().getPublicIp());
    assertEquals(PRIVATE_IP, vm3.getMetaData().getPrivateIp());
}
 
Example #4
Source File: GcpMetadataCollectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCollectShouldReturnsWithVmsInUnknownStatusWhenThereAreNoNetworkInterfaceFound() {
    List<CloudInstance> vms = createVms();
    Map<String, Optional<NetworkInterface>> networkInterfaces = createEmptyNetworkInterfaces();
    when(gcpNetworkInterfaceProvider.provide(eq(authenticatedContext), any())).thenReturn(networkInterfaces);

    List<CloudVmMetaDataStatus> actual = underTest.collect(authenticatedContext, resources, vms, KNOWN_INSTANCES);

    CloudVmMetaDataStatus vm1 = getVm(INSTANCE_NAME_1, actual);
    assertEquals(InstanceStatus.UNKNOWN, vm1.getCloudVmInstanceStatus().getStatus());
    assertNull(vm1.getMetaData().getPublicIp());
    assertNull(vm1.getMetaData().getPrivateIp());

    CloudVmMetaDataStatus vm2 = getVm(INSTANCE_NAME_2, actual);
    assertEquals(InstanceStatus.UNKNOWN, vm2.getCloudVmInstanceStatus().getStatus());
    assertNull(vm2.getMetaData().getPublicIp());
    assertNull(vm2.getMetaData().getPrivateIp());

    CloudVmMetaDataStatus vm3 = getVm(INSTANCE_NAME_3, actual);
    assertEquals(InstanceStatus.UNKNOWN, vm3.getCloudVmInstanceStatus().getStatus());
    assertNull(vm3.getMetaData().getPublicIp());
    assertNull(vm3.getMetaData().getPrivateIp());
}
 
Example #5
Source File: GcpMetadataCollectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCollectShouldReturnsWithVmsInTerminatedStatusWhenThereAreMoVmFound() {
    List<CloudInstance> vms = createVmsWithOtherIds();
    Map<String, Optional<NetworkInterface>> networkInterfaces = createEmptyNetworkInterfaces();
    when(gcpNetworkInterfaceProvider.provide(eq(authenticatedContext), any())).thenReturn(networkInterfaces);

    List<CloudVmMetaDataStatus> actual = underTest.collect(authenticatedContext, resources, vms, KNOWN_INSTANCES);

    CloudVmMetaDataStatus vm1 = getVm(INSTANCE_NAME_4, actual);
    assertEquals(InstanceStatus.TERMINATED, vm1.getCloudVmInstanceStatus().getStatus());
    assertNull(vm1.getMetaData().getPublicIp());
    assertNull(vm1.getMetaData().getPrivateIp());

    CloudVmMetaDataStatus vm2 = getVm(INSTANCE_NAME_5, actual);
    assertEquals(InstanceStatus.TERMINATED, vm2.getCloudVmInstanceStatus().getStatus());
    assertNull(vm2.getMetaData().getPublicIp());
    assertNull(vm2.getMetaData().getPrivateIp());

    CloudVmMetaDataStatus vm3 = getVm(INSTANCE_NAME_6, actual);
    assertEquals(InstanceStatus.TERMINATED, vm3.getCloudVmInstanceStatus().getStatus());
    assertNull(vm3.getMetaData().getPublicIp());
    assertNull(vm3.getMetaData().getPrivateIp());
}
 
Example #6
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private List<NetworkInterface> getNetworkInterface(GcpContext context, Iterable<CloudResource> computeResources, Group group, CloudStack stack)
        throws IOException {
    boolean noPublicIp = context.getNoPublicIp();
    String projectId = context.getProjectId();
    Location location = context.getLocation();
    Compute compute = context.getCompute();

    NetworkInterface networkInterface = new NetworkInterface();
    List<CloudResource> subnet = filterResourcesByType(context.getNetworkResources(), ResourceType.GCP_SUBNET);
    String networkName = subnet.isEmpty() ? filterResourcesByType(context.getNetworkResources(),
            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, location.getRegion().value(), reservedIp.get(0).getName());
            accessConfig.setNatIP(getReservedIp.execute().getAddress());
        }
        networkInterface.setAccessConfigs(singletonList(accessConfig));
    }
    prepareNetworkAndSubnet(projectId, location.getRegion(), stack.getNetwork(), networkInterface, subnet, networkName);
    return singletonList(networkInterface);
}
 
Example #7
Source File: GcpNetworkInterfaceProviderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvideShouldReturnsMapWithoutNetworkWhenTheGcpThrowsException() throws IOException {
    when(computeInstancesMock.execute()).thenThrow(new IOException("Error happened on GCP side."));

    Map<String, Optional<NetworkInterface>> actual = underTest.provide(authenticatedContext, instances);

    assertEquals(3, actual.size());
    assertFalse(actual.get(INSTANCE_NAME_1).isPresent());
    assertFalse(actual.get(INSTANCE_NAME_2).isPresent());
    assertFalse(actual.get(INSTANCE_NAME_3).isPresent());
}
 
Example #8
Source File: GcpNetworkInterfaceProviderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvideShouldReturnsMapWithoutNetworkWhenTheThereAreNoResponseFromGcp() throws IOException {
    when(computeInstancesMock.execute()).thenReturn(new InstanceList());

    Map<String, Optional<NetworkInterface>> actual = underTest.provide(authenticatedContext, instances);

    assertEquals(3, actual.size());
    assertFalse(actual.get(INSTANCE_NAME_1).isPresent());
    assertFalse(actual.get(INSTANCE_NAME_2).isPresent());
    assertFalse(actual.get(INSTANCE_NAME_3).isPresent());
}
 
Example #9
Source File: GcpNetworkInterfaceProviderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvideShouldReturnsMapWithoutNetworkWhenTheThereAreMissingNodes() throws IOException {
    InstanceList gcpInstances = createGcpInstancesWithMissingNode();
    when(computeInstancesMock.execute()).thenReturn(gcpInstances);

    Map<String, Optional<NetworkInterface>> actual = underTest.provide(authenticatedContext, instances);

    assertEquals(3, actual.size());
    assertEquals(actual.get(INSTANCE_NAME_1), getNetworkForInstance(gcpInstances, INSTANCE_NAME_1));
    assertEquals(actual.get(INSTANCE_NAME_2), getNetworkForInstance(gcpInstances, INSTANCE_NAME_2));
    assertEquals(actual.get(INSTANCE_NAME_3), getNetworkForInstance(gcpInstances, INSTANCE_NAME_3));
}
 
Example #10
Source File: GcpMetadataCollectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Optional<NetworkInterface> createNetworkInterface() {
    NetworkInterface networkInterface = new NetworkInterface();
    AccessConfig accessConfig = new AccessConfig();
    networkInterface.setNetworkIP(PRIVATE_IP);
    accessConfig.setNatIP(PUBLIC_IP);
    networkInterface.setAccessConfigs(List.of(accessConfig));
    return Optional.of(networkInterface);
}
 
Example #11
Source File: GcpMetadataCollectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Map<String, Optional<NetworkInterface>> createNetworkInterfaces() {
    Optional<NetworkInterface> networkInterface = createNetworkInterface();
    return Map.of(
            INSTANCE_NAME_1, networkInterface,
            INSTANCE_NAME_2, networkInterface,
            INSTANCE_NAME_3, networkInterface);
}
 
Example #12
Source File: GcpInstanceResourceBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void prepareNetworkAndSubnet(String projectId, Region region, Network network, NetworkInterface networkInterface,
        List<CloudResource> subnet, String networkName) {
    if (isNotEmpty(getSharedProjectId(network))) {
        networkInterface.setNetwork(getNetworkUrl(getSharedProjectId(network), getCustomNetworkId(network)));
        networkInterface.setSubnetwork(getSubnetUrl(getSharedProjectId(network), region.value(), getSubnetId(network)));
    } else {
        if (subnet.isEmpty()) {
            networkInterface.setNetwork(getNetworkUrl(projectId, networkName));
        } else {
            networkInterface.setSubnetwork(getSubnetUrl(projectId, region.value(), networkName));
        }
    }
}
 
Example #13
Source File: GcpMetadataCollector.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Map<String, Optional<NetworkInterface>> getNetworkInterfaceByInstance(AuthenticatedContext authenticatedContext,
        Map<String, CloudResource> instanceNameMap) {
    return gcpNetworkInterfaceProvider.provide(authenticatedContext, new ArrayList<>(instanceNameMap.values()));
}
 
Example #14
Source File: GcpMetadataCollectorTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Map<String, Optional<NetworkInterface>> createEmptyNetworkInterfaces() {
    return Map.of(
            INSTANCE_NAME_1, Optional.empty(),
            INSTANCE_NAME_2, Optional.empty(),
            INSTANCE_NAME_3, Optional.empty());
}
 
Example #15
Source File: GcpNetworkInterfaceProvider.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Function<CloudResource, Optional<NetworkInterface>> getOptionalNetworkInterfaces(List<Instance> gcpInstances) {
    return instance -> gcpInstances.stream()
            .filter(gcpInstance -> instance.getName().equals(gcpInstance.getName()))
            .findFirst()
            .map(gcpInstance -> gcpInstance.getNetworkInterfaces().get(0));
}
 
Example #16
Source File: GcpNetworkInterfaceProvider.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Map<String, Optional<NetworkInterface>> getNetworkMap(List<Instance> gcpInstances, List<CloudResource> instances) {
    return instances.stream().collect(Collectors.toMap(CloudResource::getName, getOptionalNetworkInterfaces(gcpInstances)));
}
 
Example #17
Source File: GcpNetworkInterfaceProvider.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
Map<String, Optional<NetworkInterface>> provide(AuthenticatedContext authenticatedContext, List<CloudResource> instances) {
    String instanceNamePrefix = getInstanceNamePrefix(instances);
    List<Instance> gcpInstances = getInstances(authenticatedContext, instanceNamePrefix);
    return getNetworkMap(gcpInstances, instances);
}
 
Example #18
Source File: ComputeEngineSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
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(
      String.format(
          "https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/e2-standard-1",
          PROJECT_ID, ZONE_NAME));
  // Add Network Interface to be used by VM Instance.
  NetworkInterface ifc = new NetworkInterface();
  ifc.setNetwork(
      String.format(
          "https://www.googleapis.com/compute/v1/projects/%s/global/networks/default",
          PROJECT_ID));
  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(
      String.format(
          "https://www.googleapis.com/compute/v1/projects/%s/zones/%s/diskTypes/pd-standard",
          PROJECT_ID, ZONE_NAME));
  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(String.format("gs://%s/vm-startup.sh", PROJECT_ID));
  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();
}
 
Example #19
Source File: GcpNetworkInterfaceProviderTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Instance createInstance(String name) {
    Instance instance = new Instance();
    instance.setName(name);
    instance.setNetworkInterfaces(List.of(new NetworkInterface()));
    return instance;
}
 
Example #20
Source File: GcpNetworkInterfaceProviderTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Optional<NetworkInterface> getNetworkForInstance(InstanceList gcpInstances, String instanceName) {
    return gcpInstances.getItems().stream()
            .filter(instance -> instance.getName().equals(instanceName))
            .findFirst()
            .map(gcpInstance -> gcpInstance.getNetworkInterfaces().get(0));
}