在 Windows Azure Pack 和 Java 中使用 VM 角色
适用于:Windows Azure Pack
本指南演示租户开发人员可以使用虚拟机角色 (VM 角色) 执行一些基本任务,包括创建、更新和缩放 VM 角色实例。 代码示例是用 Java 编写的,是使用 Eclipse IDE 创建的。 由于本指南中的示例使用服务管理 API 的基于 HTTP REST 的服务,因此可以修改这些示例以使用能够发送 HTTP 操作请求的任何其他语言。 有关可用于 VM 角色的所有 URL 的指南,请参阅 VM 角色 [SPFSDK][VMROLE] 的 URL 备忘单。
VM 角色可以表示专用于特定操作的一个或多个虚拟机,例如 Web 服务器或 Web 辅助角色。 服务提供商可以通过特选的虚拟机角色库为租户提供用于预配虚拟机的自助服务体验。 租户可以使用租户门户 UI 或基于 HTTP REST 的服务从库预配 VM 角色。 VM 角色不同于传统的预配虚拟机模型,因为它们提供缩放操作,使你能够轻松调整虚拟机的数量和版本。 有关将虚拟机与 WAP 和 Java 配合使用的传统预配模型的指南,请参阅 使用 Java 的虚拟机管理。 需要调整虚拟机的数量和版本时,VM 角色提供的功能可以帮助快速预配和取消预配应用程序。
service Provider Foundation 和 Windows Azure Pack for Windows Server 公开一项可扩展服务,使服务提供商能够生成多租户门户。 租户是服务提供商的自助服务客户。 服务提供商将租户的帐户与订阅 ID 相关联,并为用于验证租户的安全证书提供公钥。 在本指南中运行示例的先决条件是,需要使用提供 VM 角色库的服务提供商、订阅中的云服务来托管 VM 角色,以及订阅中的虚拟网络来放置虚拟机。 如果服务提供商已提供用户名和密码,则可以登录到租户门户 UI,并在那里找到你的订阅 ID。登录到门户时,可以上传证书,使主机能够验证你是否为受信任的用户,并且可以创建可用于放置虚拟机的虚拟网络。
在本指南中运行示例后,应能够使用 Java 代码执行以下任务。
创建用于托管 VM 角色的云服务
从库获取 VM 角色列表
获取对 VM 角色库项的引用
创建新的 VM 角色实例
缩放 VM 角色
"开始"菜单、停止、重启、关闭或删除虚拟机
更新或删除 VM 角色
创建用于托管 VM 角色的云服务
订阅中必须有云服务才能托管 VM 角色。 若要列出所有云服务,请将 HTTP GET 操作请求发送到 CloudServices 的以下 URL。 请注意,每当对 VM 角色库或云服务使用 URL 时,还必须追加 api-version=2013-03 查询字符串。 查询字符串始终以 ? URL 后面的字符。
https://server:port/subscription-id/CloudServices?api-version=2013-03
以下 Java 代码示例(Get_list)可以返回订阅中的所有云服务。 本指南中的示例将按字符串表示订阅 ID:222aa22-22a2-2a22-2a22-2a22-2aaaaa2aaaaa。 通常,可以将 x-ms-principal-id 标头设置为与当前订阅关联的租户的电子邮件。
public class Get_list
{
public static void main(String[] args) throws Exception
{
String u = "https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices?api-version=2013-03";
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();
}
}
如果 HTTP 响应中的值字段为空,这意味着订阅中没有云服务,并且需要在预配 VM 角色之前创建一个云服务。 可以通过向同一 CloudServices URL 发送 HTTP POST 操作请求来创建云服务,但在请求正文中,应为新云服务指定名称和标签。 对于本指南中的示例,添加到 HTTP 请求正文的 OData 可以保存在名为odata.txt的计算机上的文本文件中。 例如,发送以下odata.txt可用于创建名为 TestingCloudService799 的云服务。
{
"Name": "TestingCloudService799",
"Label": "TestingCloudService799"
}
所有 Java 代码示例都使用以下 getpayload () 方法读取odata.txt。
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;}
}
Java 代码示例Create_cs创建名为 TestingCloudService799 的新云服务。 它会读取odata.txt,将此信息流式传输到 HTTP 正文中,设置标头,然后将 POST 操作请求发送到 Cloudservices 终结点。
public class Create_cs
{
public static void main(String[] args) throws Exception
{
Data s = new Data();
String payload = s.getpayload();
String u = "https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices?api-version=2013-03";
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();
}
}
从库获取 VM 角色列表
服务提供商可以为租户提供虚拟机角色的自助服务库。 然后,租户可以从其中一个 VM 角色库项创建 VM 角色。 可以通过向 VM 角色库的以下 URL 发送 HTTP GET 操作请求来查询提供给订阅的所有 VM 角色。 例如,可以使用以下 URL 和Get_list获取提供给订阅的 VM 角色。
https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/Gallery/GalleryItems/$/MicrosoftCompute.VMRoleGalleryItem?api-version=2013-03
下面是包含 VM 角色库项集合的 HTTP 响应的示例。
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 2148
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Content-Language: en-US
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
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, 05 Feb 2014 20:11:29 GMT
{"odata.metadata":"https://server:port/SC2012R2/VMM/GalleryService.svc/$metadata#GalleryItems/MicrosoftCompute.VMRoleGalleryItem","value":[{"odata.type":"MicrosoftCompute.VMRoleGalleryItem","Name":"CentOS6LAMP","Publisher":"Microsoft","Version":"1.0.0.0","ContentUrl":"Gallery/GalleryItems(Name%3d%27CentOS6LAMP%27,Version%3d%271.0.0.0%27,Publisher%3d%27Microsoft%27)/Content","Description":"Deploy a CentOS 6 virtual machine role with Apache, MySQL and PHP installed.","IconUrl":null,"Label":"CentOS6 LAMP Role","PublishDate":"2014-01-21T19:09:11.163","PublisherLabel":"Microsoft","ResourceDefinition@odata.mediaContentType":"application/json","ResourceDefinitionUrl":"Gallery/GalleryItems(Name%3d%27CentOS6LAMP%27,Version%3d%271.0.0.0%27,Publisher%3d%27Microsoft%27)/MicrosoftCompute.ResourceDefinitionGalleryItem/ResourceDefinition","ViewDefinitionUrl":"Gallery/ViewDefinitions(Name%3d%27CentOS6LAMP%27,Version%3d%271.0.0.0%27,Publisher%3d%27Microsoft%27)/%24value"}]}
此响应指示服务提供商提供一个 VM 角色:已安装 Apache、MySQL 和 PHP 的 CentOS 6 虚拟机角色。 其他项可能会显示在库中,具体取决于向订阅提供哪些 VM 角色。 请注意响应中为该项提供 ContentUrl 属性的字符串。 需要使用此值来获取对特定项的引用。
“ContentUrl”:“Gallery/GalleryItems (Name%3d%27CentOS6LAMP%27,Version%3d%271.0.0.0%27,Publisher%3d%27Microsoft%27) ”
获取对 VM 角色库项的引用
从库中选择 VM 角色项后,获取该项目的资源定义,并确定需要提供的资源参数。 资源定义是描述虚拟机硬件和实例化限制的 JSON 文件。 有关资源定义的详细信息,请参阅 ResourceDefinition [SPFSDK][VMROLE] 部分。
使用Get_list向所选库项的 URL 发送 GET 操作请求。
https://server:port/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/Gallery/GalleryItems(Name%3d%27CentOS6LAMP%27,Version%3d%271.0.0.0%27,Publisher%3d%27Microsoft%27) /MicrosoftCompute.ResourceDefinitionGalleryItem/ResourceDefinition?api-version=2013-03
在此示例中,此 HTTP 响应包括 CentOS VM 角色的 ResourceDefinition 对象。
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 2009
Content-Type: application/json
Content-Language: en-US
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
DataServiceVersion: 1.0;
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
Date: Thu, 06 Feb 2014 17:03:10 GMT
{"IntrinsicSettings":{"HardwareProfile":{"VMSize":"[Param.VMRoleVMSize]"},"NetworkProfile":{"NetworkAdapters":[{"IPAddresses":[{"AllocationMethod":"Dynamic","ConfigurationName":"IPV4Configuration","Type":"IPV4"}],"Name":"NIC1","NetworkRef":"[Param.VMRoleNetworkRef]"}]},"OperatingSystemProfile":{"AdminCredential":"[Param.VMRoleAdminCredential]","ComputerNamePattern":"[Param.VMRoleComputerNamePattern]","LinuxOperatingSystemProfile":{"DNSDomainName":"[Param.VMRoleDNSDomainName]","SSHPublicKey":"[Param.VMRoleSSHPublicKey]"},"TimeZone":"[Param.VMRoleTimeZone]","WindowsOperatingSystemProfile":null},"ScaleOutSettings":{"InitialInstanceCount":"1","MaximumInstanceCount":"5","MinimumInstanceCount":"1","UpgradeDomainCount":"1"},"StorageProfile":{"OSVirtualHardDiskImage":"[Param.VMRoleOSVirtualHardDiskImage]"}},"Name":"CentOS6LAMP","Publisher":"Microsoft","ResourceExtensionReferences":[{"Name":"CentOS6LAMP","Publisher":"Microsoft","ReferenceName":"CentOS6LAMP","ResourceExtensionParameterValues":"{\"MySQLRootPassword\":\"[Param.CentOS6LAMPMySQLRootPassword]\"}","Version":"1.0.0.0"}],"ResourceParameters":[{"Description":"Computer size","Name":"VMRoleVMSize","Type":"String"},{"Description":"Operating system disk","Name":"VMRoleOSVirtualHardDiskImage","Type":"String"},{"Description":"Network reference","Name":"VMRoleNetworkRef","Type":"String"},{"Description":"Resource Extension CentOS6LAMP. Parameter MySQLRootPassword. Run once command parameter","Name":"CentOS6LAMPMySQLRootPassword","Type":"SecureString"},{"Description":"Compute name pattern","Name":"VMRoleComputerNamePattern","Type":"String"},{"Description":"Time zone","Name":"VMRoleTimeZone","Type":"String"},{"Description":"Administrator credential","Name":"VMRoleAdminCredential","Type":"Credential"},{"Description":"DNS domain name","Name":"VMRoleDNSDomainName","Type":"String"},{"Description":"SSH public key","Name":"VMRoleSSHPublicKey","Type":"String"}],"SchemaVersion":"1.0","Type":"Microsoft.Compute\/VMRole\/1.0","Version":"1.0.0.0"}
请注意,ResourceParameters 属性列出参数。 尽管并非每个 VM 角色都需要具有参数,但如果 ResourceDefinition 对象的 ResourceParameters 属性中列出了任何参数,则必须为每个参数提供一个值。 可以通过使用以下格式将参数及其值打包到 JSON 编码的字符串中来提供参数及其值。
{ “parameter1 name” : “parameter1 value”, “parameter2 name” : “parameter2 value”, ... }
收集 ParameterValues 后,可以生成包含 ParameterValues 和参数值的版本的 ResourceConfiguration 对象。 在本指南中,示例 ResourceConfiguration 对象使用以下参数值。
"ResourceConfiguration":
{
"ParameterValues": "{\"VMRoleVMSize\" : \"ExtraSmall\",\"VMRoleOSVirtualHardDiskImage\" : \"CentOS Linux 6 (64-bit):1.0.0.0\",\"VMRoleNetworkRef\" : \"VMNetwork1\",\"CentOS6LAMPMySQLRootPassword\" : \"!!pass3abc12\",\"VMRoleComputerNamePattern\" : \"LAMP###\",\"VMRoleTimeZone\" : \"Pacific Standard Time\",\"VMRoleAdminCredential\" : \"root:!!pass3abc12\",\"VMRoleDNSDomainName\" : \"mydns\",\"VMRoleSSHPublicKey\" : \"key123\"}",
"Version": "1.0.0.0"
}
请注意,名为 VMNetwork1 的虚拟网络必须已存在于租户的订阅中。 必须指定虚拟网络才能放置虚拟机。 可以使用订阅的租户 UI 门户创建虚拟网络。
创建新的 VM 角色实例
通过组合从 VM 角色库检索到的 ResourceDefinition 对象和在上一步中生成的 ResourceConfiguration 对象来生成新的 VirtualMachineRole 对象。 然后将整个 VirtualMachineRole 对象作为 HTTP POST 操作请求的正文发送到 VMRoles 的 URL。
https://server:port/subscription-id/CloudServices/cloudservice-name/Resources/MicrosoftCompute/VMRoles?api-version=2013-03
例如,odata.txt可以包含以下 VitualMachineRole 对象。
{
"InstanceView": null,
"Label": "My VM Role Instance",
"Name": "TestVMRole",
"ProvisioningState": null,
"ResourceConfiguration": {
"ParameterValues": "{\"VMRoleVMSize\" : \"ExtraSmall\",\"VMRoleOSVirtualHardDiskImage\" : \"CentOS Linux 6 (64-bit):1.0.0.0\",\"VMRoleNetworkRef\" : \"VMNetwork1\",\"CentOS6LAMPMySQLRootPassword\" : \"!!pass3abc12\",\"VMRoleComputerNamePattern\" : \"LAMP###\",\"VMRoleTimeZone\" : \"Pacific Standard Time\",\"VMRoleAdminCredential\" : \"root:!!pass3abc12\",\"VMRoleDNSDomainName\" : \"mydns\",\"VMRoleSSHPublicKey\" : \"key123\"}",
"Version": "1.0.0.0"
},
"ResourceDefinition": {
"IntrinsicSettings": {
"HardwareProfile": { "VMSize": "[Param.VMRoleVMSize]" },
"NetworkProfile": {
"NetworkAdapters": [{
"IPAddresses": [{
"AllocationMethod": "Dynamic",
"ConfigurationName": "IPV4Configuration",
"LoadBalancerConfigurations": [],
"Type": "IPV4"
}],
"Name": "NIC1",
"NetworkRef": "[Param.VMRoleNetworkRef]"
}]
},
"OperatingSystemProfile": {
"AdminCredential": "[Param.VMRoleAdminCredential]",
"ComputerNamePattern": "[Param.VMRoleComputerNamePattern]",
"LinuxOperatingSystemProfile": {
"DNSDomainName": "[Param.VMRoleDNSDomainName]",
"SSHPublicKey": "[Param.VMRoleSSHPublicKey]"
},
"TimeZone": "[Param.VMRoleTimeZone]",
"WindowsOperatingSystemProfile": null
},
"ScaleOutSettings": {
"InitialInstanceCount": "1",
"MaximumInstanceCount": "5",
"MinimumInstanceCount": "1",
"UpgradeDomainCount": "1"
},
"StorageProfile": {
"DataVirtualHardDisks": [],
"OSVirtualHardDiskImage": "[Param.VMRoleOSVirtualHardDiskImage]"
}
},
"Name": "CentOS6LAMP",
"Publisher": "Microsoft",
"ResourceExtensionReferences": [{
"Name": "CentOS6LAMP",
"Publisher": "Microsoft",
"ReferenceName": "CentOS6LAMP",
"ResourceExtensionParameterValues": "{\"MySQLRootPassword\":\"[Param.CentOS6LAMPMySQLRootPassword]\"}",
"Version": "1.0.0.0"
}],
"ResourceParameters": [{
"Description": "Computer size",
"Name": "VMRoleVMSize",
"Type": "String"
},
{
"Description": "Operating system disk",
"Name": "VMRoleOSVirtualHardDiskImage",
"Type": "String"
},
{
"Description": "Network reference",
"Name": "VMRoleNetworkRef",
"Type": "String"
},
{
"Description": "Resource Extension CentOS6LAMP. Parameter MySQLRootPassword. Run conce command parameter",
"Name": "CentOS6LAMPMySQLRootPassword",
"Type": "SecureString"
},
{
"Description": "Compute name pattern",
"Name": "VMRoleComputerNamePattern",
"Type": "String"
},
{
"Description": "Time zone",
"Name": "VMRoleTimeZone",
"Type": "String"
},
{
"Description": "Administrator credential",
"Name": "VMRoleAdminCredential",
"Type": "Credential"
},
{
"Description": "DNS domain name",
"Name": "VMRoleDNSDomainName",
"Type": "String"
},
{
"Description": "SSH public key",
"Name": "VMRoleSSHPublicKey",
"Type": "String"
}
],
"SchemaVersion": "1.0",
"Type": "Microsoft.Compute/VMRole/1.0",
"Version": "1.0.0.0"
},
"Substate": null
}
可以使用以下 Java 代码、Create_vmr和示例 VirtualMachine 对象创建名为 TestVMRole 的新 VM 角色。
public class Create_vmr
{
public static void main(String[] args) throws Exception
{
Data s = new Data();
String payload = s.getpayload();
String u = "https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles?api-version=2013-03";
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();
}
}
由于 InitialInstanceCount 为 1,因此将一个名为 LAMP0001 的 TestVMRole 虚拟机放置在 VMNetwork1 上并启动。 可以通过向 TestVMRole VM 的 URL 发送 HTTP GET 操作请求来获取此新虚拟机的 ID。
https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole/VMs?api-version=2013-03
VM 的唯一 ID 由字符串 6e66ee6e-6e6e-6666-ee666-e666e66666e 表示。
缩放 VM 角色
可以通过向 VM 角色和缩放终结点的 URL 发送 HTTP POST 操作请求来调整 VM 角色实例中运行的虚拟机数量。 实例数不能小于在 VitualMachineRole 对象中指定的实例数或最大值。 例如,使用以下 URL 调整 TestVMRole 角色的规模。
https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole/Scale?api-version=2013-03
POST 操作请求的正文应指定要为 VM 角色实例化为 InstanceCount 的虚拟机数。 发送以下odata.txt将 TestVMRole 中运行的虚拟机数增加到两个。
{
"InstanceCount": 2
}
若要获取 TestVMRole 角色中当前所有虚拟机的列表,请将 HTTP GET 操作请求发送到 VM 的 URL。
https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole/VMs?api-version=2013-03
示例 HTTP 响应如下所示。
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 496
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
request-id: d3350337-10af-0000-897f-39d3af10cf01
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, 06 Feb 2014 21:52:56 GMT
{"odata.metadata":"https://server:8090/SC2012R2/VMM/Microsoft.Management.Odata.svc/$metadata#VM","value":[{"Id":"6e66ee6e-6e6e-6666-ee66-e666e666666e","ComputerName":"LAMP001.mydns","RuntimeState":"Running","ConnectToAddresses":[{"IPAddress":"10.0.0.4","NetworkName":"VMNetwork1","Port":3389}]},{"Id":"77ff7777-7777-7777-ff7f-f7f7f77777f7","ComputerName":"LAMP002","RuntimeState":"Running","ConnectToAddresses":[{"IPAddress":"10.0.0.5","NetworkName":"VMNetwork1","Port":3389}]}]}
HTTP 响应显示,名为 LAMP0002 的 TestVMRole 角色的第二个虚拟机,由 77ff7777-7777-7777-ff7f-f7f7f7f7777f7 运行。
请注意,如果将 VM 角色缩放到小于当前虚拟机数的实例计数,则会删除某些 VM(无论它们是否正在运行)。 如果要删除 VM 角色中的特定虚拟机,请参阅以下部分"开始"菜单、停止、重启、关闭或删除虚拟机。
"开始"菜单、停止、重启、关闭或删除虚拟机
可以通过将 HTTP POST 操作请求发送到具有空正文的以下 URL 来停止虚拟机。 例如,以下 Java 代码示例停止 LAMP002,其中包含 ID=77ff7777-7777-7777-ff7f-f7f7f7f7777f7。
public class Start_vmr
{
public static void main(String[] args) throws Exception
{
String payload ="";
String u = "https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole/VMs/77ff7777-7777-7777-ff7f-f7f7f77777f7/Stop?api-version=2013-03";
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();
}
}
还可以使用此示例 Java 代码发出 HTTP POST 操作请求来启动、重启或关闭 VM。 使用以下 URL 启动已停止的 LAMP0002。
https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole/VMs/77ff7777-7777-7777-ff7f-f7f7f77777f7/Start?api-version=2013-03
使用以下 URL 重启正在运行的 LAMP0002。
https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole/VMs/77ff7777-7777-7777-ff7f-f7f7f77777f7/Restart?api-version=2013-03
使用以下 URL 关闭正在运行的 LAMP0002。
https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole/VMs/77ff7777-7777-7777-ff7f-f7f7f77777f7/Shutdown?api-version=2013-03
可以通过向具有空有效负载的 VM 的终结点发送 HTTP DELETE 操作请求来删除特定虚拟机。 删除 VM 之前,应停止 VM。 请注意,该示例使用 X-HTTP-Method 标头使用 DELETE 替代 POST 操作。 例如,以下 Java 代码Delete_vm删除 ID=77ff7777-7777-7777-ff7f-f7f7f7f7f77777f7 的 VM。
public class Delete_vm
{
public static void main(String[] args) throws Exception
{
String payload ="";
String u = "https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole/VMs/77ff7777-7777-7777-ff7f-f7f7f77777f7?api-version=2013-03";
URL url = new URL(u);
HttpURLConnection c = null;
c = (HttpsURLConnection)url.openConnection();
TrustModifier.relaxHostChecking(c); // ignore host checking errors
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();
}
}
请注意,这会专门删除虚拟机 LAMP0002。 如果 TestVMRole 从 2 个实例缩减到 1 个实例,则即使以前已停止 LAMP0002,虚拟机 LAMP0001 也会被删除。
更新或删除 VM 角色
可以在以前版本的虚拟机继续运行时将 VM 角色实例更新为新版本。 如果通过横向扩展 VM 角色来添加新虚拟机,则新虚拟机将获取 VM 角色的更新版本。 基于这两个版本的虚拟机可能同时运行。 可能需要根据早期版本停止或删除这些特定虚拟机。
可以通过向 VM 角色的 URL 发送 HTTP MERGE 操作请求来更新 VM 角色。 正文包含要合并到 VirtualMachineRole 中的更新信息。
https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole?api-version=2013-03
例如,以下odata.txt将 TestVMRole 角色从版本 1.0.0.0 更新为版本 1.0.0.1。 而版本 1.0.0.0 将虚拟机放置在 VMNetwork1 上,则示例版本 1.0.0.1 会将虚拟机置于 VMNetwork2 上。
{
"ResourceConfiguration": {
"ParameterValues": "{\"VMRoleVMSize\" : \"ExtraSmall\",\"VMRoleOSVirtualHardDiskImage\" : \"CentOS Linux 6 (64-bit):1.0.0.0\",\"VMRoleNetworkRef\" : \"VMNetwork2\",\"CentOS6LAMPMySQLRootPassword\" : \"!!pass3abc12\",\"VMRoleComputerNamePattern\" : \"LAMP###\",\"VMRoleTimeZone\" : \"Pacific Standard Time\",\"VMRoleAdminCredential\" : \"root:!!pass3abc12\",\"VMRoleDNSDomainName\" : \"mydns\",\"VMRoleSSHPublicKey\" : \"key123\"}",
"Version": "1.0.0.1"
}
}
以下 Java 代码示例可以更新 TestVMRole 版本。 请注意,该示例使用 X-HTTP-Method 标头替代使用 MERGE 的 POST 操作。
public class Update_vmr
{
public static void main(String[] args) throws Exception
{
Data s = new Data();
String payload = s.getpayload();
String u = "https://server:30006/2222aa22-22a2-2a22-2a22-2aaaaa2aaaaa/CloudServices/TestingCloudService799/Resources/MicrosoftCompute/VMRoles/TestVMRole?api-version=2013-03";
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();
}
}
运行此代码后,如果创建了任何新的 TestVMRole VM,这些 VM 将为版本 1.0.0.1。 现有版本 1.0.0.0 VM 继续运行。 例如,将 TestVMRole 的规模从 1 增加到 2。 新虚拟机使用新版本并在 VMNetwork2 上运行。 在 VMNetwork1 上运行的虚拟机继续在 VMNetwork1 上运行。 可以减少实例数,或删除较旧的虚拟机,以更新以前的 VM 角色版本的所有实例。
若要删除 VM 角色,以及角色中的所有虚拟机,请停止虚拟机,并将 HTTP DELETE 操作请求发送到具有空正文的 VM 角色的 URL。 使用 X-HTTP-Method 标头通过 DELETE 替代 POST 操作。
另请参阅
使用 Java 进行虚拟机管理
VM 角色租户服务 [SPFSDK][VMROLE]
VM 角色 JSON 参考 [SPFSDK][VMROLE]