use of com.vmware.photon.controller.model.resources.ImageService.ImageState.DiskConfiguration in project photon-model by vmware.
the class TestAzureImageEnumerationTask method testPrivateImageEnumeration_single.
/**
* That's the private image we are testing:
* {@link /resourceGroups/Images/providers/Microsoft.Compute/images/LinuxImageWithOsAndDataUnmanaged/overview}
*/
@Test
@Ignore("For now run the test manually. Will enable it once the image is created programatically, but not hardcoded")
public void testPrivateImageEnumeration_single() throws Throwable {
Assume.assumeFalse(this.isMock);
kickOffImageEnumeration(this.endpointState, PRIVATE, AZURE_ALL_IMAGES_FILTER);
// Validate at least 1 image state is CREATED
QueryTop<ImageState> queryAll = new QueryTop<ImageState>(getHost(), Builder.create().addKindFieldClause(ImageState.class).build(), ImageState.class, this.endpointState.tenantLinks, this.endpointState.documentSelfLink);
List<ImageState> images = PhotonModelUtils.waitToComplete(queryAll.collectDocuments(Collectors.toList()));
Assert.assertTrue("Expected at least " + 1 + " private image, but found " + images.size(), images.size() >= 1);
ImageState image = images.stream().filter(imageState -> {
return imageState.name.equalsIgnoreCase(PRIVATE_IMAGE_NAME);
}).findFirst().orElse(null);
// Validate created image is correctly populated
Assert.assertNotNull("Private image with '" + PRIVATE_IMAGE_NAME + "' name must have been enumerated.", image);
Assert.assertNull("Private image must NOT have endpointType set.", image.endpointType);
Assert.assertEquals("Private image must have endpointLink set.", this.endpointState.documentSelfLink, image.endpointLink);
Assert.assertNotNull("Private image must have endpointLinks set.", image.endpointLinks);
Assert.assertTrue("Private image must have endpointLinks set.", image.endpointLinks.contains(this.endpointState.documentSelfLink));
Assert.assertEquals("Private image must have tenantLinks set.", this.endpointState.tenantLinks, image.tenantLinks);
Assert.assertTrue("Image.id is invalid", image.id.endsWith(PRIVATE_IMAGE_NAME));
Assert.assertEquals("Image.name is invalid", PRIVATE_IMAGE_NAME, image.name);
Assert.assertEquals("Image.description is invalid", PRIVATE_IMAGE_NAME, image.description);
Assert.assertNotNull("Image.diskConfigs", image.diskConfigs);
Assert.assertEquals("Image.diskConfigs.size", 2, image.diskConfigs.size());
{
DiskConfiguration osDiskConfig = image.diskConfigs.get(0);
Assert.assertNotNull("Image.osDiskConfig.properties", osDiskConfig.properties);
Assert.assertNotNull("Image.osDiskConfig.properties.blobUri", osDiskConfig.properties.get(AzureConstants.AZURE_DISK_BLOB_URI));
Assert.assertNull("Image.osDiskConfig.properties.lun", osDiskConfig.properties.get(AzureConstants.AZURE_DISK_LUN));
}
{
DiskConfiguration dataDiskConfig = image.diskConfigs.get(1);
Assert.assertNotNull("Image.dataDiskConfig.properties", dataDiskConfig.properties);
Assert.assertNotNull("Image.dataDiskConfig.properties.blobUri", dataDiskConfig.properties.get(AzureConstants.AZURE_DISK_BLOB_URI));
Assert.assertEquals("Image.dataDiskConfig.properties.lun", "0", dataDiskConfig.properties.get(AzureConstants.AZURE_DISK_LUN));
}
}
use of com.vmware.photon.controller.model.resources.ImageService.ImageState.DiskConfiguration in project photon-model by vmware.
the class AzureTestUtil method createPrivateImageSource.
public static ImageSource createPrivateImageSource(VerificationHost host, EndpointState endpointState) throws Throwable {
ImageState bootImage = new ImageState();
// Change id and name according to your custom image details
bootImage.id = "/subscriptions/817776f9-ef2a-4681-9774-a66f9be11e22/resourceGroups/Images/providers/Microsoft.Compute/images/SourceImageLinuxUnmanagedAPI";
bootImage.name = "SourceImageLinuxUnmanagedAPI";
bootImage.osFamily = "Linux";
bootImage.tenantLinks = endpointState.tenantLinks;
bootImage.endpointLink = endpointState.documentSelfLink;
bootImage.endpointLinks = new HashSet<>();
bootImage.endpointLinks.add(endpointState.documentSelfLink);
List<DiskConfiguration> imageDisks = new ArrayList<>();
DiskConfiguration osDiskConfig = new DiskConfiguration();
imageDisks.add(osDiskConfig);
// Add/Remove data disks and also map correct LUN values based on your private image configuration
DiskConfiguration dataDiskConfig1 = new DiskConfiguration();
dataDiskConfig1.properties = new HashMap<>();
dataDiskConfig1.properties.put(AzureConstants.AZURE_DISK_LUN, "0");
imageDisks.add(dataDiskConfig1);
DiskConfiguration dataDiskConfig2 = new DiskConfiguration();
dataDiskConfig2.properties = new HashMap<>();
dataDiskConfig2.properties.put(AzureConstants.AZURE_DISK_LUN, "1");
imageDisks.add(dataDiskConfig2);
bootImage.diskConfigs = imageDisks;
bootImage = TestUtils.doPost(host, bootImage, ImageState.class, UriUtils.buildUri(host, ImageService.FACTORY_LINK));
return ImageSource.fromImageState(bootImage);
}
use of com.vmware.photon.controller.model.resources.ImageService.ImageState.DiskConfiguration in project photon-model by vmware.
the class AzureInstanceService method createVM.
private void createVM(AzureInstanceContext ctx, AzureInstanceStage nextStage) {
ComputeDescriptionService.ComputeDescription description = ctx.child.description;
Map<String, String> customProperties = description.customProperties;
if (customProperties == null) {
handleError(ctx, new IllegalStateException("Custom properties not specified"));
return;
}
// DiskService.DiskStateExpanded bootDisk = ctx.bootDiskState;
if (ctx.bootDiskState == null) {
handleError(ctx, new IllegalStateException("Azure bootDisk not specified"));
return;
}
String cloudConfig = null;
if (ctx.bootDiskState.bootConfig != null && ctx.bootDiskState.bootConfig.files.length > CLOUD_CONFIG_DEFAULT_FILE_INDEX) {
cloudConfig = ctx.bootDiskState.bootConfig.files[CLOUD_CONFIG_DEFAULT_FILE_INDEX].contents;
}
VirtualMachineInner request = new VirtualMachineInner();
request.withLocation(ctx.resourceGroup.location());
SubResource availabilitySetSubResource = new SubResource().withId(ctx.availabilitySet.id());
request.withAvailabilitySet(availabilitySetSubResource);
// Set OS profile.
OSProfile osProfile = new OSProfile();
osProfile.withComputerName(ctx.vmName);
if (ctx.childAuth != null) {
osProfile.withAdminUsername(ctx.childAuth.userEmail);
osProfile.withAdminPassword(EncryptionUtils.decrypt(ctx.childAuth.privateKey));
}
if (cloudConfig != null) {
try {
osProfile.withCustomData(Base64.getEncoder().encodeToString(cloudConfig.getBytes(Utils.CHARSET)));
} catch (UnsupportedEncodingException e) {
logWarning(() -> "Error encoding user data");
return;
}
}
request.withOsProfile(osProfile);
// Set hardware profile.
HardwareProfile hardwareProfile = new HardwareProfile();
hardwareProfile.withVmSize(description.instanceType != null ? VirtualMachineSizeTypes.fromString(description.instanceType) : VirtualMachineSizeTypes.BASIC_A0);
request.withHardwareProfile(hardwareProfile);
// Set storage profile.
// Create destination OS VHD
final OSDisk osDisk = newAzureOsDisk(ctx);
final StorageProfile storageProfile = new StorageProfile();
storageProfile.withOsDisk(osDisk);
List<DataDisk> dataDisks = new ArrayList<>();
List<Integer> LUNsOnImage = new ArrayList<>();
storageProfile.withImageReference(ctx.imageSource.asImageReferenceInner());
if (ctx.imageSource.type == ImageSource.Type.PRIVATE_IMAGE) {
// set LUNs of data disks present on the custom image.
final ImageState imageState = ctx.imageSource.asImageState();
if (imageState != null && imageState.diskConfigs != null) {
for (DiskConfiguration diskConfig : imageState.diskConfigs) {
if (diskConfig.properties != null && diskConfig.properties.containsKey(AzureConstants.AZURE_DISK_LUN)) {
DataDisk imageDataDisk = new DataDisk();
int lun = Integer.parseInt(diskConfig.properties.get(AzureConstants.AZURE_DISK_LUN));
LUNsOnImage.add(lun);
imageDataDisk.withLun(lun);
imageDataDisk.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
dataDisks.add(imageDataDisk);
}
}
}
String dataDiskCaching = ctx.bootDiskState.customProperties.get(AZURE_DATA_DISK_CACHING);
if (dataDiskCaching != null) {
dataDisks.stream().forEach(dataDisk -> dataDisk.withCaching(CachingTypes.fromString(dataDiskCaching)));
}
String diskType = ctx.bootDiskState.customProperties.get(AZURE_MANAGED_DISK_TYPE);
if (diskType != null) {
ManagedDiskParametersInner managedDiskParams = new ManagedDiskParametersInner();
managedDiskParams.withStorageAccountType(StorageAccountTypes.fromString(diskType));
dataDisks.stream().forEach(dataDisk -> dataDisk.withManagedDisk(managedDiskParams));
}
}
// choose LUN greater than the one specified in case of custom image. Else start from zero.
int LUNForAdditionalDisk = LUNsOnImage.size() == 0 ? 0 : Collections.max(LUNsOnImage) + 1;
dataDisks.addAll(newAzureDataDisks(ctx, LUNForAdditionalDisk));
storageProfile.withDataDisks(dataDisks);
request.withStorageProfile(storageProfile);
// Set network profile {{
NetworkProfile networkProfile = new NetworkProfile();
networkProfile.withNetworkInterfaces(new ArrayList<>());
for (AzureNicContext nicCtx : ctx.nics) {
NetworkInterfaceReferenceInner nicRef = new NetworkInterfaceReferenceInner();
nicRef.withId(nicCtx.nic.id());
// NOTE: First NIC is marked as Primary.
nicRef.withPrimary(networkProfile.networkInterfaces().isEmpty());
networkProfile.networkInterfaces().add(nicRef);
}
request.withNetworkProfile(networkProfile);
logFine(() -> String.format("Creating virtual machine with name [%s]", ctx.vmName));
AzureAsyncCallback<VirtualMachineInner> callback = new AzureAsyncCallback<VirtualMachineInner>() {
@Override
public void onError(Throwable e) {
// exception and try again with a shorter name
if (isIncorrectNameLength(e)) {
request.osProfile().withComputerName(generateWindowsComputerName(ctx.vmName));
getComputeManagementClientImpl(ctx).virtualMachines().createOrUpdateAsync(ctx.resourceGroup.name(), ctx.vmName, request, this);
return;
}
handleCloudError(String.format("Provisioning VM %s: FAILED. Details:", ctx.vmName), ctx, COMPUTE_NAMESPACE, e);
}
// Cannot tell for sure, but these checks should be enough
private boolean isIncorrectNameLength(Throwable e) {
if (e instanceof CloudException) {
CloudException ce = (CloudException) e;
CloudError body = ce.body();
if (body != null) {
String code = body.code();
String target = body.target();
return INVALID_PARAMETER.equals(code) && COMPUTER_NAME.equals(target) && request.osProfile().computerName().length() > WINDOWS_COMPUTER_NAME_MAX_LENGTH && body.message().toLowerCase().contains("windows");
}
}
return false;
}
private String generateWindowsComputerName(String vmName) {
String computerName = vmName;
if (vmName.length() > WINDOWS_COMPUTER_NAME_MAX_LENGTH) {
// Take the first 12 and the last 3 chars of the generated VM name
computerName = vmName.substring(0, 12) + vmName.substring(vmName.length() - 3, vmName.length());
}
return computerName;
}
@Override
public void onSuccess(VirtualMachineInner result) {
logFine(() -> String.format("Successfully created vm [%s]", result.name()));
ctx.provisionedVm = result;
ComputeState cs = new ComputeState();
// Azure for some case changes the case of the vm id.
ctx.vmId = result.id().toLowerCase();
cs.id = ctx.vmId;
cs.type = ComputeType.VM_GUEST;
cs.environmentName = ComputeDescription.ENVIRONMENT_NAME_AZURE;
cs.lifecycleState = LifecycleState.READY;
if (ctx.child.customProperties == null) {
cs.customProperties = new HashMap<>();
} else {
cs.customProperties = ctx.child.customProperties;
}
cs.customProperties.put(RESOURCE_GROUP_NAME, ctx.resourceGroup.name());
Operation.CompletionHandler completionHandler = (ox, exc) -> {
if (exc != null) {
handleError(ctx, exc);
return;
}
handleAllocation(ctx, nextStage);
};
sendRequest(Operation.createPatch(ctx.computeRequest.resourceReference).setBody(cs).setCompletion(completionHandler));
}
};
getComputeManagementClientImpl(ctx).virtualMachines().createOrUpdateAsync(ctx.resourceGroup.name(), ctx.vmName, request, callback);
}
use of com.vmware.photon.controller.model.resources.ImageService.ImageState.DiskConfiguration in project photon-model by vmware.
the class ImageServiceTest method buildValidStartState.
// Copy-pasted from ImageService.getDocumentTemplate
private static ImageState buildValidStartState() {
ImageState image = new ImageState();
image.id = "endpoint-specific-image-id";
image.name = "endpoint-specific-image-name";
image.description = "User-friendly-image-description";
image.osFamily = "Linux";
image.regionId = "endpoint-specific-image-region-id";
image.endpointLink = buildUriPath(EndpointService.FACTORY_LINK, "the-A-cloud");
image.groupLinks = singleton(buildUriPath(ResourceGroupService.FACTORY_LINK, "the-A-folder"));
image.tenantLinks = singletonList(buildUriPath(TenantService.FACTORY_LINK, "the-A-tenant"));
DiskConfiguration osDiskConfig = new DiskConfiguration();
osDiskConfig.id = Integer.toString(0);
osDiskConfig.capacityMBytes = Integer.MAX_VALUE;
osDiskConfig.encrypted = true;
osDiskConfig.persistent = true;
osDiskConfig.properties = Collections.singletonMap("disk.cp.name", "disk.cp.value");
DiskConfiguration dataDiskConfig = new DiskConfiguration();
dataDiskConfig.id = Integer.toString(1);
dataDiskConfig.capacityMBytes = Integer.MAX_VALUE;
dataDiskConfig.encrypted = true;
dataDiskConfig.persistent = true;
dataDiskConfig.properties = Collections.singletonMap("disk.cp.name", "disk.cp.value");
image.diskConfigs = Arrays.asList(osDiskConfig, dataDiskConfig);
return image;
}
Aggregations