Virtual Machine Management with Java
Applies To: System Center 2016 - Service Provider Foundation, System Center Technical Preview
This guide demonstrates some basic tasks you can use to develop software with Infrastructure as a Service (IaaS.) It shows how you can use Virtual Machine Manager (VMM) in Service Provider Foundation to create, start, stop, restore and remove hosted virtual machines programmatically. The code examples are written in Java and were developed and run using the Eclipse IDE. You could modify the examples in this guide to work with other languages that can form HTTP operations. Your application just needs to create an OData payload like the examples here and then do a POST operation to the REST endpoint where your service provider exposes the VMM service. For similar examples using C# and .NET, see the Virtual Machine Manager Service section of the Service Provider Foundation Developer's Guide.
Service Provider Foundation exposes an extensible OData service for VMM that enables service providers (also called hosters) to build multi-tenant self-service portals with IaaS capabilities. A tenant in Service Provider Foundation is a customer of an IaaS service provider. The service provider associates the tenant’s account with a subscription-id, a stamp that ties a server and an instance of VMM, a public key to a security certificate used to verify the tenant, and a tenant role. The service provider may also provide the tenant with a user name and password to access a management web portal.
For information about using VM roles with Windows Azure Pack see Use VM Roles in Windows Azure Pack with Java
After running the samples in this guide you should be able to do the following using Java:
Get a List of Virtual Machines List all the virtual machines currently existing in your service provider subscription.
Get a List of Clouds, Stamps, or Virtual Hard Disks List all the Clouds, Stamps, or VHDs currently existing in your service provider subscription and from these determine their StampId, CloudId, and VirtualHardDiskId guids.
Create a Virtual Machine from a VHD Create a new virtual machine by cloning an existing virtual hard disk that has an operating system.
Starting and Stopping a Virtual Machine Start and stop a virtual machine.
Delete a Virtual Machine. Delete a virtual machine in your subscription.
Create a Virtual Machine Checkpoint Create and save a checkpoint of a virtual machine’s present state.
Restore a Virtual Machine from a Checkpoint Restore a virtual machine to a previous state from a saved virtual machine checkpoint.
Delete a Virtual Machine Checkpoint Delete a saved virtual machine checkpoint.
Get a List of Virtual Machines
Because Windows Azure Pack for Windows Server and API uses RDFE for the service endpoint, you can construct a RDFE uniform resource identifier (URI) to connect to your service in the usual way. For information about how to construct the RDFE uri see SPF and RDFE URIs and OData Protocol.
In general, the RDFE endpoint for a service has the following form.
https://server:port/subscription-id/services/systemcenter/service/
...
If your service provider has given you a user name and password, you may be able to log into the management portal for your account and determine your subscription-id there. Your subscription-id is represented in the examples in this guide by the string: 2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa. While logged into the management portal you can also upload a certificate that will enable the host to verify you as a trusted user.
The following Java code returns a list of all the virtual machines in your subscription. It sends a GET request to the service uri and receives a HTTP response listing all the VirtualMachine objects in your VirtualMachines collection.
public class Get_list
{
public static void main(String[] args) throws Exception
{
String u = "https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VirtualMachines";
URL url = new URL(u);
HttpURLConnection c = null;
c = (HttpsURLConnection)url.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
c.setRequestProperty("DataServiceVersion", "3.0;NetFx");
c.setRequestProperty("MaxDataServiceVersion", "3.0;NetFx");
c.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
c.setRequestProperty("Accept-Charset", "UTF-8");
c.setRequestProperty("DataServiceUrlConventions", "KeyAsSegment");
c.setRequestProperty("User-Agent", "Microsoft ADO.NET Data Services");
c.setRequestProperty("x-ms-principal-id", "user@contoso.com");
c.setRequestProperty("Content-Type","application/json;odata=minimalmetadata");
c.setRequestProperty("Host", "user@contoso.com");
c.setRequestProperty("Expect", "100-continue");
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null){System.out.println(decodedString);}
in.close();
}
}
The following is an example of the HTTP response after running the Get_list example on the VirtualMachines collection.
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 156
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
request-id: 33c9dafc-df0d-0000-f6e6-ca330ddfce01
DataServiceVersion: 3.0;
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
Date: Wed, 20 Nov 2013 23:09:52 GMT
{"odata.metadata":"https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/$metadata#VirtualMachines","value":[]}
Note that the “value” returned in the OData payload is an empty set and indicates that there are no virtual machines in this collection.
Get a List of Clouds, Stamps, or Virtual Hard Disks
To create a new virtual machine (VM), you are going to need the following information.
The StampId of a stamp that can be used with the new VM
The CloudId of a cloud that can be used with the new VM.
The VirtualHardDiskId of an existing VirtualHardDisk object, that can be cloned to create the new VM.
The Name of the new virtual machine, which you may specify.
You can get this using the Get_List example code if Cloud and VirtualHardDisk objects already exist in your subscription. Change Get_list to point to the uri for the Clouds collection in your subscription. For this example, this is as follows:
https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/Clouds
Run Get_list to get a list of Cloud objects in your Clouds collection. The following is an example of a HTTP response that contains the guid identifiers for a cloud and stamp that already exist.
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 347
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
request-id: 33c9dafc-df0d-0001-955a-ca330ddfce01
DataServiceVersion: 3.0;
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
Date: Thu, 21 Nov 2013 18:47:58 GMT
{"odata.metadata":"https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/$metadata#Clouds","value":[{"ID":"3333b333-b3bb-333b-333b-3bbb33333bbb","Name":"KatalCloud","Description":"","LastModifiedDate":null,"WritableLibraryPath":null,"UserRoleID":null,"StampId":"444c4444-c44c-4444-c4c4-44ccc4444c4c"}]}
In this case, there is one stamp and one cloud listed in the response. The following strings represent your StampId and CloudId in later examples.
StampId : 444c4444-c44c-4444-c4c4-44ccc4444c4c
CloudId : 3333b333-b3bb-333b-333b-3bbb33333bbb
Change the “Get_list” Java code again to point to the uri for the VirtualHardDisks collection in your subscription. For this example, this would be as follows:
https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VirtualHardDisks
Run Get_list to get a list of VirtualHardDisk objects in your VirtualHardDisks collection. The following is an example of a response that returns the guid identifiers for a virtual hard disk that already exists.
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 25845
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
request-id: 33c9dafc-df0d-0000-4df3-ca330ddfce01
DataServiceVersion: 3.0;
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
Date: Thu, 21 Nov 2013 19:15:40 GMT
{"odata.metadata":"https://smapi-server.cdm.lab:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/$metadata#VirtualHardDisks","value":[{"Accessibility":"Public","AddedTime":"2013-11-07T11:06:41.62-08:00","Description":"","Directory":"\\\\Server\\MSSCVMMLibrary\\VHDs","Enabled":true,"ID":"d55ddddd-dd55-5d55-ddd5-d5dd55dd5dd5","JobGroupId":null,"MaximumSize":"42949672960","ModifiedTime":"2013-11-07T11:08:23.077-08:00","Name":"auto.cent6.v0.x86.vhd","Owner":{"UserName":null,"RoleName":null,"RoleID":null},"OwnerSid":null,"ParentDiskId":null,"SharePath":"\\\\Server\\MSSCVMMLibrary\\VHDs\\auto.cent6.v0.x86.vhd","Size":"1713867264","State":"Normal","VHDType":"DynamicallyExpanding","VMId":null,"TemplateId":null,"StampId":"444c4444-c44c-4444-c4c4-44ccc4444c4c","FamilyName":"auto.cent6.v0.x86.vhd","Release":"1.0.0.0","CloudId":null,"HostVolumeId":null,"IsOrphaned":false,"IsResourceGroup":null,"LibraryGroup":"","LibraryShareId":"2f11e261-9bd7-463b-bdcb-a7abbeed2d78","Location":"\\\\Server\\MSSCVMMLibrary\\VHDs\\auto.cent6.v0.x86.vhd","Namespace":"Global","ReleaseTime":"2013-11-07T11:08:23.077-08:00","SANCopyCapable":false,"Type":null,"VirtualizationPlatform":"Unknown","OperatingSystem":"CentOS Linux 6 (32 bit)","OperatingSystemInstance":{"Name":"CentOS Linux 6 (32 bit)","Description":"CentOS Linux 6 (32 bit)","Version":null,"Architecture":"x86","Edition":null,"OSType":"Linux","ProductType":null},"OperatingSystemId":null,"Tag":[]}]}
In this case, there is one virtual hard disk (VHD) listed in the response, which has a Linux operating system already installed on it. The following string represents the VirtualHardDiskId in later examples.
VirtualHardDiskId: d55ddddd-dd55-5d55-ddd5-d5dd55dd5dd5
The next section shows how you can clone this VHD to create a new virtual machine.
Create a Virtual Machine from a VHD
For the examples in this guide, the OData required to manage a virtual machine is saved in a text file on your computer named odata.txt. The Java code examples read odata.txt using the following getpayload() method.
public class Data
{
private String s;
public Data()
{
String fileName = ("C:"+File.separator+"test"+File.separator+"odata.txt");
File dataFile = new File(fileName);
byte[] content = new byte[0];
{
try {FileInputStream dataInputStream = new FileInputStream(dataFile);
int bytesAvailable = dataInputStream.available();
content = new byte[bytesAvailable];
dataInputStream.read(content);
dataInputStream.close();}
catch (FileNotFoundException fnfe) {System.out.println("Couldn't find a file called " + fileName);}
catch (IOException ioe) {System.out.println("Couldn't read from a file called " + fileName);}
this.s = new String(content);
}
}
public String getpayload(){return s;}
}
The CloudId, StampId, VirtualHardDiskId and Name is required to create a new virtual machine. In the following OData example the values of StampId, CloudId, VirtualHardDiskId, and Name (in this case “redvm”) have been written into odata.txt. For this example, the contents of odata.txt are the following:
{
"AddedTime": null,
"Agent": null,
"AllocatedGPU": null,
"BackupEnabled": null,
"BlockDynamicOptimization": null,
"BlockLiveMigrationIfHostBusy": null,
"CPUCount": null,
"CPULimitForMigration": null,
"CPULimitFunctionality": null,
"CPUMax": null,
"CPURelativeWeight": null,
"CPUReserve": null,
"CPUType": null,
"CPUUtilization": null,
"CanVMConnect": null,
"CapabilityProfile": null,
"CheckpointLocation": null,
"CloudId": "3333b333-b3bb-333b-333b-3bbb33333bbb",
"CloudVMRoleName": null,
"ComputerName": null,
"ComputerTierId": null,
"CostCenter": null,
"CreationSource": null,
"CreationTime": null,
"DataExchangeEnabled": null,
"DelayStart": null,
"DelayStartSeconds": null,
"DeployPath": null,
"DeploymentErrorInfo": {
"CloudProblem": null,
"Code": null,
"DetailedCode": null,
"DetailedErrorCode": null,
"DetailedSource": null,
"DisplayableErrorCode": null,
"ErrorCodeString": null,
"ErrorType": null,
"ExceptionDetails": null,
"IsConditionallyTerminating": null,
"IsDeploymentBlocker": null,
"IsMomAlert": null,
"IsSuccess": null,
"IsTerminating": null,
"MessageParameters": null,
"MomAlertSeverity": null,
"Problem": null,
"RecommendedAction": null,
"RecommendedActionCLI": null,
"ShowDetailedError": null,
"odata.type": "VMM.ErrorInfo"
},
"Description": null,
"DiskIO": null,
"Dismiss": null,
"Domain": null,
"DynamicMemoryBufferPercentage": null,
"DynamicMemoryDemandMB": null,
"DynamicMemoryEnabled": null,
"DynamicMemoryMaximumMB": null,
"Enabled": null,
"ExcludeFromPRO": null,
"ExpectedCPUUtilization": null,
"FailedJobID": null,
"FullName": null,
"Generation": null,
"GrantedToList": [],
"GrantedToList@odata.type": "Collection(VMM.UserAndRole)",
"HardwareProfileId": null,
"HasPassthroughDisk": null,
"HasSavedState": null,
"HasVMAdditions": null,
"HeartbeatEnabled": null,
"HighlyAvailable": null,
"ID": "00000000-0000-0000-0000-000000000000",
"IsFaultTolerant": null,
"IsHighlyAvailable": null,
"IsRecoveryVM": null,
"IsUndergoingLiveMigration": null,
"LastRestoredCheckpointId": null,
"LibraryGroup": null,
"LimitCPUForMigration": null,
"LimitCPUFunctionality": null,
"LinuxAdministratorSSHKey": null,
"LinuxAdministratorSSHKeyString": null,
"LinuxDomainName": null,
"LocalAdminPassword": null,
"LocalAdminRunAsAccountName": null,
"LocalAdminUserName": null,
"Location": null,
"MarkedAsTemplate": null,
"Memory": null,
"MemoryAssignedMB": null,
"MemoryAvailablePercentage": null,
"MemoryWeight": null,
"ModifiedTime": null,
"MostRecentTaskId": null,
"Name": "redvm",
"NetworkUtilization": null,
"NewVirtualNetworkAdapterInput": [],
"NewVirtualNetworkAdapterInput@odata.type": "Collection(VMM.NewVMVirtualNetworkAdapterInput)",
"NumLock": null,
"OperatingSystem": null,
"OperatingSystemInstance": {
"Architecture": null,
"Description": null,
"Edition": null,
"Name": null,
"OSType": null,
"ProductType": null,
"Version": null,
"odata.type": "VMM.OperatingSystem"
},
"OperatingSystemShutdownEnabled": null,
"Operation": null,
"OrganizationName": null,
"Owner": {
"RoleID": null,
"RoleName": null,
"UserName": null,
"odata.type": "VMM.UserAndRole"
},
"Password": null,
"Path": null,
"PerfCPUUtilization": null,
"PerfDiskBytesRead": null,
"PerfDiskBytesWrite": null,
"PerfNetworkBytesRead": null,
"PerfNetworkBytesWrite": null,
"ProductKey": null,
"Retry": null,
"RunAsAccountUserName": null,
"RunGuestAccount": null,
"ServiceDeploymentErrorMessage": null,
"ServiceId": null,
"SharePath": null,
"SourceObjectType": null,
"StampId": "444c4444-c44c-4444-c4c4-44ccc4444c4c",
"StartAction": null,
"StartVM": null,
"Status": null,
"StatusString": null,
"StopAction": null,
"Tag": null,
"TimeSynchronizationEnabled": null,
"TimeZone": null,
"TotalSize": null,
"Undo": null,
"UndoDisksEnabled": null,
"UpgradeDomain": null,
"UseCluster": null,
"UseLAN": null,
"UserName": null,
"VMBaseConfigurationId": null,
"VMCPath": null,
"VMConfigResource": null,
"VMHostName": null,
"VMId": null,
"VMNetworkAssignments": [],
"VMNetworkAssignments@odata.type": "Collection(VMM.VMNetworkAssignment)",
"VMResource": null,
"VMResourceGroup": null,
"VMTemplateId": null,
"VirtualHardDiskId": "d55ddddd-dd55-5d55-ddd5-d5dd55dd5dd5",
"VirtualMachineState": null,
"VirtualizationPlatform": null,
"WorkGroup": null,
"odata.type": "VMM.VirtualMachine"
}
The following Java code example, Create_vm, creates a new vm. It reads an Odata payload from odata.txt, streams this into a HTTP payload and then requests a POST operation to the VirtualMachines endpoint.
public class Create_vm
{
public static void main(String[] args) throws Exception
{
Data s = new Data();
String payload = s.getpayload();
String u = "https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VirtualMachines";
URL url = new URL(u);
HttpURLConnection c = null;
c = (HttpsURLConnection)url.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
c.setRequestProperty("DataServiceVersion", "3.0;NetFx");
c.setRequestProperty("MaxDataServiceVersion", "3.0;NetFx");
c.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
c.setRequestProperty("Accept-Charset", "UTF-8");
c.setRequestProperty("DataServiceUrlConventions", "KeyAsSegment");
c.setRequestProperty("User-Agent", "Microsoft ADO.NET Data Services");
c.setRequestProperty("x-ms-principal-id", "user@contoso.com");
c.setRequestProperty("Content-Type","application/json;odata=minimalmetadata");
c.setRequestProperty("Host", "user@contoso.com");
c.setRequestProperty("Expect", "100-continue");
c.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
out.write(payload);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {System.out.println(decodedString);}
in.close();
}
}
When Create_vm creates a new virtual machine, there will be a HTTP response such as the following.
HTTP/1.1 201 Created
Cache-Control: no-cache
Content-Length: 4136
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Location: https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VirtualMachines(ID=guid'6e66ee6e-6e6e-6666-ee66-e666e666666e',StampId=guid'444c4444-c44c-4444-c4c4-44ccc4444c4c')
Server: Microsoft-IIS/8.5
x-ms-request-id: 57cf3554-f891-4206-8722-5e1ea3d76c16
X-Content-Type-Options: nosniff
request-id: 33c9dafc-df0d-0000-9ff4-ca330ddfce01
DataServiceVersion: 3.0;
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
Date: Thu, 21 Nov 2013 20:54:05 GMT
{…response payload…}
The virtual machine ID guid for the new virtual machine “redvm” appears in the response. In later examples “redvm” has a virtual machine ID represented by the string: 6e66ee6e-6e6e-6666-ee66-e666e666666e.
To create another new virtual machine, call Create_vm again but change the value of Name in odata.txt to "greenvm". In the following examples, this virtual machine has a different virtual machine ID: 77ff7777-7777-7777-ff7f-f7f7f77777f7.
Starting and Stopping a Virtual Machine
When Create_vm creates a virtual machine, the new machine is created in the “Stopped” state. To start the “redvm” virtual machine, you can update the virtual machine object by sending a MERGE request to the location of “redvvm.” In a MERGE operation only the properties sent in the payload get updated. In this case, the content of the odata.txt file is as follows.
{
"odata.type": "VMM.VirtualMachine",
"ModifiedTime": "2013-08-06T23:17:18.4061005-07:00",
"Operation": "Start"
}
The following Java code, Startvm, reads odata.txt and sends a MERGE to update the “redvm” virtual machine. The example uses the X-HTTP-Method header to override the POST operation with MERGE.
public class Startvm
{
public static void main(String[] args) throws Exception
{
Data s = new Data();
String payload = s.getpayload();
String u = "https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VirtualMachines(ID=guid'6e66ee6e-6e6e-6666-ee66-e666e666666e',StampId=guid'444c4444-c44c-4444-c4c4-44ccc4444c4c')";
URL url = new URL(u);
HttpURLConnection c = null;
c = (HttpsURLConnection)url.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("X-HTTP-Method", "MERGE");
c.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
c.setRequestProperty("DataServiceVersion", "3.0;NetFx");
c.setRequestProperty("MaxDataServiceVersion", "3.0;NetFx");
c.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
c.setRequestProperty("Accept-Charset", "UTF-8");
c.setRequestProperty("DataServiceUrlConventions", "KeyAsSegment");
c.setRequestProperty("User-Agent", "Microsoft ADO.NET Data Services");
c.setRequestProperty("x-ms-principal-id", "user@contoso.com");
c.setRequestProperty("Content-Type","application/json;odata=minimalmetadata");
c.setRequestProperty("Host", "user@contoso.com");
c.setRequestProperty("Expect", "100-continue");
c.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
out.write(payload);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(c.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {System.out.println(decodedString);}
in.close();
}
}
If the virtual machine starts, there will be a HTTP response indicating that the server has processed the request.
To stop a running virtual machine, you can use Startvm again after changing the operation property to “Stop” in odata.txt.
{
"odata.type": "VMM.VirtualMachine",
"ModifiedTime": "2013-08-06T23:17:18.4061005-08:00",
"Operation": "Stop"
}
Delete a Virtual Machine
You must stop a running virtual machine before deleting it. To delete a virtual machine, send a DELETE request to the resource’s uri with an empty OData payload. The following Java code sends a DELETE with an empty payload to the location of the “greenvm” virtual machine. The example uses the X-HTTP-Method header to override the POST operation with DELETE.
public class Deletevm
{
public static void main(String[] args) throws Exception
{
String payload ="";
String u = "https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VirtualMachines(ID=77ff7777-7777-7777-ff7f-f7f7f77777f7',StampId= guid'444c4444-c44c-4444-c4c4-44ccc4444c4c')";
URL url = new URL(u);
HttpURLConnection c = null;
c = (HttpsURLConnection)url.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("X-HTTP-Method", "DELETE");
c.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
c.setRequestProperty("DataServiceVersion", "3.0;NetFx");
c.setRequestProperty("MaxDataServiceVersion", "3.0;NetFx");
c.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
c.setRequestProperty("Accept-Charset", "UTF-8");
c.setRequestProperty("DataServiceUrlConventions", "KeyAsSegment");
c.setRequestProperty("User-Agent", "Microsoft ADO.NET Data Services");
c.setRequestProperty("x-ms-principal-id", "user@contoso.com");
c.setRequestProperty("Content-Type","application/json;odata=minimalmetadata");
c.setRequestProperty("Host", "user@contoso.com");
c.setRequestProperty("Expect", "100-continue");
c.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
out.write(payload);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {System.out.println(decodedString);}
in.close();
}
}
Create a Virtual Machine Checkpoint
Virtual machine checkpoints provide a way to capture the state of a virtual machine. The checkpoint can be used to restore the virtual machine back to the way it was when the checkpoint was created. To create a new virtual machine checkpoint, send a POST to the url of the VMCheckPoints collection of VMCheckPoint objects in your subscription. The OData in the payload should provide the guids identifying the stamp and virtual machine. For this example, the contents of odata.txt to create a checkpoint for the virtual machine “redvm” is the following.
{
"odata.type": "VMM.VMCheckPoint",
"Accessibility": null,
"AddedTime": null,
"CheckpointID": null,
"Confirm": null,
"Description": "This is a snapshot of the VM taken at 11/19/2013 2:28:00 PM",
"Enabled": null,
"ID": "00000000-0000-0000-0000-000000000000",
"ModifiedTime": null,
"Name": "Testing Checkpoint #1",
"ParentCheckpointID": null,
"RunAsynchronously": null,
"StampId": "444c4444-c44c-4444-c4c4-44ccc4444c4c",
"VMCheckPointAction": null,
"VMId": "6e66ee6e-6e6e-6666-ee66-e666e666666e"
}
The following Java code example reads odata.txt and sends a POST with the OData as the payload to the URI. This creates a checkpoint for the virtual machine “redvm”.
public class Create_ckpt
{
public static void main(String[] args) throws Exception
{
Data s = new Data();
String payload = s.getpayload();
String u = "https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VMCheckPoints";
URL url = new URL(u);
HttpURLConnection c = null;
c = (HttpsURLConnection)url.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
c.setRequestProperty("DataServiceVersion", "3.0;NetFx");
c.setRequestProperty("MaxDataServiceVersion", "3.0;NetFx");
c.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
c.setRequestProperty("Accept-Charset", "UTF-8");
c.setRequestProperty("DataServiceUrlConventions", "KeyAsSegment");
c.setRequestProperty("User-Agent", "Microsoft ADO.NET Data Services");
c.setRequestProperty("x-ms-principal-id", "user@contoso.com");
c.setRequestProperty("Content-Type","application/json;odata=minimalmetadata");
c.setRequestProperty("Host", "user@contoso.com");
c.setRequestProperty("Expect", "100-continue");
c.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
out.write(payload);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {System.out.println(decodedString);}
in.close();
}
}
The HTTP response contains information for the VMCheckPoint object created for “redvm”.
HTTP/1.1 201 Created
Cache-Control: no-cache
Content-Length: 649
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Location: https://smapi-server:30006/3115ac40-25f4-4a24-8e73-5cbeee9ebbbd/services/systemcenter/vmm/VMCheckPoints(ID=guid'h88h8h8h-8hh8-88hh-hh88-888h8888hh8h',StampId=guid'444c4444-c44c-4444-c4c4-44ccc4444c4c')
Server: Microsoft-IIS/8.5
x-ms-request-id: d6ac9c14-b6ef-463e-9ba2-6e73639d919e
X-Content-Type-Options: nosniff
request-id: 33c9dafc-df0d-0000-9b07-cb330ddfce01
DataServiceVersion: 3.0;
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
Date: Fri, 22 Nov 2013 18:42:37 GMT
{"odata.metadata":"https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/$metadata#VMCheckPoints/@Element","Accessibility":"Public","CheckpointID":null,"Description":"This is a snapshot of the VM taken at 11/19/2013 2:28:00 PM","Enabled":true,"ID":"h88h8h8h-8hh8-88hh-hh88-888h8888hh8h","Name":"Testing Checkpoint #1","ParentCheckpointID":null,"VMId":"6e66ee6e-6e6e-6666-ee66-e666e666666e","AddedTime":"2013-11-22T10:42:38.0658285-08:00","ModifiedTime":"2013-11-22T10:42:38.0908291-08:00","StampId":"444c4444-c44c-4444-c4c4-44ccc4444c4c","VMCheckPointAction":null,"Confirm":null,"RunAsynchronously":null}
This response indicates that the checkpoint ID guid for this virtual machine checkpoint is h88h8h8h-8hh8-88hh-hh88-888h8888hh8h.
Restore a Virtual Machine from a Checkpoint
To restore a virtual machine to a previously saved checkpoint state, update an existing checkpoint object by setting the VMCheckPointAction property to Restore and submit the changed entity back to the server. This can be done with a MERGE operation. The contents of odata.txt in this case will look as follows.
{
"VMCheckPointAction": "Restore",
"odata.type": "VMM.VMCheckPoint"
}
The example, Restore_ckpt, restores the “redvm” virtual machine to the “Testing Checkpoint.” It reads odata.txt and sends a MERGE to the URI of “Testing Checkpoint.”
public class Restore_ckpt
{
public static void main(String[] args) throws Exception
{
Data s = new Data();
String payload = s.getpayload();
String u = "https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VMCheckPoints(ID=guid'h88h8h8h-8hh8-88hh-hh88-888h8888hh8h',StampId=guid'444c4444-c44c-4444-c4c4-44ccc4444c4c')";
System.out.println(u);
URL url = new URL(u);
HttpURLConnection c = null;
c = (HttpsURLConnection)url.openConnection();
c.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
c.setRequestMethod("POST");
c.setRequestProperty("X-HTTP-Method", "MERGE");
c.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
c.setRequestProperty("DataServiceVersion", "3.0;NetFx");
c.setRequestProperty("MaxDataServiceVersion", "3.0;NetFx");
c.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
c.setRequestProperty("Accept-Charset", "UTF-8");
c.setRequestProperty("DataServiceUrlConventions", "KeyAsSegment");
c.setRequestProperty("User-Agent", "Microsoft ADO.NET Data Services");
c.setRequestProperty("x-ms-principal-id", "user@contoso.com");
c.setRequestProperty("Content-Type","application/json;odata=minimalmetadata");
c.setRequestProperty("Host", "user@contoso.com");
c.setRequestProperty("Expect", "100-continue");
c.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
out.write(payload);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {System.out.println(decodedString);}
in.close();
}
}
Delete a Virtual Machine Checkpoint
To delete a virtual machine checkpoint, your application can use the standard OData method of deleting a resource. A checkpoint can be deleted by calling the DELETE operation on the checkpoint identified by its URL. The following Java code deletes the “Testing Checkpoint” for the “redvm” virtual machine.
public class Deleteckpt
{
public static void main(String[] args) throws Exception
{
String payload ="";
String u = "https://smapi-server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/services/systemcenter/vmm/VMCheckPoints(ID=guid'h88h8h8h-8hh8-88hh-hh88-888h8888hh8h',StampId=guid'444c4444-c44c-4444-c4c4-44ccc4444c4c')";
URL url = new URL(u);
HttpURLConnection c = null;
c = (HttpsURLConnection)url.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("X-HTTP-Method", "DELETE");
c.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
c.setRequestProperty("DataServiceVersion", "3.0;NetFx");
c.setRequestProperty("MaxDataServiceVersion", "3.0;NetFx");
c.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
c.setRequestProperty("Accept-Charset", "UTF-8");
c.setRequestProperty("DataServiceUrlConventions", "KeyAsSegment");
c.setRequestProperty("User-Agent", "Microsoft ADO.NET Data Services");
c.setRequestProperty("x-ms-principal-id", "user@contoso.com");
c.setRequestProperty("Content-Type","application/json;odata=minimalmetadata");
c.setRequestProperty("Host", "user@contoso.com");
c.setRequestProperty("Expect", "100-continue");
c.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
out.write(payload);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {System.out.println(decodedString);}
in.close();
}
}
See Also
Service Provider Foundation Developer's Guide
Virtual Machine Management