-
Notifications
You must be signed in to change notification settings - Fork 928
Expand file tree
/
Copy pathazure.py
More file actions
3227 lines (2661 loc) · 103 KB
/
Copy pathazure.py
File metadata and controls
3227 lines (2661 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Driver for Microsoft Azure Virtual Machines service.
http://azure.microsoft.com/en-us/services/virtual-machines/
"""
import re
import copy
import time
import base64
import random
import collections
from xml.dom import minidom
from datetime import datetime
from xml.sax.saxutils import escape as xml_escape
from libcloud.utils.py3 import ET, httplib, urlparse
from libcloud.utils.py3 import urlquote as url_quote
from libcloud.utils.py3 import _real_unicode, ensure_string
from libcloud.utils.misc import ReprMixin
from libcloud.common.azure import AzureRedirectException, AzureServiceManagementConnection
from libcloud.common.types import LibcloudError
from libcloud.compute.base import (
Node,
NodeSize,
NodeImage,
NodeDriver,
NodeLocation,
StorageVolume,
)
from libcloud.compute.types import NodeState
from libcloud.compute.providers import Provider
HTTPSConnection = httplib.HTTPSConnection
_str = str
_unicode_type = str
AZURE_SERVICE_MANAGEMENT_HOST = "management.core.windows.net"
X_MS_VERSION = "2013-08-01"
WINDOWS_SERVER_REGEX = re.compile(r"Win|SQL|SharePoint|Visual|Dynamics|DynGP|BizTalk")
"""
Sizes must be hardcoded because Microsoft doesn't provide an API to fetch them
From http://msdn.microsoft.com/en-us/library/windowsazure/dn197896.aspx
Prices are for Linux instances in East US data center. To see what pricing will
actually be, visit:
http://azure.microsoft.com/en-gb/pricing/details/virtual-machines/
"""
AZURE_COMPUTE_INSTANCE_TYPES = {
"A0": {
"id": "ExtraSmall",
"name": "Extra Small Instance",
"ram": 768,
"disk": 127,
"bandwidth": None,
"price": "0.0211",
"max_data_disks": 1,
"cores": "Shared",
},
"A1": {
"id": "Small",
"name": "Small Instance",
"ram": 1792,
"disk": 127,
"bandwidth": None,
"price": "0.0633",
"max_data_disks": 2,
"cores": 1,
},
"A2": {
"id": "Medium",
"name": "Medium Instance",
"ram": 3584,
"disk": 127,
"bandwidth": None,
"price": "0.1266",
"max_data_disks": 4,
"cores": 2,
},
"A3": {
"id": "Large",
"name": "Large Instance",
"ram": 7168,
"disk": 127,
"bandwidth": None,
"price": "0.2531",
"max_data_disks": 8,
"cores": 4,
},
"A4": {
"id": "ExtraLarge",
"name": "Extra Large Instance",
"ram": 14336,
"disk": 127,
"bandwidth": None,
"price": "0.5062",
"max_data_disks": 16,
"cores": 8,
},
"A5": {
"id": "A5",
"name": "Memory Intensive Instance",
"ram": 14336,
"disk": 127,
"bandwidth": None,
"price": "0.2637",
"max_data_disks": 4,
"cores": 2,
},
"A6": {
"id": "A6",
"name": "A6 Instance",
"ram": 28672,
"disk": 127,
"bandwidth": None,
"price": "0.5273",
"max_data_disks": 8,
"cores": 4,
},
"A7": {
"id": "A7",
"name": "A7 Instance",
"ram": 57344,
"disk": 127,
"bandwidth": None,
"price": "1.0545",
"max_data_disks": 16,
"cores": 8,
},
"A8": {
"id": "A8",
"name": "A8 Instance",
"ram": 57344,
"disk": 127,
"bandwidth": None,
"price": "2.0774",
"max_data_disks": 16,
"cores": 8,
},
"A9": {
"id": "A9",
"name": "A9 Instance",
"ram": 114688,
"disk": 127,
"bandwidth": None,
"price": "4.7137",
"max_data_disks": 16,
"cores": 16,
},
"A10": {
"id": "A10",
"name": "A10 Instance",
"ram": 57344,
"disk": 127,
"bandwidth": None,
"price": "1.2233",
"max_data_disks": 16,
"cores": 8,
},
"A11": {
"id": "A11",
"name": "A11 Instance",
"ram": 114688,
"disk": 127,
"bandwidth": None,
"price": "2.1934",
"max_data_disks": 16,
"cores": 16,
},
"D1": {
"id": "Standard_D1",
"name": "D1 Faster Compute Instance",
"ram": 3584,
"disk": 127,
"bandwidth": None,
"price": "0.0992",
"max_data_disks": 2,
"cores": 1,
},
"D2": {
"id": "Standard_D2",
"name": "D2 Faster Compute Instance",
"ram": 7168,
"disk": 127,
"bandwidth": None,
"price": "0.1983",
"max_data_disks": 4,
"cores": 2,
},
"D3": {
"id": "Standard_D3",
"name": "D3 Faster Compute Instance",
"ram": 14336,
"disk": 127,
"bandwidth": None,
"price": "0.3965",
"max_data_disks": 8,
"cores": 4,
},
"D4": {
"id": "Standard_D4",
"name": "D4 Faster Compute Instance",
"ram": 28672,
"disk": 127,
"bandwidth": None,
"price": "0.793",
"max_data_disks": 16,
"cores": 8,
},
"D11": {
"id": "Standard_D11",
"name": "D11 Faster Compute Instance",
"ram": 14336,
"disk": 127,
"bandwidth": None,
"price": "0.251",
"max_data_disks": 4,
"cores": 2,
},
"D12": {
"id": "Standard_D12",
"name": "D12 Faster Compute Instance",
"ram": 28672,
"disk": 127,
"bandwidth": None,
"price": "0.502",
"max_data_disks": 8,
"cores": 4,
},
"D13": {
"id": "Standard_D13",
"name": "D13 Faster Compute Instance",
"ram": 57344,
"disk": 127,
"bandwidth": None,
"price": "0.9038",
"max_data_disks": 16,
"cores": 8,
},
"D14": {
"id": "Standard_D14",
"name": "D14 Faster Compute Instance",
"ram": 114688,
"disk": 127,
"bandwidth": None,
"price": "1.6261",
"max_data_disks": 32,
"cores": 16,
},
}
_KNOWN_SERIALIZATION_XFORMS = {
"include_apis": "IncludeAPIs",
"message_id": "MessageId",
"content_md5": "Content-MD5",
"last_modified": "Last-Modified",
"cache_control": "Cache-Control",
"account_admin_live_email_id": "AccountAdminLiveEmailId",
"service_admin_live_email_id": "ServiceAdminLiveEmailId",
"subscription_id": "SubscriptionID",
"fqdn": "FQDN",
"private_id": "PrivateID",
"os_virtual_hard_disk": "OSVirtualHardDisk",
"logical_disk_size_in_gb": "LogicalDiskSizeInGB",
"logical_size_in_gb": "LogicalSizeInGB",
"os": "OS",
"persistent_vm_downtime_info": "PersistentVMDowntimeInfo",
"copy_id": "CopyId",
"os_disk_configuration": "OSDiskConfiguration",
"is_dns_programmed": "IsDnsProgrammed",
}
class AzureNodeDriver(NodeDriver):
connectionCls = AzureServiceManagementConnection
name = "Azure Virtual machines"
website = "http://azure.microsoft.com/en-us/services/virtual-machines/"
type = Provider.AZURE
_instance_types = AZURE_COMPUTE_INSTANCE_TYPES
_blob_url = ".blob.core.windows.net"
features = {"create_node": ["password"]}
service_location = collections.namedtuple(
"service_location", ["is_affinity_group", "service_location"]
)
NODE_STATE_MAP = {
"RoleStateUnknown": NodeState.UNKNOWN,
"CreatingVM": NodeState.PENDING,
"StartingVM": NodeState.PENDING,
"Provisioning": NodeState.PENDING,
"CreatingRole": NodeState.PENDING,
"StartingRole": NodeState.PENDING,
"ReadyRole": NodeState.RUNNING,
"BusyRole": NodeState.PENDING,
"StoppingRole": NodeState.PENDING,
"StoppingVM": NodeState.PENDING,
"DeletingVM": NodeState.PENDING,
"StoppedVM": NodeState.STOPPED,
"RestartingRole": NodeState.REBOOTING,
"CyclingRole": NodeState.TERMINATED,
"FailedStartingRole": NodeState.TERMINATED,
"FailedStartingVM": NodeState.TERMINATED,
"UnresponsiveRole": NodeState.TERMINATED,
"StoppedDeallocated": NodeState.TERMINATED,
}
def __init__(self, subscription_id=None, key_file=None, **kwargs):
"""
subscription_id contains the Azure subscription id in the form of GUID
key_file contains the Azure X509 certificate in .pem form
"""
self.subscription_id = subscription_id
self.key_file = key_file
self.follow_redirects = kwargs.get("follow_redirects", True)
super().__init__(self.subscription_id, self.key_file, secure=True, **kwargs)
def list_sizes(
self,
location=None,
):
"""
Lists all sizes
:rtype: ``list`` of :class:`NodeSize`
"""
sizes = []
for _, values in self._instance_types.items():
node_size = self._to_node_size(copy.deepcopy(values))
sizes.append(node_size)
return sizes
def list_images(self, location=None):
"""
Lists all images
:rtype: ``list`` of :class:`NodeImage`
"""
data = self._perform_get(self._get_image_path(), Images)
custom_image_data = self._perform_get(self._get_vmimage_path(), VMImages)
images = [self._to_image(i) for i in data]
images.extend(self._vm_to_image(j) for j in custom_image_data)
if location is not None:
images = [image for image in images if location in image.extra["location"]]
return images
def list_locations(self):
"""
Lists all locations
:rtype: ``list`` of :class:`NodeLocation`
"""
data = self._perform_get("/" + self.subscription_id + "/locations", Locations)
return [self._to_location(location) for location in data]
def list_nodes(self, ex_cloud_service_name):
"""
List all nodes
ex_cloud_service_name parameter is used to scope the request
to a specific Cloud Service. This is a required parameter as
nodes cannot exist outside of a Cloud Service nor be shared
between a Cloud Service within Azure.
:param ex_cloud_service_name: Cloud Service name
:type ex_cloud_service_name: ``str``
:rtype: ``list`` of :class:`Node`
"""
response = self._perform_get(
self._get_hosted_service_path(ex_cloud_service_name) + "?embed-detail=True",
None,
)
self.raise_for_response(response, 200)
data = self._parse_response(response, HostedService)
vips = None
if len(data.deployments) > 0 and data.deployments[0].virtual_ips is not None:
vips = [vip.address for vip in data.deployments[0].virtual_ips]
try:
return [
self._to_node(n, ex_cloud_service_name, vips)
for n in data.deployments[0].role_instance_list
]
except IndexError:
return []
def reboot_node(self, node, ex_cloud_service_name=None, ex_deployment_slot=None):
"""
Reboots a node.
ex_cloud_service_name parameter is used to scope the request
to a specific Cloud Service. This is a required parameter as
nodes cannot exist outside of a Cloud Service nor be shared
between a Cloud Service within Azure.
:param ex_cloud_service_name: Cloud Service name
:type ex_cloud_service_name: ``str``
:param ex_deployment_slot: Options are "production" (default)
or "Staging". (Optional)
:type ex_deployment_slot: ``str``
:rtype: ``bool``
"""
if ex_cloud_service_name is None:
if node.extra is not None:
ex_cloud_service_name = node.extra.get("ex_cloud_service_name")
if not ex_cloud_service_name:
raise ValueError("ex_cloud_service_name is required.")
if not ex_deployment_slot:
ex_deployment_slot = "Production"
_deployment_name = self._get_deployment(
service_name=ex_cloud_service_name, deployment_slot=ex_deployment_slot
).name
try:
response = self._perform_post(
self._get_deployment_path_using_name(ex_cloud_service_name, _deployment_name)
+ "/roleinstances/"
+ _str(node.id)
+ "?comp=reboot",
"",
)
self.raise_for_response(response, 202)
if self._parse_response_for_async_op(response):
return True
else:
return False
except Exception:
return False
def list_volumes(self, node=None):
"""
Lists volumes of the disks in the image repository that are
associated with the specified subscription.
Pass Node object to scope the list of volumes to a single
instance.
:rtype: ``list`` of :class:`StorageVolume`
"""
data = self._perform_get(self._get_disk_path(), Disks)
volumes = [self._to_volume(volume=v, node=node) for v in data]
return volumes
def create_node(
self,
name,
size,
image,
location=None,
auth=None,
ex_cloud_service_name=None,
ex_storage_service_name=None,
ex_new_deployment=False,
ex_deployment_slot="Production",
ex_deployment_name=None,
ex_admin_user_id="azureuser",
ex_custom_data=None,
ex_virtual_network_name=None,
ex_network_config=None,
**kwargs,
):
"""
Create Azure Virtual Machine
Reference: http://bit.ly/1fIsCb7
[www.windowsazure.com/en-us/documentation/]
We default to:
+ 3389/TCP - RDP - 1st Microsoft instance.
+ RANDOM/TCP - RDP - All succeeding Microsoft instances.
+ 22/TCP - SSH - 1st Linux instance
+ RANDOM/TCP - SSH - All succeeding Linux instances.
The above replicates the standard behavior of the Azure UI.
You can retrieve the assigned ports to each instance by
using the following private function:
_get_endpoint_ports(service_name)
Returns public,private port key pair.
@inherits: :class:`NodeDriver.create_node`
:keyword image: The image to use when creating this node
:type image: `NodeImage`
:keyword size: The size of the instance to create
:type size: `NodeSize`
:keyword ex_cloud_service_name: Required.
Name of the Azure Cloud Service.
:type ex_cloud_service_name: ``str``
:keyword ex_storage_service_name: Optional:
Name of the Azure Storage Service.
:type ex_storage_service_name: ``str``
:keyword ex_new_deployment: Optional. Tells azure to create a
new deployment rather than add to an
existing one.
:type ex_new_deployment: ``boolean``
:keyword ex_deployment_slot: Optional: Valid values: production|
staging.
Defaults to production.
:type ex_deployment_slot: ``str``
:keyword ex_deployment_name: Optional. The name of the
deployment.
If this is not passed in we default
to using the Cloud Service name.
:type ex_deployment_name: ``str``
:type ex_custom_data: ``str``
:keyword ex_custom_data: Optional script or other data which is
injected into the VM when it's beginning
provisioned.
:keyword ex_admin_user_id: Optional. Defaults to 'azureuser'.
:type ex_admin_user_id: ``str``
:keyword ex_virtual_network_name: Optional. If this is not passed
in no virtual network is used.
:type ex_virtual_network_name: ``str``
:keyword ex_network_config: Optional. The ConfigurationSet to use
for network configuration
:type ex_network_config: `ConfigurationSet`
"""
# TODO: Refactor this method to make it more readable, split it into
# multiple smaller methods
auth = self._get_and_check_auth(auth)
password = auth.password
if not isinstance(size, NodeSize):
raise ValueError("Size must be an instance of NodeSize")
if not isinstance(image, NodeImage):
raise ValueError("Image must be an instance of NodeImage, " "produced by list_images()")
# Retrieve a list of currently available nodes for the provided cloud
# service
node_list = self.list_nodes(ex_cloud_service_name=ex_cloud_service_name)
if ex_network_config is None:
network_config = ConfigurationSet()
else:
network_config = ex_network_config
network_config.configuration_set_type = "NetworkConfiguration"
# Base64 encode custom data if provided
if ex_custom_data:
ex_custom_data = self._encode_base64(data=ex_custom_data)
# We do this because we need to pass a Configuration to the
# method. This will be either Linux or Windows.
if WINDOWS_SERVER_REGEX.search(image.id, re.I):
machine_config = WindowsConfigurationSet(
computer_name=name,
admin_password=password,
admin_user_name=ex_admin_user_id,
)
machine_config.domain_join = None
if not node_list or ex_new_deployment:
port = "3389"
else:
port = random.randint(41952, 65535)
endpoints = self._get_deployment(
service_name=ex_cloud_service_name,
deployment_slot=ex_deployment_slot,
)
for instances in endpoints.role_instance_list:
ports = [ep.public_port for ep in instances.instance_endpoints]
while port in ports:
port = random.randint(41952, 65535)
endpoint = ConfigurationSetInputEndpoint(
name="Remote Desktop",
protocol="tcp",
port=port,
local_port="3389",
load_balanced_endpoint_set_name=None,
enable_direct_server_return=False,
)
else:
if not node_list or ex_new_deployment:
port = "22"
else:
port = random.randint(41952, 65535)
endpoints = self._get_deployment(
service_name=ex_cloud_service_name,
deployment_slot=ex_deployment_slot,
)
for instances in endpoints.role_instance_list:
ports = []
if instances.instance_endpoints is not None:
for ep in instances.instance_endpoints:
ports += [ep.public_port]
while port in ports:
port = random.randint(41952, 65535)
endpoint = ConfigurationSetInputEndpoint(
name="SSH",
protocol="tcp",
port=port,
local_port="22",
load_balanced_endpoint_set_name=None,
enable_direct_server_return=False,
)
machine_config = LinuxConfigurationSet(
name, ex_admin_user_id, password, False, ex_custom_data
)
network_config.input_endpoints.items.append(endpoint)
_storage_location = self._get_cloud_service_location(service_name=ex_cloud_service_name)
if ex_storage_service_name is None:
ex_storage_service_name = ex_cloud_service_name
ex_storage_service_name = re.sub(
r"[\W_-]+", "", ex_storage_service_name.lower(), flags=re.UNICODE
)
if self._is_storage_service_unique(service_name=ex_storage_service_name):
self._create_storage_account(
service_name=ex_storage_service_name,
location=_storage_location.service_location,
is_affinity_group=_storage_location.is_affinity_group,
)
# OK, bit annoying here. You must create a deployment before
# you can create an instance; however, the deployment function
# creates the first instance, but all subsequent instances
# must be created using the add_role function.
#
# So, yeah, annoying.
if not node_list or ex_new_deployment:
# This is the first node in this cloud service.
if not ex_deployment_name:
ex_deployment_name = ex_cloud_service_name
vm_image_id = None
disk_config = None
if image.extra.get("vm_image", False):
vm_image_id = image.id
# network_config = None
else:
blob_url = "http://%s.blob.core.windows.net" % (ex_storage_service_name)
# Azure's pattern in the UI.
disk_name = "{}-{}-{}.vhd".format(
ex_cloud_service_name,
name,
time.strftime("%Y-%m-%d"),
)
media_link = "{}/vhds/{}".format(blob_url, disk_name)
disk_config = OSVirtualHardDisk(image.id, media_link)
response = self._perform_post(
self._get_deployment_path_using_name(ex_cloud_service_name),
AzureXmlSerializer.virtual_machine_deployment_to_xml(
ex_deployment_name,
ex_deployment_slot,
name,
name,
machine_config,
disk_config,
"PersistentVMRole",
network_config,
None,
None,
size.id,
ex_virtual_network_name,
vm_image_id,
),
)
self.raise_for_response(response, 202)
self._ex_complete_async_azure_operation(response)
else:
_deployment_name = self._get_deployment(
service_name=ex_cloud_service_name, deployment_slot=ex_deployment_slot
).name
vm_image_id = None
disk_config = None
if image.extra.get("vm_image", False):
vm_image_id = image.id
# network_config = None
else:
blob_url = "http://%s.blob.core.windows.net" % (ex_storage_service_name)
disk_name = "{}-{}-{}.vhd".format(
ex_cloud_service_name,
name,
time.strftime("%Y-%m-%d"),
)
media_link = "{}/vhds/{}".format(blob_url, disk_name)
disk_config = OSVirtualHardDisk(image.id, media_link)
path = self._get_role_path(ex_cloud_service_name, _deployment_name)
body = AzureXmlSerializer.add_role_to_xml(
name, # role_name
machine_config, # system_config
disk_config, # os_virtual_hard_disk
"PersistentVMRole", # role_type
network_config, # network_config
None, # availability_set_name
None, # data_virtual_hard_disks
vm_image_id, # vm_image
size.id, # role_size
)
response = self._perform_post(path, body)
self.raise_for_response(response, 202)
self._ex_complete_async_azure_operation(response)
return Node(
id=name,
name=name,
state=NodeState.PENDING,
public_ips=[],
private_ips=[],
driver=self.connection.driver,
extra={"ex_cloud_service_name": ex_cloud_service_name},
)
def destroy_node(self, node, ex_cloud_service_name=None, ex_deployment_slot="Production"):
"""
Remove Azure Virtual Machine
This removes the instance, but does not
remove the disk. You will need to use destroy_volume.
Azure sometimes has an issue where it will hold onto
a blob lease for an extended amount of time.
:keyword ex_cloud_service_name: Required.
Name of the Azure Cloud Service.
:type ex_cloud_service_name: ``str``
:keyword ex_deployment_slot: Optional: The name of the deployment
slot. If this is not passed in we
default to production.
:type ex_deployment_slot: ``str``
"""
if not isinstance(node, Node):
raise ValueError("A libcloud Node object is required.")
if ex_cloud_service_name is None and node.extra is not None:
ex_cloud_service_name = node.extra.get("ex_cloud_service_name")
if not ex_cloud_service_name:
raise ValueError("Unable to get ex_cloud_service_name from Node.")
_deployment = self._get_deployment(
service_name=ex_cloud_service_name, deployment_slot=ex_deployment_slot
)
_deployment_name = _deployment.name
_server_deployment_count = len(_deployment.role_instance_list)
if _server_deployment_count > 1:
path = self._get_role_path(ex_cloud_service_name, _deployment_name, node.id)
else:
path = self._get_deployment_path_using_name(ex_cloud_service_name, _deployment_name)
path += "?comp=media"
self._perform_delete(path)
return True
def ex_list_cloud_services(self):
return self._perform_get(self._get_hosted_service_path(), HostedServices)
def ex_create_cloud_service(self, name, location, description=None, extended_properties=None):
"""
Create an azure cloud service.
:param name: Name of the service to create
:type name: ``str``
:param location: Standard azure location string
:type location: ``str``
:param description: Optional description
:type description: ``str``
:param extended_properties: Optional extended_properties
:type extended_properties: ``dict``
:rtype: ``bool``
"""
response = self._perform_cloud_service_create(
self._get_hosted_service_path(),
AzureXmlSerializer.create_hosted_service_to_xml(
name,
self._encode_base64(name),
description,
location,
None,
extended_properties,
),
)
self.raise_for_response(response, 201)
return True
def ex_destroy_cloud_service(self, name):
"""
Delete an azure cloud service.
:param name: Name of the cloud service to destroy.
:type name: ``str``
:rtype: ``bool``
"""
response = self._perform_cloud_service_delete(self._get_hosted_service_path(name))
self.raise_for_response(response, 200)
return True
def ex_add_instance_endpoints(self, node, endpoints, ex_deployment_slot="Production"):
all_endpoints = [
{
"name": endpoint.name,
"protocol": endpoint.protocol,
"port": endpoint.public_port,
"local_port": endpoint.local_port,
}
for endpoint in node.extra["instance_endpoints"]
]
all_endpoints.extend(endpoints)
# pylint: disable=assignment-from-no-return
result = self.ex_set_instance_endpoints(node, all_endpoints, ex_deployment_slot)
return result
def ex_set_instance_endpoints(self, node, endpoints, ex_deployment_slot="Production"):
"""
For example::
endpoint = ConfigurationSetInputEndpoint(
name='SSH',
protocol='tcp',
port=port,
local_port='22',
load_balanced_endpoint_set_name=None,
enable_direct_server_return=False
)
{
'name': 'SSH',
'protocol': 'tcp',
'port': port,
'local_port': '22'
}
"""
ex_cloud_service_name = node.extra["ex_cloud_service_name"]
vm_role_name = node.name
network_config = ConfigurationSet()
network_config.configuration_set_type = "NetworkConfiguration"
for endpoint in endpoints:
new_endpoint = ConfigurationSetInputEndpoint(**endpoint)
network_config.input_endpoints.items.append(new_endpoint)
_deployment_name = self._get_deployment(
service_name=ex_cloud_service_name, deployment_slot=ex_deployment_slot
).name
response = self._perform_put(
self._get_role_path(ex_cloud_service_name, _deployment_name, vm_role_name),
AzureXmlSerializer.add_role_to_xml(
None, # role_name
None, # system_config
None, # os_virtual_hard_disk
"PersistentVMRole", # role_type
network_config, # network_config
None, # availability_set_name
None, # data_virtual_hard_disks
None, # vm_image
None, # role_size
),
)
self.raise_for_response(response, 202)
def ex_create_storage_service(
self,
name,
location,
description=None,
affinity_group=None,
extended_properties=None,
):
"""
Create an azure storage service.
:param name: Name of the service to create
:type name: ``str``
:param location: Standard azure location string
:type location: ``str``
:param description: (Optional) Description of storage service.
:type description: ``str``
:param affinity_group: (Optional) Azure affinity group.
:type affinity_group: ``str``
:param extended_properties: (Optional) Additional configuration
options support by Azure.
:type extended_properties: ``dict``
:rtype: ``bool``
"""
response = self._perform_storage_service_create(
self._get_storage_service_path(),
AzureXmlSerializer.create_storage_service_to_xml(
service_name=name,
label=self._encode_base64(name),
description=description,
location=location,
affinity_group=affinity_group,
extended_properties=extended_properties,
),
)
self.raise_for_response(response, 202)
return True
def ex_destroy_storage_service(self, name):
"""
Destroy storage service. Storage service must not have any active
blobs. Sometimes Azure likes to hold onto volumes after they are
deleted for an inordinate amount of time, so sleep before calling
this method after volume deletion.
:param name: Name of storage service.
:type name: ``str``
:rtype: ``bool``
"""