use of com.vmware.xenon.common.ServiceHost in project photon-model by vmware.
the class AWSEnumerationUtils method mapInstanceToComputeState.
/**
* Maps the instance discovered on AWS to a local compute state that will be persisted.
*/
public static ComputeState mapInstanceToComputeState(ServiceHost host, Instance instance, String parentComputeLink, String placementComputeLink, String resourcePoolLink, String existingEndpointLink, Set<String> endpointLinks, String computeDescriptionLink, Set<URI> parentCDStatsAdapterReferences, Set<String> internalTagLinks, String regionId, String zoneId, List<String> tenantLinks, List<Tag> createdExternalTags, Boolean isNewState, List<String> diskLinks) {
ComputeState computeState = new ComputeState();
computeState.id = instance.getInstanceId();
computeState.name = instance.getInstanceId();
computeState.parentLink = parentComputeLink;
computeState.computeHostLink = parentComputeLink;
computeState.type = ComputeType.VM_GUEST;
computeState.environmentName = ComputeDescription.ENVIRONMENT_NAME_AWS;
computeState.regionId = regionId;
computeState.zoneId = zoneId;
computeState.instanceType = instance.getInstanceType();
computeState.instanceAdapterReference = AdapterUriUtil.buildAdapterUri(host, AWSUriPaths.AWS_INSTANCE_ADAPTER);
computeState.enumerationAdapterReference = AdapterUriUtil.buildAdapterUri(host, AWSUriPaths.AWS_ENUMERATION_CREATION_ADAPTER);
computeState.statsAdapterReference = AdapterUriUtil.buildAdapterUri(host, AWSUriPaths.AWS_STATS_ADAPTER);
computeState.statsAdapterReferences = parentCDStatsAdapterReferences;
computeState.resourcePoolLink = resourcePoolLink;
if (computeState.endpointLinks == null) {
computeState.endpointLinks = new HashSet<>();
}
computeState.endpointLinks.addAll(endpointLinks);
// assign existing one, if exists
if (existingEndpointLink != null) {
computeState.endpointLink = existingEndpointLink;
} else {
computeState.endpointLink = endpointLinks.iterator().next();
}
// Compute descriptions are looked up by the instanceType in the local list of CDs.
computeState.descriptionLink = computeDescriptionLink;
computeState.hostName = instance.getPublicDnsName();
// TODO VSYM-375 for adding disk information
computeState.address = instance.getPublicIpAddress();
computeState.powerState = AWSUtils.mapToPowerState(instance.getState());
computeState.customProperties = new HashMap<>();
computeState.customProperties.put(CUSTOM_OS_TYPE, getNormalizedOSType(instance));
computeState.customProperties.put(SOURCE_TASK_LINK, ResourceEnumerationTaskService.FACTORY_LINK);
computeState.customProperties.put(ComputeProperties.PLACEMENT_LINK, placementComputeLink);
// Network State. Create one network state mapping to each VPC that is discovered during
// enumeration.
computeState.customProperties.put(AWS_VPC_ID, instance.getVpcId());
computeState.tagLinks = new HashSet<>();
// PATCH to update tagLinks of existing disks.
if (!instance.getTags().isEmpty() && isNewState) {
// we have already made sure that the tags exist and we can build their links ourselves
computeState.tagLinks = instance.getTags().stream().filter(t -> !AWSConstants.AWS_TAG_NAME.equals(t.getKey()) && createdExternalTags.contains(t)).map(t -> newTagState(t.getKey(), t.getValue(), true, tenantLinks)).map(TagFactoryService::generateSelfLink).collect(Collectors.toSet());
if (computeState.tagLinks != null && computeState.tagLinks.contains(null)) {
host.log(Level.SEVERE, "Null tag link inserted in new ComputeState for instance ID: %s", instance.getInstanceId());
host.log(Level.SEVERE, "Removing null tag link from new ComputeState");
computeState.tagLinks.remove(null);
}
}
// The name of the compute state is the value of the AWS_TAG_NAME tag
String nameTag = getTagValue(instance.getTags(), AWS_TAG_NAME);
if (nameTag != null && !nameTag.equals(EMPTY_STRING)) {
computeState.name = nameTag;
}
// append internal tagLinks to any existing ones
if (internalTagLinks != null) {
computeState.tagLinks.addAll(internalTagLinks);
}
if (instance.getLaunchTime() != null) {
computeState.creationTimeMicros = TimeUnit.MILLISECONDS.toMicros(instance.getLaunchTime().getTime());
}
if (diskLinks != null && !diskLinks.isEmpty()) {
computeState.diskLinks = new ArrayList<>();
computeState.diskLinks.addAll(diskLinks);
}
computeState.tenantLinks = tenantLinks;
return computeState;
}
use of com.vmware.xenon.common.ServiceHost in project photon-model by vmware.
the class EndpointAdapterUtils method registerEndpointAdapters.
/**
* Register end-point adapters into End-point Adapters Registry.
*
* @param host
* The host the end-point is running on.
* @param endpointType
* The type of the end-point.
* @param startedAdapterLinks
* The array of started adapter links.
* @param adapterLinksToRegister
* Map of adapter links (to be registered) to their adapter type key. e.g for
* standard adapters this is {@link com.vmware.photon.controller.model.UriPaths.AdapterTypePath#key}
* @param registryLocator
* ServiceEndpointLocator containing the host of the adapter registry. Can be null if the
* registry is on the same host.
* @see #handleEndpointRegistration(ServiceHost, EndpointType, Consumer, ServiceEndpointLocator)
*/
public static void registerEndpointAdapters(ServiceHost host, EndpointType endpointType, String[] startedAdapterLinks, Map<String, String> adapterLinksToRegister, ServiceEndpointLocator registryLocator) {
// Count all adapters - both FAILED and STARTED
AtomicInteger adaptersCountDown = new AtomicInteger(startedAdapterLinks.length);
// Keep started adapters only...
// - key = adapter type ket (e.g. AdapterTypePath.key)
// - value = adapter URI
Map<String, String> startedAdapters = new ConcurrentHashMap<>();
// Wait for all adapter services to start
host.registerForServiceAvailability((op, ex) -> {
if (ex != null) {
String adapterPath = op.getUri().getPath();
host.log(Level.WARNING, "Starting '%s' adapter [%s]: FAILED - %s", endpointType, adapterPath, Utils.toString(ex));
} else {
String adapterPath = op.getUri().getPath();
host.log(Level.FINE, "Starting '%s' adapter [%s]: SUCCESS", endpointType, adapterPath);
String adapterKey = adapterLinksToRegister.get(adapterPath);
if (adapterKey != null) {
startedAdapters.put(adapterKey, AdapterUriUtil.buildPublicAdapterUri(host, adapterPath).toString());
}
}
if (adaptersCountDown.decrementAndGet() == 0) {
// Once ALL Adapters are started register them into End-point Adapters Registry
host.log(Level.INFO, "Starting %d '%s' adapters: SUCCESS", startedAdapters.size(), endpointType);
// Populate end-point config with started adapters
Consumer<PhotonModelAdapterConfig> endpointConfigEnhancer = ep -> ep.adapterEndpoints.putAll(startedAdapters);
// Delegate to core end-point config/registration logic
handleEndpointRegistration(host, endpointType, endpointConfigEnhancer, registryLocator);
}
}, /* this services are not replicated */
false, startedAdapterLinks);
}
use of com.vmware.xenon.common.ServiceHost in project photon-model by vmware.
the class AWSUtils method waitForTransitionCompletion.
public static void waitForTransitionCompletion(ServiceHost host, List<InstanceStateChange> stateChangeList, final String desiredState, AmazonEC2AsyncClient client, BiConsumer<InstanceState, Exception> callback) {
InstanceStateChange stateChange = stateChangeList.get(0);
try {
DescribeInstancesRequest request = new DescribeInstancesRequest();
request.withInstanceIds(stateChange.getInstanceId());
DescribeInstancesResult result = client.describeInstances(request);
Instance instance = result.getReservations().stream().flatMap(r -> r.getInstances().stream()).filter(i -> i.getInstanceId().equalsIgnoreCase(stateChange.getInstanceId())).findFirst().orElseThrow(() -> new IllegalArgumentException(String.format("%s instance not found", stateChange.getInstanceId())));
String state = instance.getState().getName();
if (state.equals(desiredState)) {
callback.accept(instance.getState(), null);
} else {
host.schedule(() -> waitForTransitionCompletion(host, stateChangeList, desiredState, client, callback), 5, TimeUnit.SECONDS);
}
} catch (AmazonServiceException | IllegalArgumentException ase) {
callback.accept(null, ase);
}
}
use of com.vmware.xenon.common.ServiceHost in project photon-model by vmware.
the class MockAdapter method startFactories.
public static void startFactories(BaseModelTest test) throws Throwable {
ServiceHost host = test.getHost();
if (host.getServiceStage(MockSuccessInstanceAdapter.SELF_LINK) != null) {
return;
}
host.startService(new MockSuccessInstanceAdapter());
host.startService(new MockFailureInstanceAdapter());
host.startService(new MockSuccessBootAdapter());
host.startService(new MockFailureBootAdapter());
host.startService(new MockSuccessEnumerationAdapter());
host.startService(new MockPreserveMissingEnumerationAdapter());
host.startService(new MockFailureEnumerationAdapter());
host.startService(new MockSuccessImageEnumerationAdapter());
host.startService(new MockFailureImageEnumerationAdapter());
host.startService(new MockFailOperationImageEnumerationAdapter());
host.startService(new MockCancelledImageEnumerationAdapter());
host.startService(new MockSnapshotSuccessAdapter());
host.startService(new MockSnapshotFailureAdapter());
host.startService(new MockNetworkInstanceSuccessAdapter());
host.startService(new MockNetworkInstanceFailureAdapter());
host.startService(new MockLoadBalancerInstanceSuccessAdapter());
host.startService(new MockLoadBalancerInstanceFailureAdapter());
host.startService(new MockSubnetInstanceSuccessAdapter());
host.startService(new MockSubnetInstanceFailureAdapter());
host.startService(new MockSecurityGroupInstanceSuccessAdapter());
host.startService(new MockSecurityGroupInstanceFailureAdapter());
host.startService(new MockSuccessEndpointAdapter(test));
host.startService(new MockUntrustedCertEndpointAdapter());
host.startService(new MockFailNPEEndpointAdapter());
host.startService(new MockNetworkInterfaceSecurityGroupsFailureAdapter());
host.startService(new MockNetworkInterfaceSecurityGroupsSuccessAdapter());
}
use of com.vmware.xenon.common.ServiceHost in project photon-model by vmware.
the class InstanceClient method handleVirtualDiskCleanup.
/**
* For every disk states in the compute based on the persistent flag if it is set as TRUE,
* then disk will be detached before we delete the vm.
*/
private void handleVirtualDiskCleanup(ServiceHost serviceHost, ManagedObjectReference vm, ArrayOfVirtualDevice devices, List<DiskStateExpanded> disks) throws Exception {
if (CollectionUtils.isEmpty(disks)) {
return;
}
List<DiskStateExpanded> persistDisks = disks.stream().filter(disk -> disk.type == DiskType.HDD).filter(disk -> disk.persistent != null && disk.persistent).collect(Collectors.toList());
if (CollectionUtils.isEmpty(persistDisks)) {
return;
}
List<Operation> diskUpdateOps = new ArrayList<>(persistDisks.size());
for (DiskStateExpanded ds : persistDisks) {
VirtualDisk vd = (VirtualDisk) findMatchingVirtualDevice(getListOfVirtualDisk(devices), ds);
if (vd != null) {
detachDisk(this.connection, vd, vm, getVimPort());
}
// Now update the status of the persistent disks to be AVAILABLE
ds.status = DiskService.DiskStatus.AVAILABLE;
CustomProperties.of(ds).put(DISK_CONTROLLER_NUMBER, (String) null).put(PROVIDER_DISK_UNIQUE_ID, (String) null);
ds.id = UriUtils.getLastPathSegment(ds.documentSelfLink);
diskUpdateOps.add(Operation.createPut(PhotonModelUriUtils.createInventoryUri(serviceHost, ds.documentSelfLink)).setReferer(serviceHost.getUri()).setBody(ds));
disks.remove(ds);
}
// call patch operations on the disk states
OperationJoin.create(diskUpdateOps).setCompletion((os, errors) -> {
if (errors != null && !errors.isEmpty()) {
logger.warn(String.format("Exception in updating persistent disk during deletion of VM." + " Error : %s", Utils.toString(errors)));
}
}).sendWith(serviceHost);
}
Aggregations