本文整理汇总了Java中com.google.api.services.compute.model.Instance类的典型用法代码示例。如果您正苦于以下问题:Java Instance类的具体用法?Java Instance怎么用?Java Instance使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Instance类属于com.google.api.services.compute.model包,在下文中一共展示了Instance类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getPropertyValue
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
@Override
protected String getPropertyValue(Instance instance, Disk bootDisk) {
String creationTimestampStr = null;
try {
creationTimestampStr = instance.getCreationTimestamp();
Date creationTimestamp = null;
if (creationTimestampStr != null) {
creationTimestamp = Dates.getDateFromTimestamp(creationTimestampStr);
}
if (creationTimestamp != null) {
// TODO(duftler): Use appropriate date formatting.
return creationTimestamp.toString();
}
} catch (IllegalArgumentException e) {
LOG.info("Problem parsing creation timestamp '{}' of instance '{}': {}",
creationTimestampStr, instance.getName(), e.getMessage());
}
return null;
}
示例2: getPrivateIpAddress
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* Returns the private IP address of the specified Google instance.
*
* @param instance the instance
* @return the private IP address of the specified Google instance
* @throws IllegalArgumentException if the instance does not have a valid private IP address
*/
private static InetAddress getPrivateIpAddress(Instance instance) {
Preconditions.checkNotNull(instance, "instance is null");
List<NetworkInterface> networkInterfaceList = instance.getNetworkInterfaces();
if (networkInterfaceList == null || networkInterfaceList.isEmpty()) {
throw new IllegalArgumentException("No network interfaces found for instance '" + instance.getName() + "'.");
} else {
try {
return InetAddress.getByName(networkInterfaceList.get(0).getNetworkIP());
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid private IP address", e);
}
}
}
示例3: getBootDisk
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
protected Disk getBootDisk(Instance instance)
{
AttachedDisk bootDisk = Lists.newArrayList(Iterables.filter(instance.getDisks(), new Predicate<AttachedDisk>()
{
@Override
public boolean apply(@Nullable AttachedDisk input)
{
return input != null && input.getBoot();
}
})).get(0);
//https://www.googleapis.com/compute/v1/projects/poised-bot-553/zones/us-central1-a/disks/f1-micro-test
//persistent-disk-0
// I removed this constraint because of a possible bug in the Google Compute Engine, since it is not setting the correct name of the disk.
// This issue is also occurring at the google client. Above we have an example of the returned values;
// Preconditions.checkState(Objects.equal(splitAndGetLast("/", bootDisk.getSource()), bootDisk.getDeviceName()));
// return getDisk(splitAndGetLast("/", instance.getZone()), bootDisk.getDeviceName());
return getDisk(splitAndGetLast("/", instance.getZone()), splitAndGetLast("/", bootDisk.getSource()));
}
示例4: getAllComputeInstances
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
protected ImmutableMap<String, Instance> getAllComputeInstances()
{
Map<String, Instance> instances = new HashMap<String, Instance>();
Map<String, InstancesScopedList> instancesByZone = this.compute.instances().aggregatedList(credentials_.getProject()).execute().getItems();
for (String zone: instancesByZone.keySet())
{
List<Instance> instancePerZone = instancesByZone.get(zone).getInstances();
if (instancePerZone != null)
{
for (Instance instance : instancePerZone)
{
instances.put(instance.getName(), instance);
}
}
}
return ImmutableMap.copyOf(instances);
}
示例5: setUpMockedInstanceGroup
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* Sets up the mock API clients to front a given fake GCE instance group.
*
* @param simulatedGroup
*/
private void setUpMockedInstanceGroup(FakeMultiZoneInstanceGroup simulatedGroup) {
LOG.debug("setting up mocked call to get instance group ...");
when(this.instanceGroupClientMock.getInstanceGroup()).thenReturn(simulatedGroup.instanceGroupManager());
LOG.debug("setting up mocked call to get instance group members {} ...",
simulatedGroup.instances().stream().map(Instance::getName).collect(Collectors.toList()));
when(this.instanceGroupClientMock.listInstances()).thenReturn(simulatedGroup.managedInstances());
when(this.gceClientMock.multiZoneInstanceGroup(INSTANCE_GROUP_URL)).thenReturn(this.instanceGroupClientMock);
when(this.gceClientMock
.getInstanceTemplate(InstanceTemplateUrl.from(PROJECT, simulatedGroup.instanceTemplateName()).getUrl()))
.thenReturn(simulatedGroup.instanceTemplate());
for (Instance instance : simulatedGroup.instances()) {
String zone = UrlUtils.basename(instance.getZone());
LOG.debug("setting up mocked call to get instance metadata for {} ...",
PROJECT + "/" + zone + "/" + instance.getName());
when(this.gceClientMock.getInstance(instance.getSelfLink())).thenReturn(instance);
}
}
示例6: setServiceState
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* setServiceState should call through to modify the instance's metadata.
*/
@Test
public void setServiceState() {
int targetSize = 1;
int runningInstances = 1;
FakeSingleZoneInstanceGroup simulatedGroup = new FakeSingleZoneInstanceGroup(POOL_DRIVER_CONFIG, targetSize,
runningInstances);
setUpMockedInstanceGroup(simulatedGroup);
Instance instance = simulatedGroup.instances().get(0);
Map<String, String> instanceMetadata = MetadataUtil.toMap(instance.getMetadata());
String instanceUrl = instance.getSelfLink();
this.driver.setServiceState(instanceUrl, ServiceState.IN_SERVICE);
instanceMetadata.put(MetadataKeys.SERVICE_STATE, ServiceState.IN_SERVICE.name());
Metadata expectedMetadata = instance.getMetadata().clone().setItems(MetadataUtil.toItems(instanceMetadata));
// should call through to set metadata
verify(this.gceClientMock).setMetadata(instanceUrl, expectedMetadata);
}
示例7: setMembershipStatus
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* setMembershipStatus should call through to set the instance's metadata
*/
@Test
public void setMembershipStatus() {
int targetSize = 1;
int runningInstances = 1;
FakeSingleZoneInstanceGroup simulatedGroup = new FakeSingleZoneInstanceGroup(POOL_DRIVER_CONFIG, targetSize,
runningInstances);
setUpMockedInstanceGroup(simulatedGroup);
Instance instance = simulatedGroup.instances().get(0);
Map<String, String> instanceMetadata = MetadataUtil.toMap(instance.getMetadata());
String instanceUrl = instance.getSelfLink();
this.driver.setMembershipStatus(instanceUrl, MembershipStatus.blessed());
instanceMetadata.put(MetadataKeys.MEMBERSHIP_STATUS,
JsonUtils.toString(JsonUtils.toJson(MembershipStatus.blessed())));
Metadata expectedMetadata = instance.getMetadata().clone().setItems(MetadataUtil.toItems(instanceMetadata));
// should call through to set metadata
verify(this.gceClientMock).setMetadata(instanceUrl, expectedMetadata);
}
示例8: setUpMockedInstanceGroup
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* Sets up the mock API clients to front a given fake GCE instance group.
*
* @param simulatedGroup
*/
private void setUpMockedInstanceGroup(FakeSingleZoneInstanceGroup simulatedGroup) {
LOG.debug("setting up mocked call to get instance group ...");
when(this.instanceGroupClientMock.getInstanceGroup()).thenReturn(simulatedGroup.instanceGroupManager());
LOG.debug("setting up mocked call to get instance group members {} ...",
simulatedGroup.instances().stream().map(Instance::getName).collect(Collectors.toList()));
when(this.instanceGroupClientMock.listInstances()).thenReturn(simulatedGroup.managedInstances());
when(this.gceClientMock.singleZoneInstanceGroup(INSTANCE_GROUP_URL)).thenReturn(this.instanceGroupClientMock);
when(this.gceClientMock.getInstanceTemplate(simulatedGroup.instanceGroupManager().getInstanceTemplate()))
.thenReturn(simulatedGroup.instanceTemplate());
for (Instance instance : simulatedGroup.instances()) {
LOG.debug("setting up mocked call to get instance metadata for {} ...", instance.getName());
when(this.gceClientMock.getInstance(instance.getSelfLink())).thenReturn(instance);
}
}
示例9: convertInstance
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* Test converting a (metadata-complete) {@link Instance} to a
* {@link Machine} representation.
*/
@Test
public void convertInstance() throws IOException {
Instance instance = instance("instances/instance.json");
Machine machine = this.converter.apply(instance);
// the instance's URL is used as machine id
assertThat(machine.getId(), is(instance.getSelfLink()));
assertThat(machine.getMachineState(), is(MachineState.RUNNING));
assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN));
assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus()));
assertThat(machine.getLaunchTime(), is(UtcTime.parse(instance.getCreationTimestamp())));
assertThat(machine.getRequestTime(), is(nullValue()));
assertThat(machine.getPrivateIps(), is(Arrays.asList(instance.getNetworkInterfaces().get(0).getNetworkIP())));
assertThat(machine.getPublicIps(),
is(Arrays.asList(instance.getNetworkInterfaces().get(0).getAccessConfigs().get(0).getNatIP())));
assertThat(machine.getRequestTime(), is(nullValue()));
assertThat(machine.getCloudProvider(), is(CloudProviders.GCE));
assertThat(machine.getRegion(), is("europe-west1"));
assertThat(machine.getMachineSize(), is("n1-standard-1"));
assertThat(machine.getMetadata(), is(nullValue()));
}
示例10: convertMachineState
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* An instance's status should be correctly converted to a corresponding
* {@link MachineState}.
*/
@Test
public void convertMachineState() {
Instance instance = instance("instances/instance.json");
instance.setStatus("PROVISIONING");
assertThat(this.converter.apply(instance).getMachineState(), is(MachineState.PENDING));
instance.setStatus("STAGING");
assertThat(this.converter.apply(instance).getMachineState(), is(MachineState.PENDING));
instance.setStatus("RUNNING");
assertThat(this.converter.apply(instance).getMachineState(), is(MachineState.RUNNING));
instance.setStatus("STOPPING");
assertThat(this.converter.apply(instance).getMachineState(), is(MachineState.TERMINATING));
instance.setStatus("SUSPENDING");
assertThat(this.converter.apply(instance).getMachineState(), is(MachineState.TERMINATING));
instance.setStatus("SUSPENDED");
assertThat(this.converter.apply(instance).getMachineState(), is(MachineState.TERMINATED));
instance.setStatus("TERMINATED");
assertThat(this.converter.apply(instance).getMachineState(), is(MachineState.TERMINATED));
}
示例11: convertInstanceWithMembershipStatusMetadata
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* If a {@link MetadataKeys#MEMBERSHIP_STATUS} metadata key has been set on
* the {@link Instance}, it should be parsed and set on the {@link Machine}.
*/
@Test
public void convertInstanceWithMembershipStatusMetadata() {
Instance instance = instance("instances/instance.json");
setInstanceMetadata(instance, MetadataKeys.MEMBERSHIP_STATUS, MembershipStatus.defaultStatus());
assertThat(this.converter.apply(instance).getMembershipStatus(), is(MembershipStatus.defaultStatus()));
setInstanceMetadata(instance, MetadataKeys.MEMBERSHIP_STATUS, MembershipStatus.awaitingService());
assertThat(this.converter.apply(instance).getMembershipStatus(), is(MembershipStatus.awaitingService()));
setInstanceMetadata(instance, MetadataKeys.MEMBERSHIP_STATUS, MembershipStatus.blessed());
assertThat(this.converter.apply(instance).getMembershipStatus(), is(MembershipStatus.blessed()));
setInstanceMetadata(instance, MetadataKeys.MEMBERSHIP_STATUS, MembershipStatus.disposable());
assertThat(this.converter.apply(instance).getMembershipStatus(), is(MembershipStatus.disposable()));
}
示例12: convertInstanceWithServiceStateMetadata
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* If a {@link MetadataKeys#SERVICE_STATE} metadata key has been set on the
* {@link Instance}, it should be parsed and set on the {@link Machine}.
*/
@Test
public void convertInstanceWithServiceStateMetadata() {
Instance instance = instance("instances/instance.json");
setInstanceMetadata(instance, MetadataKeys.SERVICE_STATE, ServiceState.BOOTING);
assertThat(this.converter.apply(instance).getServiceState(), is(ServiceState.BOOTING));
setInstanceMetadata(instance, MetadataKeys.SERVICE_STATE, ServiceState.IN_SERVICE);
assertThat(this.converter.apply(instance).getServiceState(), is(ServiceState.IN_SERVICE));
setInstanceMetadata(instance, MetadataKeys.SERVICE_STATE, ServiceState.OUT_OF_SERVICE);
assertThat(this.converter.apply(instance).getServiceState(), is(ServiceState.OUT_OF_SERVICE));
setInstanceMetadata(instance, MetadataKeys.SERVICE_STATE, ServiceState.UNHEALTHY);
assertThat(this.converter.apply(instance).getServiceState(), is(ServiceState.UNHEALTHY));
setInstanceMetadata(instance, MetadataKeys.SERVICE_STATE, ServiceState.UNKNOWN);
assertThat(this.converter.apply(instance).getServiceState(), is(ServiceState.UNKNOWN));
}
示例13: collectGroupInstances
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* Collects metadata about all {@link Instance}s belonging to a certain
* instance group.
*
* @param instanceGroupClient
* An API client that makes calls targeting a particular instance
* group.
* @return
*/
private List<Instance> collectGroupInstances(InstanceGroupClient instanceGroupClient)
throws NotFoundException, CloudPoolException {
List<Instance> instances = new ArrayList<>();
List<ManagedInstance> members = instanceGroupClient.listInstances();
for (ManagedInstance member : members) {
try {
Instance instance = this.client.computeClient().getInstance(member.getInstance());
instances.add(instance);
} catch (Exception e) {
throw GceErrors.wrap(String.format("unable to get metadata for node pool instance %s: %s",
member.getInstance(), e.getMessage()), e);
}
}
return instances;
}
示例14: provisionInstances
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* Provision the given number of instances in specified project and zone.
* @param host The test service host.
* @param compute The Google Compute Engine client.
* @param userEmail The service account's client email.
* @param projectId The GCP project ID.
* @param zoneId The GCP project's zone ID.
* @param n The number of instances to provision.
* @param batchSize The batch size.
* @param interval The waiting interval.
* @throws Throwable The exception during provisioning remote instances.
*/
public static List<String> provisionInstances(VerificationHost host, Compute compute, String userEmail,
String projectId, String zoneId, int n, int batchSize, long interval)
throws Throwable {
if (n < 0) {
throw new IllegalArgumentException("the number of instances to be provisioned cannot be negative.");
}
if (batchSize <= 0) {
throw new IllegalArgumentException("batch size cannot be less or equal to zero.");
}
if (interval <= 0) {
throw new IllegalArgumentException("waiting interval cannot be less or equal to zero");
}
List<String> scopes = Collections.singletonList(ComputeScopes.CLOUD_PLATFORM);
List<String> instanceNames = new ArrayList<>();
com.google.api.services.compute.model.Operation[] ops =
new com.google.api.services.compute.model.Operation[n];
String[] zones = new String[n];
String[] opIds = new String[n];
Instance instance = createInstanceTemplate(userEmail, projectId, zoneId, scopes);
for (int i = 0;i < n;i++) {
String instanceName = ADAPTER_TEST_INSTANCE + UUID.randomUUID().toString();
instanceNames.add(instanceName);
ops[i] = provisionOneInstance(compute, instance, instanceName, projectId, zoneId);
zones[i] = ops[i].getZone();
zones[i] = extractZoneFromZoneUri(zones[i]);
opIds[i] = ops[i].getName();
// There is an upper bound for the frequency of making Google API calls.
// This is to prevent making too much API calls in a very short time.
if ((i + 1) % batchSize == 0) {
TimeUnit.MILLISECONDS.sleep(interval);
}
}
waitForOperationsDone(host, compute, projectId, ops, zones, opIds);
return instanceNames;
}
示例15: createInstanceTemplate
import com.google.api.services.compute.model.Instance; //导入依赖的package包/类
/**
* 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;
}