/
cloudstack.py
1804 lines (1443 loc) · 59.6 KB
/
cloudstack.py
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.
from __future__ import with_statement
import base64
import warnings
from libcloud.utils.py3 import b
from libcloud.utils.py3 import urlparse
from libcloud.compute.providers import Provider
from libcloud.common.cloudstack import CloudStackDriverMixIn
from libcloud.compute.base import Node, NodeDriver, NodeImage, NodeLocation
from libcloud.compute.base import NodeSize, StorageVolume
from libcloud.compute.base import KeyPair
from libcloud.compute.types import NodeState, LibcloudError
from libcloud.compute.types import KeyPairDoesNotExistError
from libcloud.utils.networking import is_private_subnet
"""
Define the extra dictionary for specific resources
"""
RESOURCE_EXTRA_ATTRIBUTES_MAP = {
'network': {
'broadcast_domain_type': {
'key_name': 'broadcastdomaintype',
'transform_func': str
},
'traffic_type': {
'key_name': 'traffictype',
'transform_func': str
},
'zone_name': {
'key_name': 'zonename',
'transform_func': str
},
'network_offering_name': {
'key_name': 'networkofferingname',
'transform_func': str
},
'network_offeringdisplay_text': {
'key_name': 'networkofferingdisplaytext',
'transform_func': str
},
'network_offering_availability': {
'key_name': 'networkofferingavailability',
'transform_func': str
},
'is_system': {
'key_name': 'issystem',
'transform_func': str
},
'state': {
'key_name': 'state',
'transform_func': str
},
'dns1': {
'key_name': 'dns1',
'transform_func': str
},
'dns2': {
'key_name': 'dns2',
'transform_func': str
},
'type': {
'key_name': 'type',
'transform_func': str
},
'acl_type': {
'key_name': 'acltype',
'transform_func': str
},
'subdomain_access': {
'key_name': 'subdomainaccess',
'transform_func': str
},
'network_domain': {
'key_name': 'networkdomain',
'transform_func': str
},
'physical_network_id': {
'key_name': 'physicalnetworkid',
'transform_func': str
},
'can_use_for_deploy': {
'key_name': 'canusefordeploy',
'transform_func': str
}
},
'node': {
'haenable': {
'key_name': 'haenable',
'transform_func': str
},
'zone_id': {
'key_name': 'zoneid',
'transform_func': str
},
'zone_name': {
'key_name': 'zonename',
'transform_func': str
},
'key_name': {
'key_name': 'keypair',
'transform_func': str
},
'password': {
'key_name': 'password',
'transform_func': str
},
'image_id': {
'key_name': 'templateid',
'transform_func': str
},
'image_name': {
'key_name': 'templatename',
'transform_func': str
},
'template_display_text': {
'key_name': 'templatdisplaytext',
'transform_func': str
},
'password_enabled': {
'key_name': 'passwordenabled',
'transform_func': str
},
'size_id': {
'key_name': 'serviceofferingid',
'transform_func': str
},
'size_name': {
'key_name': 'serviceofferingname',
'transform_func': str
},
'root_device_id': {
'key_name': 'rootdeviceid',
'transform_func': str
},
'root_device_type': {
'key_name': 'rootdevicetype',
'transform_func': str
},
'hypervisor': {
'key_name': 'hypervisor',
'transform_func': str
}
},
'volume': {
'created': {
'key_name': 'created',
'transform_func': str
},
'device_id': {
'key_name': 'deviceid',
'transform_func': int
},
'instance_id': {
'key_name': 'serviceofferingid',
'transform_func': str
},
'state': {
'key_name': 'state',
'transform_func': str
},
'volume_type': {
'key_name': 'type',
'transform_func': str
},
'zone_id': {
'key_name': 'zoneid',
'transform_func': str
},
'zone_name': {
'key_name': 'zonename',
'transform_func': str
}
}
}
class CloudStackNode(Node):
"""
Subclass of Node so we can expose our extension methods.
"""
def ex_allocate_public_ip(self):
"""
Allocate a public IP and bind it to this node.
"""
return self.driver.ex_allocate_public_ip(self)
def ex_release_public_ip(self, address):
"""
Release a public IP that this node holds.
"""
return self.driver.ex_release_public_ip(self, address)
def ex_create_ip_forwarding_rule(self, address, protocol,
start_port, end_port=None):
"""
Add a NAT/firewall forwarding rule for a port or ports.
"""
return self.driver.ex_create_ip_forwarding_rule(node=self,
address=address,
protocol=protocol,
start_port=start_port,
end_port=end_port)
def ex_create_port_forwarding_rule(self, address,
private_port, public_port,
protocol,
public_end_port=None,
private_end_port=None,
openfirewall=True):
"""
Add a port forwarding rule for port or ports.
"""
return self.driver.ex_create_port_forwarding_rule(node=self,
address=
address,
private_port=
private_port,
public_port=
public_port,
protocol=protocol,
public_end_port=
public_end_port,
private_end_port=
private_end_port,
openfirewall=
openfirewall)
def ex_delete_ip_forwarding_rule(self, rule):
"""
Delete a port forwarding rule.
"""
return self.driver.ex_delete_ip_forwarding_rule(node=self, rule=rule)
def ex_delete_port_forwarding_rule(self, rule):
"""
Delete a NAT/firewall rule.
"""
return self.driver.ex_delete_port_forwarding_rule(node=self, rule=rule)
def ex_start(self):
"""
Starts a stopped virtual machine.
"""
return self.driver.ex_start(node=self)
def ex_stop(self):
"""
Stops a running virtual machine.
"""
return self.driver.ex_stop(node=self)
class CloudStackAddress(object):
"""
A public IP address.
"""
def __init__(self, id, address, driver):
self.id = id
self.address = address
self.driver = driver
def release(self):
self.driver.ex_release_public_ip(address=self)
def __str__(self):
return self.address
def __eq__(self, other):
return self.__class__ is other.__class__ and self.id == other.id
class CloudStackIPForwardingRule(object):
"""
A NAT/firewall forwarding rule.
"""
def __init__(self, node, id, address, protocol, start_port, end_port=None):
self.node = node
self.id = id
self.address = address
self.protocol = protocol
self.start_port = start_port
self.end_port = end_port
def delete(self):
self.node.ex_delete_ip_forwarding_rule(rule=self)
def __eq__(self, other):
return self.__class__ is other.__class__ and self.id == other.id
class CloudStackPortForwardingRule(object):
"""
A Port forwarding rule for Source NAT.
"""
def __init__(self, node, rule_id, address, protocol, public_port,
private_port, public_end_port=None, private_end_port=None):
"""
A Port forwarding rule for Source NAT.
@note: This is a non-standard extension API, and only works for EC2.
:param node: Node for rule
:type node: :class:`Node`
:param rule_id: Rule ID
:type rule_id: ``int``
:param address: External IP address
:type address: :class:`CloudStackAddress`
:param protocol: TCP/IP Protocol (TCP, UDP)
:type protocol: ``str``
:param public_port: External port for rule (or start port if
public_end_port is also provided)
:type public_port: ``int``
:param private_port: Internal node port for rule (or start port if
public_end_port is also provided)
:type private_port: ``int``
:param public_end_port: End of external port range
:type public_end_port: ``int``
:param private_end_port: End of internal port range
:type private_end_port: ``int``
:rtype: :class:`CloudStackPortForwardingRule`
"""
self.node = node
self.id = rule_id
self.address = address
self.protocol = protocol
self.public_port = public_port
self.public_end_port = public_end_port
self.private_port = private_port
self.private_end_port = private_end_port
def delete(self):
self.node.ex_delete_port_forwarding_rule(rule=self)
def __eq__(self, other):
return self.__class__ is other.__class__ and self.id == other.id
class CloudStackDiskOffering(object):
"""
A disk offering within CloudStack.
"""
def __init__(self, id, name, size, customizable):
self.id = id
self.name = name
self.size = size
self.customizable = customizable
def __eq__(self, other):
return self.__class__ is other.__class__ and self.id == other.id
class CloudStackNetwork(object):
"""
Class representing a CloudStack Network.
"""
def __init__(self, displaytext, name, networkofferingid, id, zoneid,
driver, extra=None):
self.displaytext = displaytext
self.name = name
self.networkofferingid = networkofferingid
self.id = id
self.zoneid = zoneid
self.driver = driver
self.extra = extra or {}
def __repr__(self):
return (('<CloudStackNetwork: id=%s, displaytext=%s, name=%s, '
'networkofferingid=%s, zoneid=%s, driver%s>')
% (self.id, self.displaytext, self.name,
self.networkofferingid, self.zoneid, self.driver.name))
class CloudStackNodeDriver(CloudStackDriverMixIn, NodeDriver):
"""
Driver for the CloudStack API.
:cvar host: The host where the API can be reached.
:cvar path: The path where the API can be reached.
:cvar async_poll_frequency: How often (in seconds) to poll for async
job completion.
:type async_poll_frequency: ``int``"""
name = 'CloudStack'
api_name = 'cloudstack'
website = 'http://cloudstack.org/'
type = Provider.CLOUDSTACK
features = {'create_node': ['generates_password']}
NODE_STATE_MAP = {
'Running': NodeState.RUNNING,
'Starting': NodeState.REBOOTING,
'Stopped': NodeState.STOPPED,
'Stopping': NodeState.STOPPED,
'Destroyed': NodeState.TERMINATED,
'Expunging': NodeState.TERMINATED,
'Error': NodeState.TERMINATED
}
def __init__(self, key, secret=None, secure=True, host=None,
path=None, port=None, url=None, *args, **kwargs):
"""
:inherits: :class:`NodeDriver.__init__`
:param host: The host where the API can be reached. (required)
:type host: ``str``
:param path: The path where the API can be reached. (required)
:type path: ``str``
:param url: Full URL to the API endpoint. Mutually exclusive with host
and path argument.
:type url: ``str``
"""
if url:
parsed = urlparse.urlparse(url)
path = parsed.path
scheme = parsed.scheme
split = parsed.netloc.split(':')
if len(split) == 1:
# No port provided, use the default one
host = parsed.netloc
port = 443 if scheme == 'https' else 80
else:
host = split[0]
port = int(split[1])
else:
host = host if host else self.host
path = path if path else self.path
if path is not None:
self.path = path
if host is not None:
self.host = host
if (self.type == Provider.CLOUDSTACK) and (not host or not path):
raise Exception('When instantiating CloudStack driver directly '
'you also need to provide url or host and path '
'argument')
super(CloudStackNodeDriver, self).__init__(key=key,
secret=secret,
secure=secure,
host=host,
port=port)
def list_images(self, location=None):
args = {
'templatefilter': 'executable'
}
if location is not None:
args['zoneid'] = location.id
imgs = self._sync_request(command='listTemplates',
params=args,
method='GET')
images = []
for img in imgs.get('template', []):
images.append(NodeImage(
id=img['id'],
name=img['name'],
driver=self.connection.driver,
extra={
'hypervisor': img['hypervisor'],
'format': img['format'],
'os': img['ostypename'],
'displaytext': img['displaytext']}))
return images
def list_locations(self):
"""
:rtype ``list`` of :class:`NodeLocation`
"""
locs = self._sync_request('listZones')
locations = []
for loc in locs['zone']:
location = NodeLocation(str(loc['id']), loc['name'], 'Unknown',
self)
locations.append(location)
return locations
def list_nodes(self):
"""
@inherits: :class:`NodeDriver.list_nodes`
:rtype: ``list`` of :class:`CloudStackNode`
"""
vms = self._sync_request('listVirtualMachines')
addrs = self._sync_request('listPublicIpAddresses')
public_ips_map = {}
for addr in addrs.get('publicipaddress', []):
if 'virtualmachineid' not in addr:
continue
vm_id = str(addr['virtualmachineid'])
if vm_id not in public_ips_map:
public_ips_map[vm_id] = {}
public_ips_map[vm_id][addr['ipaddress']] = addr['id']
nodes = []
for vm in vms.get('virtualmachine', []):
public_ips = public_ips_map.get(str(vm['id']), {}).keys()
public_ips = list(public_ips)
node = self._to_node(data=vm, public_ips=public_ips)
addresses = public_ips_map.get(vm['id'], {}).items()
addresses = [CloudStackAddress(node, v, k) for k, v in addresses]
node.extra['ip_addresses'] = addresses
rules = []
for addr in addresses:
result = self._sync_request('listIpForwardingRules')
for r in result.get('ipforwardingrule', []):
if str(r['virtualmachineid']) == node.id:
rule = CloudStackIPForwardingRule(node, r['id'],
addr,
r['protocol']
.upper(),
r['startport'],
r['endport'])
rules.append(rule)
node.extra['ip_forwarding_rules'] = rules
rules = []
public_ips = self.ex_list_public_ips()
result = self._sync_request('listPortForwardingRules')
for r in result.get('portforwardingrule', []):
if str(r['virtualmachineid']) == node.id:
addr = [a for a in public_ips if
a.address == r['ipaddress']]
rule = CloudStackPortForwardingRule(node, r['id'],
addr[0],
r['protocol'].upper(),
r['publicport'],
r['privateport'],
r['publicendport'],
r['privateendport'])
if not addr[0].address in node.public_ips:
node.public_ips.append(addr[0].address)
rules.append(rule)
node.extra['port_forwarding_rules'] = rules
nodes.append(node)
return nodes
def list_sizes(self, location=None):
"""
:rtype ``list`` of :class:`NodeSize`
"""
szs = self._sync_request(command='listServiceOfferings',
method='GET')
sizes = []
for sz in szs['serviceoffering']:
extra = {'cpu': sz['cpunumber']}
sizes.append(NodeSize(sz['id'], sz['name'], sz['memory'], 0, 0,
0, self, extra=extra))
return sizes
def create_node(self, **kwargs):
"""
Create a new node
@inherits: :class:`NodeDriver.create_node`
:keyword networks: Optional list of networks to launch the server
into.
:type networks: ``list`` of :class:`.CloudStackNetwork`
:keyword ex_keyname: Name of existing keypair
:type ex_keyname: ``str``
:keyword ex_userdata: String containing user data
:type ex_userdata: ``str``
:keyword ex_security_groups: List of security groups to assign to
the node
:type ex_security_groups: ``list`` of ``str``
:rtype: :class:`.CloudStackNode`
"""
server_params = self._create_args_to_params(None, **kwargs)
data = self._async_request(command='deployVirtualMachine',
params=server_params,
method='GET')['virtualmachine']
node = self._to_node(data=data)
return node
def _create_args_to_params(self, node, **kwargs):
server_params = {
'name': kwargs.get('name'),
}
# TODO: Refactor and use "kwarg_to_server_params" map
name = kwargs.get('name', None)
size = kwargs.get('size', None)
image = kwargs.get('image', None)
location = kwargs.get('location', None)
networks = kwargs.get('networks', None)
ex_key_name = kwargs.get('ex_keyname', None)
ex_user_data = kwargs.get('ex_userdata', None)
ex_security_groups = kwargs.get('ex_security_groups', None)
if name:
server_params['name'] = name
if size:
server_params['serviceofferingid'] = size.id
if image:
server_params['templateid'] = image.id
if location:
server_params['zoneid'] = location.id
else:
# Use a default location
server_params['zoneid'] = self.list_locations()[0].id
if networks:
networks = ','.join([network.id for network in networks])
server_params['networkids'] = networks
if ex_key_name:
server_params['keypair'] = ex_key_name
if ex_user_data:
ex_user_data = base64.b64encode(b(ex_user_data).decode('ascii'))
server_params['userdata'] = ex_user_data
if ex_security_groups:
ex_security_groups = ','.join(ex_security_groups)
server_params['securitygroupnames'] = ex_security_groups
return server_params
def destroy_node(self, node):
"""
@inherits: :class:`NodeDriver.reboot_node`
:type node: :class:`CloudStackNode`
:rtype: ``bool``
"""
self._async_request(command='destroyVirtualMachine',
params={'id': node.id},
method='GET')
return True
def reboot_node(self, node):
"""
@inherits: :class:`NodeDriver.reboot_node`
:type node: :class:`CloudStackNode`
:rtype: ``bool``
"""
self._async_request(command='rebootVirtualMachine',
params={'id': node.id},
method='GET')
return True
def ex_start(self, node):
"""
Starts/Resumes a stopped virtual machine
:type node: :class:`CloudStackNode`
:param id: The ID of the virtual machine (required)
:type id: ``str``
:param hostid: destination Host ID to deploy the VM to
parameter available for root admin only
:type hostid: ``str``
:rtype ``str``
"""
res = self._async_request(command='startVirtualMachine',
params={'id': node.id},
method='GET')
return res['virtualmachine']['state']
def ex_stop(self, node):
"""
Stops/Suspends a running virtual machine
:param node: Node to stop.
:type node: :class:`CloudStackNode`
:rtype: ``str``
"""
res = self._async_request(command='stopVirtualMachine',
params={'id': node.id},
method='GET')
return res['virtualmachine']['state']
def ex_list_disk_offerings(self):
"""
Fetch a list of all available disk offerings.
:rtype: ``list`` of :class:`CloudStackDiskOffering`
"""
diskOfferings = []
diskOfferResponse = self._sync_request(command='listDiskOfferings',
method='GET')
for diskOfferDict in diskOfferResponse.get('diskoffering', ()):
diskOfferings.append(
CloudStackDiskOffering(
id=diskOfferDict['id'],
name=diskOfferDict['name'],
size=diskOfferDict['disksize'],
customizable=diskOfferDict['iscustomized']))
return diskOfferings
def ex_list_networks(self):
"""
List the available networks
:rtype ``list`` of :class:`CloudStackNetwork`
"""
res = self._sync_request(command='listNetworks',
method='GET')
nets = res.get('network', [])
networks = []
extra_map = RESOURCE_EXTRA_ATTRIBUTES_MAP['network']
for net in nets:
extra = self._get_extra_dict(net, extra_map)
if 'tags' in net:
extra['tags'] = self._get_resource_tags(net['tags'])
networks.append(CloudStackNetwork(
net['displaytext'],
net['name'],
net['networkofferingid'],
net['id'],
net['zoneid'],
self,
extra=extra))
return networks
def create_volume(self, size, name, location=None, snapshot=None):
"""
Creates a data volume
Defaults to the first location
"""
for diskOffering in self.ex_list_disk_offerings():
if diskOffering.size == size or diskOffering.customizable:
break
else:
raise LibcloudError(
'Disk offering with size=%s not found' % size)
if location is None:
location = self.list_locations()[0]
params = {'name': name,
'diskOfferingId': diskOffering.id,
'zoneId': location.id}
if diskOffering.customizable:
params['size'] = size
requestResult = self._async_request(command='createVolume',
params=params,
method='GET')
volumeResponse = requestResult['volume']
return StorageVolume(id=volumeResponse['id'],
name=name,
size=size,
driver=self,
extra=dict(name=volumeResponse['name']))
def destroy_volume(self, volume):
"""
:rtype: ``bool``
"""
self._sync_request(command='deleteVolume',
params={'id': volume.id},
method='GET')
return True
def attach_volume(self, node, volume, device=None):
"""
@inherits: :class:`NodeDriver.attach_volume`
:type node: :class:`CloudStackNode`
:rtype: ``bool``
"""
# TODO Add handling for device name
self._async_request(command='attachVolume',
params={'id': volume.id,
'virtualMachineId': node.id},
method='GET')
return True
def detach_volume(self, volume):
"""
:rtype: ``bool``
"""
self._async_request(command='detachVolume',
params={'id': volume.id},
method='GET')
return True
def list_volumes(self, node=None):
"""
List all volumes
:param node: Only return volumes for the provided node.
:type node: :class:`CloudStackNode`
:rtype: ``list`` of :class:`StorageVolume`
"""
if node:
volumes = self._sync_request(command='listVolumes',
params={'virtualmachineid': node.id},
method='GET')
else:
volumes = self._sync_request(command='listVolumes',
method='GET')
list_volumes = []
extra_map = RESOURCE_EXTRA_ATTRIBUTES_MAP['volume']
for vol in volumes['volume']:
extra = self._get_extra_dict(vol, extra_map)
if 'tags' in vol:
extra['tags'] = self._get_resource_tags(vol['tags'])
list_volumes.append(StorageVolume(id=vol['id'],
name=vol['name'],
size=vol['size'],
driver=self,
extra=extra))
return list_volumes
def list_key_pairs(self, **kwargs):
"""
List registered key pairs.
:param projectid: list objects by project
:type projectid: ``str``
:param page: The page to list the keypairs from
:type page: ``int``
:param keyword: List by keyword
:type keyword: ``str``
:param listall: If set to false, list only resources
belonging to the command's caller;
if set to true - list resources that
the caller is authorized to see.
Default value is false
:type listall: ``bool``
:param pagesize: The number of results per page
:type pagesize: ``int``
:param account: List resources by account.
Must be used with the domainId parameter
:type account: ``str``
:param isrecursive: Defaults to false, but if true,
lists all resources from
the parent specified by the
domainId till leaves.
:type isrecursive: ``bool``
:param fingerprint: A public key fingerprint to look for
:type fingerprint: ``str``
:param name: A key pair name to look for
:type name: ``str``
:param domainid: List only resources belonging to
the domain specified
:type domainid: ``str``
:return: A list of key par objects.
:rtype: ``list`` of :class:`libcloud.compute.base.KeyPair`
"""
extra_args = kwargs.copy()
res = self._sync_request(command='listSSHKeyPairs',
params=extra_args,
method='GET')
key_pairs = res.get('sshkeypair', [])
key_pairs = self._to_key_pairs(data=key_pairs)
return key_pairs
def get_key_pair(self, name):
params = {'name': name}
res = self._sync_request(command='listSSHKeyPairs',
params=params,
method='GET')
key_pairs = res.get('sshkeypair', [])
if len(key_pairs) == 0:
raise KeyPairDoesNotExistError(name=name, driver=self)
key_pair = self._to_key_pair(data=key_pairs[0])
return key_pair
def create_key_pair(self, name, **kwargs):
"""
Create a new key pair object.
:param name: Key pair name.
:type name: ``str``
:param name: Name of the keypair (required)
:type name: ``str``
:param projectid: An optional project for the ssh key
:type projectid: ``str``
:param domainid: An optional domainId for the ssh key.
If the account parameter is used,
domainId must also be used.
:type domainid: ``str``
:param account: An optional account for the ssh key.
Must be used with domainId.
:type account: ``str``
:return: Created key pair object.
:rtype: :class:`libcloud.compute.base.KeyPair`
"""
extra_args = kwargs.copy()
params = {'name': name}
params.update(extra_args)
res = self._sync_request(command='createSSHKeyPair',
params=params,
method='GET')
key_pair = self._to_key_pair(data=res['keypair'])
return key_pair
def import_key_pair_from_string(self, name, key_material):
"""
Import a new public key from string.
:param name: Key pair name.
:type name: ``str``
:param key_material: Public key material.
:type key_material: ``str``
:return: Imported key pair object.
:rtype: :class:`libcloud.compute.base.KeyPair`
"""
res = self._sync_request(command='registerSSHKeyPair',
params={'name': name,