1
#-------------------------------------------------------------------------
2
# Copyright (c) Microsoft. All rights reserved.
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
# http://www.apache.org/licenses/LICENSE-2.0
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
#--------------------------------------------------------------------------
15
from xml.dom import minidom
22
_general_error_handler,
23
_get_children_from_path,
24
_get_first_child_node_value,
30
#-----------------------------------------------------------------------------
31
# Constants for Azure app environment settings.
32
AZURE_MANAGEMENT_CERTFILE = 'AZURE_MANAGEMENT_CERTFILE'
33
AZURE_MANAGEMENT_SUBSCRIPTIONID = 'AZURE_MANAGEMENT_SUBSCRIPTIONID'
35
# x-ms-version for service management.
36
X_MS_VERSION = '2013-06-01'
38
#-----------------------------------------------------------------------------
42
class StorageServices(WindowsAzureData):
45
self.storage_services = _list_of(StorageService)
48
return iter(self.storage_services)
51
return len(self.storage_services)
53
def __getitem__(self, index):
54
return self.storage_services[index]
57
class StorageService(WindowsAzureData):
61
self.service_name = ''
62
self.storage_service_properties = StorageAccountProperties()
63
self.storage_service_keys = StorageServiceKeys()
64
self.extended_properties = _dict_of(
65
'ExtendedProperty', 'Name', 'Value')
66
self.capabilities = _scalar_list_of(str, 'Capability')
69
class StorageAccountProperties(WindowsAzureData):
72
self.description = u''
73
self.affinity_group = u''
75
self.label = _Base64String()
77
self.endpoints = _scalar_list_of(str, 'Endpoint')
78
self.geo_replication_enabled = False
79
self.geo_primary_region = u''
80
self.status_of_primary = u''
81
self.geo_secondary_region = u''
82
self.status_of_secondary = u''
83
self.last_geo_failover_time = u''
86
class StorageServiceKeys(WindowsAzureData):
93
class Locations(WindowsAzureData):
96
self.locations = _list_of(Location)
99
return iter(self.locations)
102
return len(self.locations)
104
def __getitem__(self, index):
105
return self.locations[index]
108
class Location(WindowsAzureData):
112
self.display_name = u''
113
self.available_services = _scalar_list_of(str, 'AvailableService')
116
class AffinityGroup(WindowsAzureData):
120
self.label = _Base64String()
121
self.description = u''
123
self.hosted_services = HostedServices()
124
self.storage_services = StorageServices()
125
self.capabilities = _scalar_list_of(str, 'Capability')
128
class AffinityGroups(WindowsAzureData):
131
self.affinity_groups = _list_of(AffinityGroup)
134
return iter(self.affinity_groups)
137
return len(self.affinity_groups)
139
def __getitem__(self, index):
140
return self.affinity_groups[index]
143
class HostedServices(WindowsAzureData):
146
self.hosted_services = _list_of(HostedService)
149
return iter(self.hosted_services)
152
return len(self.hosted_services)
154
def __getitem__(self, index):
155
return self.hosted_services[index]
158
class HostedService(WindowsAzureData):
162
self.service_name = u''
163
self.hosted_service_properties = HostedServiceProperties()
164
self.deployments = Deployments()
167
class HostedServiceProperties(WindowsAzureData):
170
self.description = u''
172
self.affinity_group = u''
173
self.label = _Base64String()
175
self.date_created = u''
176
self.date_last_modified = u''
177
self.extended_properties = _dict_of(
178
'ExtendedProperty', 'Name', 'Value')
181
class VirtualNetworkSites(WindowsAzureData):
184
self.virtual_network_sites = _list_of(VirtualNetworkSite)
187
return iter(self.virtual_network_sites)
190
return len(self.virtual_network_sites)
192
def __getitem__(self, index):
193
return self.virtual_network_sites[index]
196
class VirtualNetworkSite(WindowsAzureData):
201
self.affinity_group = u''
202
self.subnets = Subnets()
205
class Subnets(WindowsAzureData):
208
self.subnets = _list_of(Subnet)
211
return iter(self.subnets)
214
return len(self.subnets)
216
def __getitem__(self, index):
217
return self.subnets[index]
220
class Subnet(WindowsAzureData):
224
self.address_prefix = u''
228
class Deployments(WindowsAzureData):
231
self.deployments = _list_of(Deployment)
234
return iter(self.deployments)
237
return len(self.deployments)
239
def __getitem__(self, index):
240
return self.deployments[index]
243
class Deployment(WindowsAzureData):
247
self.deployment_slot = u''
248
self.private_id = u''
250
self.label = _Base64String()
252
self.configuration = _Base64String()
253
self.role_instance_list = RoleInstanceList()
254
self.upgrade_status = UpgradeStatus()
255
self.upgrade_domain_count = u''
256
self.role_list = RoleList()
257
self.sdk_version = u''
258
self.input_endpoint_list = InputEndpoints()
260
self.rollback_allowed = False
261
self.persistent_vm_downtime_info = PersistentVMDowntimeInfo()
262
self.created_time = u''
263
self.virtual_network_name = u''
264
self.last_modified_time = u''
265
self.extended_properties = _dict_of(
266
'ExtendedProperty', 'Name', 'Value')
269
class RoleInstanceList(WindowsAzureData):
272
self.role_instances = _list_of(RoleInstance)
275
return iter(self.role_instances)
278
return len(self.role_instances)
280
def __getitem__(self, index):
281
return self.role_instances[index]
284
class RoleInstance(WindowsAzureData):
288
self.instance_name = u''
289
self.instance_status = u''
290
self.instance_upgrade_domain = 0
291
self.instance_fault_domain = 0
292
self.instance_size = u''
293
self.instance_state_details = u''
294
self.instance_error_code = u''
295
self.ip_address = u''
296
self.instance_endpoints = InstanceEndpoints()
297
self.power_state = u''
302
class InstanceEndpoints(WindowsAzureData):
305
self.instance_endpoints = _list_of(InstanceEndpoint)
308
return iter(self.instance_endpoints)
311
return len(self.instance_endpoints)
313
def __getitem__(self, index):
314
return self.instance_endpoints[index]
317
class InstanceEndpoint(WindowsAzureData):
322
self.public_port = u''
323
self.local_port = u''
327
class UpgradeStatus(WindowsAzureData):
330
self.upgrade_type = u''
331
self.current_upgrade_domain_state = u''
332
self.current_upgrade_domain = u''
335
class InputEndpoints(WindowsAzureData):
338
self.input_endpoints = _list_of(InputEndpoint)
341
return iter(self.input_endpoints)
344
return len(self.input_endpoints)
346
def __getitem__(self, index):
347
return self.input_endpoints[index]
350
class InputEndpoint(WindowsAzureData):
358
class RoleList(WindowsAzureData):
361
self.roles = _list_of(Role)
364
return iter(self.roles)
367
return len(self.roles)
369
def __getitem__(self, index):
370
return self.roles[index]
373
class Role(WindowsAzureData):
378
self.os_version = u''
379
self.configuration_sets = ConfigurationSets()
380
self.availability_set_name = u''
381
self.data_virtual_hard_disks = DataVirtualHardDisks()
382
self.os_virtual_hard_disk = OSVirtualHardDisk()
384
self.default_win_rm_certificate_thumbprint = u''
387
class PersistentVMDowntimeInfo(WindowsAzureData):
390
self.start_time = u''
395
class Certificates(WindowsAzureData):
398
self.certificates = _list_of(Certificate)
401
return iter(self.certificates)
404
return len(self.certificates)
406
def __getitem__(self, index):
407
return self.certificates[index]
410
class Certificate(WindowsAzureData):
413
self.certificate_url = u''
414
self.thumbprint = u''
415
self.thumbprint_algorithm = u''
419
class OperationError(WindowsAzureData):
426
class Operation(WindowsAzureData):
431
self.http_status_code = u''
432
self.error = OperationError()
435
class OperatingSystem(WindowsAzureData):
439
self.label = _Base64String()
440
self.is_default = True
441
self.is_active = True
443
self.family_label = _Base64String()
446
class OperatingSystems(WindowsAzureData):
449
self.operating_systems = _list_of(OperatingSystem)
452
return iter(self.operating_systems)
455
return len(self.operating_systems)
457
def __getitem__(self, index):
458
return self.operating_systems[index]
461
class OperatingSystemFamily(WindowsAzureData):
465
self.label = _Base64String()
466
self.operating_systems = OperatingSystems()
469
class OperatingSystemFamilies(WindowsAzureData):
472
self.operating_system_families = _list_of(OperatingSystemFamily)
475
return iter(self.operating_system_families)
478
return len(self.operating_system_families)
480
def __getitem__(self, index):
481
return self.operating_system_families[index]
484
class Subscription(WindowsAzureData):
487
self.subscription_id = u''
488
self.subscription_name = u''
489
self.subscription_status = u''
490
self.account_admin_live_email_id = u''
491
self.service_admin_live_email_id = u''
492
self.max_core_count = 0
493
self.max_storage_accounts = 0
494
self.max_hosted_services = 0
495
self.current_core_count = 0
496
self.current_hosted_services = 0
497
self.current_storage_accounts = 0
498
self.max_virtual_network_sites = 0
499
self.max_local_network_sites = 0
500
self.max_dns_servers = 0
503
class AvailabilityResponse(WindowsAzureData):
509
class SubscriptionCertificates(WindowsAzureData):
512
self.subscription_certificates = _list_of(SubscriptionCertificate)
515
return iter(self.subscription_certificates)
518
return len(self.subscription_certificates)
520
def __getitem__(self, index):
521
return self.subscription_certificates[index]
524
class SubscriptionCertificate(WindowsAzureData):
527
self.subscription_certificate_public_key = u''
528
self.subscription_certificate_thumbprint = u''
529
self.subscription_certificate_data = u''
533
class Images(WindowsAzureData):
536
self.images = _list_of(OSImage)
539
return iter(self.images)
542
return len(self.images)
544
def __getitem__(self, index):
545
return self.images[index]
548
class OSImage(WindowsAzureData):
551
self.affinity_group = u''
554
self.logical_size_in_gb = 0
556
self.media_link = u''
560
self.description = u''
563
class Disks(WindowsAzureData):
566
self.disks = _list_of(Disk)
569
return iter(self.disks)
572
return len(self.disks)
574
def __getitem__(self, index):
575
return self.disks[index]
578
class Disk(WindowsAzureData):
581
self.affinity_group = u''
582
self.attached_to = AttachedTo()
583
self.has_operating_system = u''
584
self.is_corrupted = u''
586
self.logical_disk_size_in_gb = 0
588
self.media_link = u''
591
self.source_image_name = u''
594
class AttachedTo(WindowsAzureData):
597
self.hosted_service_name = u''
598
self.deployment_name = u''
602
class PersistentVMRole(WindowsAzureData):
607
self.os_version = u'' # undocumented
608
self.configuration_sets = ConfigurationSets()
609
self.availability_set_name = u''
610
self.data_virtual_hard_disks = DataVirtualHardDisks()
611
self.os_virtual_hard_disk = OSVirtualHardDisk()
613
self.default_win_rm_certificate_thumbprint = u''
616
class ConfigurationSets(WindowsAzureData):
619
self.configuration_sets = _list_of(ConfigurationSet)
622
return iter(self.configuration_sets)
625
return len(self.configuration_sets)
627
def __getitem__(self, index):
628
return self.configuration_sets[index]
631
class ConfigurationSet(WindowsAzureData):
634
self.configuration_set_type = u'NetworkConfiguration'
636
self.input_endpoints = ConfigurationSetInputEndpoints()
637
self.subnet_names = _scalar_list_of(str, 'SubnetName')
640
class ConfigurationSetInputEndpoints(WindowsAzureData):
643
self.input_endpoints = _list_of(
644
ConfigurationSetInputEndpoint, 'InputEndpoint')
647
return iter(self.input_endpoints)
650
return len(self.input_endpoints)
652
def __getitem__(self, index):
653
return self.input_endpoints[index]
656
class ConfigurationSetInputEndpoint(WindowsAzureData):
659
Initializes a network configuration input endpoint.
661
name: Specifies the name for the external endpoint.
663
Specifies the protocol to use to inspect the virtual machine
664
availability status. Possible values are: HTTP, TCP.
665
port: Specifies the external port to use for the endpoint.
667
Specifies the internal port on which the virtual machine is listening
668
to serve the endpoint.
669
load_balanced_endpoint_set_name:
670
Specifies a name for a set of load-balanced endpoints. Specifying this
671
element for a given endpoint adds it to the set. If you are setting an
672
endpoint to use to connect to the virtual machine via the Remote
673
Desktop, do not set this property.
674
enable_direct_server_return:
675
Specifies whether direct server return load balancing is enabled.
678
def __init__(self, name=u'', protocol=u'', port=u'', local_port=u'',
679
load_balanced_endpoint_set_name=u'',
680
enable_direct_server_return=False):
681
self.enable_direct_server_return = enable_direct_server_return
682
self.load_balanced_endpoint_set_name = load_balanced_endpoint_set_name
683
self.local_port = local_port
686
self.load_balancer_probe = LoadBalancerProbe()
687
self.protocol = protocol
690
class WindowsConfigurationSet(WindowsAzureData):
692
def __init__(self, computer_name=None, admin_password=None,
693
reset_password_on_first_logon=None,
694
enable_automatic_updates=None, time_zone=None,
695
admin_username=None):
696
self.configuration_set_type = u'WindowsProvisioningConfiguration'
697
self.computer_name = computer_name
698
self.admin_password = admin_password
699
self.admin_username = admin_username
700
self.reset_password_on_first_logon = reset_password_on_first_logon
701
self.enable_automatic_updates = enable_automatic_updates
702
self.time_zone = time_zone
703
self.domain_join = DomainJoin()
704
self.stored_certificate_settings = StoredCertificateSettings()
705
self.win_rm = WinRM()
708
class DomainJoin(WindowsAzureData):
711
self.credentials = Credentials()
712
self.join_domain = u''
713
self.machine_object_ou = u''
716
class Credentials(WindowsAzureData):
724
class StoredCertificateSettings(WindowsAzureData):
727
self.stored_certificate_settings = _list_of(CertificateSetting)
730
return iter(self.stored_certificate_settings)
733
return len(self.stored_certificate_settings)
735
def __getitem__(self, index):
736
return self.stored_certificate_settings[index]
739
class CertificateSetting(WindowsAzureData):
742
Initializes a certificate setting.
745
Specifies the thumbprint of the certificate to be provisioned. The
746
thumbprint must specify an existing service certificate.
748
Specifies the name of the certificate store from which retrieve
751
Specifies the target certificate store location on the virtual machine.
752
The only supported value is LocalMachine.
755
def __init__(self, thumbprint=u'', store_name=u'', store_location=u''):
756
self.thumbprint = thumbprint
757
self.store_name = store_name
758
self.store_location = store_location
761
class WinRM(WindowsAzureData):
764
Contains configuration settings for the Windows Remote Management service on
769
self.listeners = Listeners()
772
class Listeners(WindowsAzureData):
775
self.listeners = _list_of(Listener)
778
return iter(self.listeners)
781
return len(self.listeners)
783
def __getitem__(self, index):
784
return self.listeners[index]
787
class Listener(WindowsAzureData):
790
Specifies the protocol and certificate information for the listener.
793
Specifies the protocol of listener. Possible values are: Http, Https.
794
The value is case sensitive.
795
certificate_thumbprint:
796
Optional. Specifies the certificate thumbprint for the secure
797
connection. If this value is not specified, a self-signed certificate is
798
generated and used for the Virtual Machine.
801
def __init__(self, protocol=u'', certificate_thumbprint=u''):
802
self.protocol = protocol
803
self.certificate_thumbprint = certificate_thumbprint
806
class LinuxConfigurationSet(WindowsAzureData):
808
def __init__(self, host_name=None, user_name=None, user_password=None,
809
disable_ssh_password_authentication=None):
810
self.configuration_set_type = u'LinuxProvisioningConfiguration'
811
self.host_name = host_name
812
self.user_name = user_name
813
self.user_password = user_password
814
self.disable_ssh_password_authentication =\
815
disable_ssh_password_authentication
819
class SSH(WindowsAzureData):
822
self.public_keys = PublicKeys()
823
self.key_pairs = KeyPairs()
826
class PublicKeys(WindowsAzureData):
829
self.public_keys = _list_of(PublicKey)
832
return iter(self.public_keys)
835
return len(self.public_keys)
837
def __getitem__(self, index):
838
return self.public_keys[index]
841
class PublicKey(WindowsAzureData):
843
def __init__(self, fingerprint=u'', path=u''):
844
self.fingerprint = fingerprint
848
class KeyPairs(WindowsAzureData):
851
self.key_pairs = _list_of(KeyPair)
854
return iter(self.key_pairs)
857
return len(self.key_pairs)
859
def __getitem__(self, index):
860
return self.key_pairs[index]
863
class KeyPair(WindowsAzureData):
865
def __init__(self, fingerprint=u'', path=u''):
866
self.fingerprint = fingerprint
870
class LoadBalancerProbe(WindowsAzureData):
878
class DataVirtualHardDisks(WindowsAzureData):
881
self.data_virtual_hard_disks = _list_of(DataVirtualHardDisk)
884
return iter(self.data_virtual_hard_disks)
887
return len(self.data_virtual_hard_disks)
889
def __getitem__(self, index):
890
return self.data_virtual_hard_disks[index]
893
class DataVirtualHardDisk(WindowsAzureData):
896
self.host_caching = u''
897
self.disk_label = u''
900
self.logical_disk_size_in_gb = 0
901
self.media_link = u''
904
class OSVirtualHardDisk(WindowsAzureData):
906
def __init__(self, source_image_name=None, media_link=None,
907
host_caching=None, disk_label=None, disk_name=None):
908
self.source_image_name = source_image_name
909
self.media_link = media_link
910
self.host_caching = host_caching
911
self.disk_label = disk_label
912
self.disk_name = disk_name
913
self.os = u'' # undocumented, not used when adding a role
916
class AsynchronousOperationResult(WindowsAzureData):
918
def __init__(self, request_id=None):
919
self.request_id = request_id
922
class ServiceBusRegion(WindowsAzureData):
929
class ServiceBusNamespace(WindowsAzureData):
934
self.default_key = u''
936
self.created_at = u''
937
self.acs_management_endpoint = u''
938
self.servicebus_endpoint = u''
939
self.connection_string = u''
940
self.subscription_id = u''
944
def _update_management_header(request):
945
''' Add additional headers for management. '''
947
if request.method in ['PUT', 'POST', 'MERGE', 'DELETE']:
948
request.headers.append(('Content-Length', str(len(request.body))))
950
# append additional headers base on the service
951
request.headers.append(('x-ms-version', X_MS_VERSION))
953
# if it is not GET or HEAD request, must set content-type.
954
if not request.method in ['GET', 'HEAD']:
955
for name, _ in request.headers:
956
if 'content-type' == name.lower():
959
request.headers.append(
961
'application/atom+xml;type=entry;charset=utf-8'))
963
return request.headers
966
def _parse_response_for_async_op(response):
967
''' Extracts request id from response header. '''
972
result = AsynchronousOperationResult()
974
for name, value in response.headers:
975
if name.lower() == 'x-ms-request-id':
976
result.request_id = value
981
def _management_error_handler(http_error):
982
''' Simple error handler for management service. '''
983
return _general_error_handler(http_error)
990
class _XmlSerializer(object):
993
def create_storage_service_input_to_xml(service_name, description, label,
994
affinity_group, location,
995
geo_replication_enabled,
996
extended_properties):
997
return _XmlSerializer.doc_from_data(
998
'CreateStorageServiceInput',
999
[('ServiceName', service_name),
1000
('Description', description),
1001
('Label', label, _encode_base64),
1002
('AffinityGroup', affinity_group),
1003
('Location', location),
1004
('GeoReplicationEnabled', geo_replication_enabled, _lower)],
1005
extended_properties)
1008
def update_storage_service_input_to_xml(description, label,
1009
geo_replication_enabled,
1010
extended_properties):
1011
return _XmlSerializer.doc_from_data(
1012
'UpdateStorageServiceInput',
1013
[('Description', description),
1014
('Label', label, _encode_base64),
1015
('GeoReplicationEnabled', geo_replication_enabled, _lower)],
1016
extended_properties)
1019
def regenerate_keys_to_xml(key_type):
1020
return _XmlSerializer.doc_from_data('RegenerateKeys',
1021
[('KeyType', key_type)])
1024
def update_hosted_service_to_xml(label, description, extended_properties):
1025
return _XmlSerializer.doc_from_data('UpdateHostedService',
1026
[('Label', label, _encode_base64),
1027
('Description', description)],
1028
extended_properties)
1031
def create_hosted_service_to_xml(service_name, label, description,
1032
location, affinity_group,
1033
extended_properties):
1034
return _XmlSerializer.doc_from_data(
1035
'CreateHostedService',
1036
[('ServiceName', service_name),
1037
('Label', label, _encode_base64),
1038
('Description', description),
1039
('Location', location),
1040
('AffinityGroup', affinity_group)],
1041
extended_properties)
1044
def create_deployment_to_xml(name, package_url, label, configuration,
1045
start_deployment, treat_warnings_as_error,
1046
extended_properties):
1047
return _XmlSerializer.doc_from_data(
1050
('PackageUrl', package_url),
1051
('Label', label, _encode_base64),
1052
('Configuration', configuration),
1054
start_deployment, _lower),
1055
('TreatWarningsAsError', treat_warnings_as_error, _lower)],
1056
extended_properties)
1059
def swap_deployment_to_xml(production, source_deployment):
1060
return _XmlSerializer.doc_from_data(
1062
[('Production', production),
1063
('SourceDeployment', source_deployment)])
1066
def update_deployment_status_to_xml(status):
1067
return _XmlSerializer.doc_from_data(
1068
'UpdateDeploymentStatus',
1069
[('Status', status)])
1072
def change_deployment_to_xml(configuration, treat_warnings_as_error, mode,
1073
extended_properties):
1074
return _XmlSerializer.doc_from_data(
1075
'ChangeConfiguration',
1076
[('Configuration', configuration),
1077
('TreatWarningsAsError', treat_warnings_as_error, _lower),
1079
extended_properties)
1082
def upgrade_deployment_to_xml(mode, package_url, configuration, label,
1083
role_to_upgrade, force, extended_properties):
1084
return _XmlSerializer.doc_from_data(
1085
'UpgradeDeployment',
1087
('PackageUrl', package_url),
1088
('Configuration', configuration),
1089
('Label', label, _encode_base64),
1090
('RoleToUpgrade', role_to_upgrade),
1091
('Force', force, _lower)],
1092
extended_properties)
1095
def rollback_upgrade_to_xml(mode, force):
1096
return _XmlSerializer.doc_from_data(
1097
'RollbackUpdateOrUpgrade',
1099
('Force', force, _lower)])
1102
def walk_upgrade_domain_to_xml(upgrade_domain):
1103
return _XmlSerializer.doc_from_data(
1104
'WalkUpgradeDomain',
1105
[('UpgradeDomain', upgrade_domain)])
1108
def certificate_file_to_xml(data, certificate_format, password):
1109
return _XmlSerializer.doc_from_data(
1112
('CertificateFormat', certificate_format),
1113
('Password', password)])
1116
def create_affinity_group_to_xml(name, label, description, location):
1117
return _XmlSerializer.doc_from_data(
1118
'CreateAffinityGroup',
1120
('Label', label, _encode_base64),
1121
('Description', description),
1122
('Location', location)])
1125
def update_affinity_group_to_xml(label, description):
1126
return _XmlSerializer.doc_from_data(
1127
'UpdateAffinityGroup',
1128
[('Label', label, _encode_base64),
1129
('Description', description)])
1132
def subscription_certificate_to_xml(public_key, thumbprint, data):
1133
return _XmlSerializer.doc_from_data(
1134
'SubscriptionCertificate',
1135
[('SubscriptionCertificatePublicKey', public_key),
1136
('SubscriptionCertificateThumbprint', thumbprint),
1137
('SubscriptionCertificateData', data)])
1140
def os_image_to_xml(label, media_link, name, os):
1141
return _XmlSerializer.doc_from_data(
1144
('MediaLink', media_link),
1149
def data_virtual_hard_disk_to_xml(host_caching, disk_label, disk_name, lun,
1150
logical_disk_size_in_gb, media_link,
1152
return _XmlSerializer.doc_from_data(
1153
'DataVirtualHardDisk',
1154
[('HostCaching', host_caching),
1155
('DiskLabel', disk_label),
1156
('DiskName', disk_name),
1158
('LogicalDiskSizeInGB', logical_disk_size_in_gb),
1159
('MediaLink', media_link),
1160
('SourceMediaLink', source_media_link)])
1163
def disk_to_xml(has_operating_system, label, media_link, name, os):
1164
return _XmlSerializer.doc_from_data(
1166
[('HasOperatingSystem', has_operating_system, _lower),
1168
('MediaLink', media_link),
1173
def restart_role_operation_to_xml():
1174
return _XmlSerializer.doc_from_xml(
1175
'RestartRoleOperation',
1176
'<OperationType>RestartRoleOperation</OperationType>')
1179
def shutdown_role_operation_to_xml(post_shutdown_action):
1180
xml = _XmlSerializer.data_to_xml(
1181
[('OperationType', 'ShutdownRoleOperation'),
1182
('PostShutdownAction', post_shutdown_action)])
1183
return _XmlSerializer.doc_from_xml('ShutdownRoleOperation', xml)
1186
def shutdown_roles_operation_to_xml(role_names, post_shutdown_action):
1187
xml = _XmlSerializer.data_to_xml(
1188
[('OperationType', 'ShutdownRolesOperation')])
1190
for role_name in role_names:
1191
xml += _XmlSerializer.data_to_xml([('Name', role_name)])
1193
xml += _XmlSerializer.data_to_xml(
1194
[('PostShutdownAction', post_shutdown_action)])
1195
return _XmlSerializer.doc_from_xml('ShutdownRolesOperation', xml)
1198
def start_role_operation_to_xml():
1199
return _XmlSerializer.doc_from_xml(
1200
'StartRoleOperation',
1201
'<OperationType>StartRoleOperation</OperationType>')
1204
def start_roles_operation_to_xml(role_names):
1205
xml = _XmlSerializer.data_to_xml(
1206
[('OperationType', 'StartRolesOperation')])
1208
for role_name in role_names:
1209
xml += _XmlSerializer.data_to_xml([('Name', role_name)])
1211
return _XmlSerializer.doc_from_xml('StartRolesOperation', xml)
1214
def windows_configuration_to_xml(configuration):
1215
xml = _XmlSerializer.data_to_xml(
1216
[('ConfigurationSetType', configuration.configuration_set_type),
1217
('ComputerName', configuration.computer_name),
1218
('AdminPassword', configuration.admin_password),
1219
('ResetPasswordOnFirstLogon',
1220
configuration.reset_password_on_first_logon,
1222
('EnableAutomaticUpdates',
1223
configuration.enable_automatic_updates,
1225
('TimeZone', configuration.time_zone)])
1227
if configuration.domain_join is not None:
1228
xml += '<DomainJoin>'
1229
xml += '<Credentials>'
1230
xml += _XmlSerializer.data_to_xml(
1231
[('Domain', configuration.domain_join.credentials.domain),
1232
('Username', configuration.domain_join.credentials.username),
1233
('Password', configuration.domain_join.credentials.password)])
1234
xml += '</Credentials>'
1235
xml += _XmlSerializer.data_to_xml(
1236
[('JoinDomain', configuration.domain_join.join_domain),
1238
configuration.domain_join.machine_object_ou)])
1239
xml += '</DomainJoin>'
1240
if configuration.stored_certificate_settings is not None:
1241
xml += '<StoredCertificateSettings>'
1242
for cert in configuration.stored_certificate_settings:
1243
xml += '<CertificateSetting>'
1244
xml += _XmlSerializer.data_to_xml(
1245
[('StoreLocation', cert.store_location),
1246
('StoreName', cert.store_name),
1247
('Thumbprint', cert.thumbprint)])
1248
xml += '</CertificateSetting>'
1249
xml += '</StoredCertificateSettings>'
1250
if configuration.win_rm is not None:
1251
xml += '<WinRM><Listeners>'
1252
for listener in configuration.win_rm.listeners:
1254
xml += _XmlSerializer.data_to_xml(
1255
[('Protocol', listener.protocol),
1256
('CertificateThumbprint', listener.certificate_thumbprint)])
1257
xml += '</Listener>'
1258
xml += '</Listeners></WinRM>'
1259
xml += _XmlSerializer.data_to_xml(
1260
[('AdminUsername', configuration.admin_username)])
1264
def linux_configuration_to_xml(configuration):
1265
xml = _XmlSerializer.data_to_xml(
1266
[('ConfigurationSetType', configuration.configuration_set_type),
1267
('HostName', configuration.host_name),
1268
('UserName', configuration.user_name),
1269
('UserPassword', configuration.user_password),
1270
('DisableSshPasswordAuthentication',
1271
configuration.disable_ssh_password_authentication,
1274
if configuration.ssh is not None:
1276
xml += '<PublicKeys>'
1277
for key in configuration.ssh.public_keys:
1278
xml += '<PublicKey>'
1279
xml += _XmlSerializer.data_to_xml(
1280
[('Fingerprint', key.fingerprint),
1281
('Path', key.path)])
1282
xml += '</PublicKey>'
1283
xml += '</PublicKeys>'
1285
for key in configuration.ssh.key_pairs:
1287
xml += _XmlSerializer.data_to_xml(
1288
[('Fingerprint', key.fingerprint),
1289
('Path', key.path)])
1291
xml += '</KeyPairs>'
1296
def network_configuration_to_xml(configuration):
1297
xml = _XmlSerializer.data_to_xml(
1298
[('ConfigurationSetType', configuration.configuration_set_type)])
1299
xml += '<InputEndpoints>'
1300
for endpoint in configuration.input_endpoints:
1301
xml += '<InputEndpoint>'
1302
xml += _XmlSerializer.data_to_xml(
1303
[('LoadBalancedEndpointSetName',
1304
endpoint.load_balanced_endpoint_set_name),
1305
('LocalPort', endpoint.local_port),
1306
('Name', endpoint.name),
1307
('Port', endpoint.port)])
1309
if endpoint.load_balancer_probe.path or\
1310
endpoint.load_balancer_probe.port or\
1311
endpoint.load_balancer_probe.protocol:
1312
xml += '<LoadBalancerProbe>'
1313
xml += _XmlSerializer.data_to_xml(
1314
[('Path', endpoint.load_balancer_probe.path),
1315
('Port', endpoint.load_balancer_probe.port),
1316
('Protocol', endpoint.load_balancer_probe.protocol)])
1317
xml += '</LoadBalancerProbe>'
1319
xml += _XmlSerializer.data_to_xml(
1320
[('Protocol', endpoint.protocol),
1321
('EnableDirectServerReturn',
1322
endpoint.enable_direct_server_return,
1325
xml += '</InputEndpoint>'
1326
xml += '</InputEndpoints>'
1327
xml += '<SubnetNames>'
1328
for name in configuration.subnet_names:
1329
xml += _XmlSerializer.data_to_xml([('SubnetName', name)])
1330
xml += '</SubnetNames>'
1334
def role_to_xml(availability_set_name, data_virtual_hard_disks,
1335
network_configuration_set, os_virtual_hard_disk, role_name,
1336
role_size, role_type, system_configuration_set):
1337
xml = _XmlSerializer.data_to_xml([('RoleName', role_name),
1338
('RoleType', role_type)])
1340
xml += '<ConfigurationSets>'
1342
if system_configuration_set is not None:
1343
xml += '<ConfigurationSet>'
1344
if isinstance(system_configuration_set, WindowsConfigurationSet):
1345
xml += _XmlSerializer.windows_configuration_to_xml(
1346
system_configuration_set)
1347
elif isinstance(system_configuration_set, LinuxConfigurationSet):
1348
xml += _XmlSerializer.linux_configuration_to_xml(
1349
system_configuration_set)
1350
xml += '</ConfigurationSet>'
1352
if network_configuration_set is not None:
1353
xml += '<ConfigurationSet>'
1354
xml += _XmlSerializer.network_configuration_to_xml(
1355
network_configuration_set)
1356
xml += '</ConfigurationSet>'
1358
xml += '</ConfigurationSets>'
1360
if availability_set_name is not None:
1361
xml += _XmlSerializer.data_to_xml(
1362
[('AvailabilitySetName', availability_set_name)])
1364
if data_virtual_hard_disks is not None:
1365
xml += '<DataVirtualHardDisks>'
1366
for hd in data_virtual_hard_disks:
1367
xml += '<DataVirtualHardDisk>'
1368
xml += _XmlSerializer.data_to_xml(
1369
[('HostCaching', hd.host_caching),
1370
('DiskLabel', hd.disk_label),
1371
('DiskName', hd.disk_name),
1373
('LogicalDiskSizeInGB', hd.logical_disk_size_in_gb),
1374
('MediaLink', hd.media_link)])
1375
xml += '</DataVirtualHardDisk>'
1376
xml += '</DataVirtualHardDisks>'
1378
if os_virtual_hard_disk is not None:
1379
xml += '<OSVirtualHardDisk>'
1380
xml += _XmlSerializer.data_to_xml(
1381
[('HostCaching', os_virtual_hard_disk.host_caching),
1382
('DiskLabel', os_virtual_hard_disk.disk_label),
1383
('DiskName', os_virtual_hard_disk.disk_name),
1384
('MediaLink', os_virtual_hard_disk.media_link),
1385
('SourceImageName', os_virtual_hard_disk.source_image_name)])
1386
xml += '</OSVirtualHardDisk>'
1388
if role_size is not None:
1389
xml += _XmlSerializer.data_to_xml([('RoleSize', role_size)])
1394
def add_role_to_xml(role_name, system_configuration_set,
1395
os_virtual_hard_disk, role_type,
1396
network_configuration_set, availability_set_name,
1397
data_virtual_hard_disks, role_size):
1398
xml = _XmlSerializer.role_to_xml(
1399
availability_set_name,
1400
data_virtual_hard_disks,
1401
network_configuration_set,
1402
os_virtual_hard_disk,
1406
system_configuration_set)
1407
return _XmlSerializer.doc_from_xml('PersistentVMRole', xml)
1410
def update_role_to_xml(role_name, os_virtual_hard_disk, role_type,
1411
network_configuration_set, availability_set_name,
1412
data_virtual_hard_disks, role_size):
1413
xml = _XmlSerializer.role_to_xml(
1414
availability_set_name,
1415
data_virtual_hard_disks,
1416
network_configuration_set,
1417
os_virtual_hard_disk,
1422
return _XmlSerializer.doc_from_xml('PersistentVMRole', xml)
1425
def capture_role_to_xml(post_capture_action, target_image_name,
1426
target_image_label, provisioning_configuration):
1427
xml = _XmlSerializer.data_to_xml(
1428
[('OperationType', 'CaptureRoleOperation'),
1429
('PostCaptureAction', post_capture_action)])
1431
if provisioning_configuration is not None:
1432
xml += '<ProvisioningConfiguration>'
1433
if isinstance(provisioning_configuration, WindowsConfigurationSet):
1434
xml += _XmlSerializer.windows_configuration_to_xml(
1435
provisioning_configuration)
1436
elif isinstance(provisioning_configuration, LinuxConfigurationSet):
1437
xml += _XmlSerializer.linux_configuration_to_xml(
1438
provisioning_configuration)
1439
xml += '</ProvisioningConfiguration>'
1441
xml += _XmlSerializer.data_to_xml(
1442
[('TargetImageLabel', target_image_label),
1443
('TargetImageName', target_image_name)])
1445
return _XmlSerializer.doc_from_xml('CaptureRoleOperation', xml)
1448
def virtual_machine_deployment_to_xml(deployment_name, deployment_slot,
1450
system_configuration_set,
1451
os_virtual_hard_disk, role_type,
1452
network_configuration_set,
1453
availability_set_name,
1454
data_virtual_hard_disks, role_size,
1455
virtual_network_name):
1456
xml = _XmlSerializer.data_to_xml([('Name', deployment_name),
1457
('DeploymentSlot', deployment_slot),
1461
xml += _XmlSerializer.role_to_xml(
1462
availability_set_name,
1463
data_virtual_hard_disks,
1464
network_configuration_set,
1465
os_virtual_hard_disk,
1469
system_configuration_set)
1471
xml += '</RoleList>'
1473
if virtual_network_name is not None:
1474
xml += _XmlSerializer.data_to_xml(
1475
[('VirtualNetworkName', virtual_network_name)])
1477
return _XmlSerializer.doc_from_xml('Deployment', xml)
1480
def data_to_xml(data):
1481
'''Creates an xml fragment from the specified data.
1482
data: Array of tuples, where first: xml element name
1483
second: xml element text
1484
third: conversion function
1487
for element in data:
1490
if len(element) > 2:
1491
converter = element[2]
1496
if converter is not None:
1497
text = _str(converter(_str(val)))
1501
xml += ''.join(['<', name, '>', text, '</', name, '>'])
1505
def doc_from_xml(document_element_name, inner_xml):
1506
'''Wraps the specified xml in an xml root element with default azure
1508
xml = ''.join(['<', document_element_name,
1509
' xmlns:i="http://www.w3.org/2001/XMLSchema-instance"',
1510
' xmlns="http://schemas.microsoft.com/windowsazure">'])
1512
xml += ''.join(['</', document_element_name, '>'])
1516
def doc_from_data(document_element_name, data, extended_properties=None):
1517
xml = _XmlSerializer.data_to_xml(data)
1518
if extended_properties is not None:
1519
xml += _XmlSerializer.extended_properties_dict_to_xml_fragment(
1520
extended_properties)
1521
return _XmlSerializer.doc_from_xml(document_element_name, xml)
1524
def extended_properties_dict_to_xml_fragment(extended_properties):
1526
if extended_properties is not None and len(extended_properties) > 0:
1527
xml += '<ExtendedProperties>'
1528
for key, val in extended_properties.items():
1529
xml += ''.join(['<ExtendedProperty>',
1536
'</ExtendedProperty>'])
1537
xml += '</ExtendedProperties>'
1541
def _parse_bool(value):
1542
if value.lower() == 'true':
1547
class _ServiceBusManagementXmlSerializer(object):
1550
def namespace_to_xml(region):
1551
'''Converts a service bus namespace description to xml
1554
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
1555
<entry xmlns="http://www.w3.org/2005/Atom">
1556
<content type="application/xml">
1557
<NamespaceDescription
1558
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
1559
<Region>West US</Region>
1560
</NamespaceDescription>
1564
body = '<NamespaceDescription xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">'
1565
body += ''.join(['<Region>', region, '</Region>'])
1566
body += '</NamespaceDescription>'
1568
return _create_entry(body)
1571
def xml_to_namespace(xmlstr):
1572
'''Converts xml response to service bus namespace
1574
The xml format for namespace:
1576
<id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id>
1577
<title type="text">myunittests</title>
1578
<updated>2012-08-22T16:48:10Z</updated>
1579
<content type="application/xml">
1580
<NamespaceDescription
1581
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"
1582
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
1583
<Name>myunittests</Name>
1584
<Region>West US</Region>
1585
<DefaultKey>0000000000000000000000000000000000000000000=</DefaultKey>
1586
<Status>Active</Status>
1587
<CreatedAt>2012-08-22T16:48:10.217Z</CreatedAt>
1588
<AcsManagementEndpoint>https://myunittests-sb.accesscontrol.windows.net/</AcsManagementEndpoint>
1589
<ServiceBusEndpoint>https://myunittests.servicebus.windows.net/</ServiceBusEndpoint>
1590
<ConnectionString>Endpoint=sb://myunittests.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=0000000000000000000000000000000000000000000=</ConnectionString>
1591
<SubscriptionId>00000000000000000000000000000000</SubscriptionId>
1592
<Enabled>true</Enabled>
1593
</NamespaceDescription>
1597
xmldoc = minidom.parseString(xmlstr)
1598
namespace = ServiceBusNamespace()
1601
('Name', 'name', None),
1602
('Region', 'region', None),
1603
('DefaultKey', 'default_key', None),
1604
('Status', 'status', None),
1605
('CreatedAt', 'created_at', None),
1606
('AcsManagementEndpoint', 'acs_management_endpoint', None),
1607
('ServiceBusEndpoint', 'servicebus_endpoint', None),
1608
('ConnectionString', 'connection_string', None),
1609
('SubscriptionId', 'subscription_id', None),
1610
('Enabled', 'enabled', _parse_bool),
1613
for desc in _get_children_from_path(xmldoc,
1616
'NamespaceDescription'):
1617
for xml_name, field_name, conversion_func in mappings:
1618
node_value = _get_first_child_node_value(desc, xml_name)
1619
if node_value is not None:
1620
if conversion_func is not None:
1621
node_value = conversion_func(node_value)
1622
setattr(namespace, field_name, node_value)
1627
def xml_to_region(xmlstr):
1628
'''Converts xml response to service bus region
1630
The xml format for region:
1632
<id>uuid:157c311f-081f-4b4a-a0ba-a8f990ffd2a3;id=1756759</id>
1633
<title type="text"></title>
1634
<updated>2013-04-10T18:25:29Z</updated>
1635
<content type="application/xml">
1636
<RegionCodeDescription
1637
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"
1638
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
1639
<Code>East Asia</Code>
1640
<FullName>East Asia</FullName>
1641
</RegionCodeDescription>
1645
xmldoc = minidom.parseString(xmlstr)
1646
region = ServiceBusRegion()
1648
for desc in _get_children_from_path(xmldoc, 'entry', 'content',
1649
'RegionCodeDescription'):
1650
node_value = _get_first_child_node_value(desc, 'Code')
1651
if node_value is not None:
1652
region.code = node_value
1653
node_value = _get_first_child_node_value(desc, 'FullName')
1654
if node_value is not None:
1655
region.fullname = node_value
1660
def xml_to_namespace_availability(xmlstr):
1661
'''Converts xml response to service bus namespace availability
1664
<?xml version="1.0" encoding="utf-8"?>
1665
<entry xmlns="http://www.w3.org/2005/Atom">
1666
<id>uuid:9fc7c652-1856-47ab-8d74-cd31502ea8e6;id=3683292</id>
1667
<title type="text"></title>
1668
<updated>2013-04-16T03:03:37Z</updated>
1669
<content type="application/xml">
1670
<NamespaceAvailability
1671
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"
1672
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
1673
<Result>false</Result>
1674
</NamespaceAvailability>
1678
xmldoc = minidom.parseString(xmlstr)
1679
availability = AvailabilityResponse()
1681
for desc in _get_children_from_path(xmldoc, 'entry', 'content',
1682
'NamespaceAvailability'):
1683
node_value = _get_first_child_node_value(desc, 'Result')
1684
if node_value is not None:
1685
availability.result = _parse_bool(node_value)
1689
from azure.servicemanagement.servicemanagementservice import (
1690
ServiceManagementService)
1691
from azure.servicemanagement.servicebusmanagementservice import (
1692
ServiceBusManagementService)