forked from MissionCriticalCloud/cloudstackOps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudstackops.py
More file actions
1608 lines (1347 loc) · 59.4 KB
/
cloudstackops.py
File metadata and controls
1608 lines (1347 loc) · 59.4 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
# Copyright 2015, Schuberg Philis BV
#
# 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.
# Class to support tools used to operate CloudStack
# Remi Bergsma - rbergsma@schubergphilis.com
# Import the class we depend on
from cloudstackopsbase import *
# Import our dependencies
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from prettytable import PrettyTable
import subprocess
from subprocess import Popen, PIPE
import pprint
import re
# Marvin
try:
from marvin.cloudstackConnection import cloudConnection
from marvin.cloudstackException import cloudstackAPIException
from marvin.cloudstackAPI import *
from marvin import cloudstackAPI
except:
print "Error: Please install Marvin to talk to the CloudStack API:"
print " pip install ./marvin/Marvin-0.1.0.tar.gz (file is in this repository)"
sys.exit(1)
# Colored terminals
try:
from clint.textui import colored
except:
print "Error: Please install clint library to support color in the terminal:"
print " pip install clint"
sys.exit(1)
class CloudStackOps(CloudStackOpsBase):
# Init function
def __init__(self, debug=0, dryrun=0, force=0):
self.apikey = ''
self.secretkey = ''
self.api = ''
self.cloudstack = ''
self.DEBUG = debug
self.DRYRUN = dryrun
self.FORCE = force
self.configProfileNameFullPath = ''
self.apiurl = ''
self.apiserver = ''
self.apiprotocol = ''
self.apiport = ''
self.csApiClass = ''
self.conn = ''
self.organization = ''
self.smtpserver = 'localhost'
self.mail_from = ''
self.errors_to = ''
self.configfile = os.getcwd() + '/config'
self.pp = pprint.PrettyPrinter(depth=6)
self.ssh = None
self.xenserver = None
self.printWelcome()
self.checkScreen()
signal.signal(signal.SIGINT, self.catch_ctrl_C)
def printWelcome(self):
print colored.green("Welcome to CloudStackOps")
# Check if we run in a screen session
def checkScreen(self):
try:
if len(os.environ['STY']) > 0 and self.DEBUG == 1:
print "DEBUG: We're running in screen."
except:
print colored.red("Warning: You are NOT running inside screen. Please start a screen session to keep commands running in case you get disconnected!")
# Handle unwanted CTRL+C presses
def catch_ctrl_C(self, sig, frame):
print "Warning: do not interupt! If you really want to quit, use kill -9."
# Read config files
def readConfigFile(self):
# Check config file
home = expanduser("~")
self.configProfileNameFullPath = home + "/.cloudmonkey/config"
tryLocal = False
# Read config for CloudStack API credentials
try:
print "Note: Trying to use API credentials from CloudMonkey profile '" + self.configProfileName + "'"
self.parseConfig(self.configProfileNameFullPath)
except:
print colored.yellow("Warning: Cannot read or parse CloudMonkey profile '" + self.configProfileName + "'. Trying local config file..")
tryLocal = True
if self.configProfileName == "config":
tryLocal = True
if tryLocal:
# Read config for CloudStack API credentials
try:
print "Note: Trying to use API credentials from local config profile '" + self.configProfileName + "'"
self.parseConfig(self.configfile)
except:
print colored.yellow("Warning: Cannot read or parse profile '" + self.configProfileName + "' from local config file either")
# Do we have all required settings?
if self.apiurl == '' or self.apikey == '' or self.secretkey == '':
print colored.red("Error: Could not load CloudStack API settings from local config file, nor from CloudMonkey config file. Halting.")
print "Hint: Specify a CloudMonkey profile or setup the local config file 'config'. See documentation."
sys.exit(2)
# Read our own config file for some more settings
config = ConfigParser.RawConfigParser()
config.read(self.configfile)
try:
self.organization = config.get('cloudstackOps', 'organization')
self.smtpserver = config.get('mail', 'smtpserver')
self.mail_from = config.get('mail', 'mail_from')
self.errors_to = config.get('mail', 'errors_to')
except:
print "Error: Cannot read or parse CloudStackOps config file '" + self.configfile + "'"
print "Hint: Setup the local config file 'config', using 'config.sample' as a starting point. See documentation."
sys.exit(1)
# Read and parse config file
def parseConfig(self, configFile):
if self.DEBUG == 1:
print "Debug: Parsing config file " + configFile
config = ConfigParser.RawConfigParser()
config.read(configFile)
if self.DEBUG == 1:
print "Selected profile: " + self.configProfileName
# lets figure out your config:
if config.has_option('core', 'profile'):
if self.configProfileName == 'config':
# cloudmonkey > 5.2.x config without the commandline profile
# option
if self.DEBUG == 1:
print "Cloudmonkey > 5.2.x configfile found, no profile option, use profile directive from configfile"
profile = config.get('core', 'profile')
if self.DEBUG == 1:
print "Debug: profile " + profile
self.apikey = config.get(profile, 'apikey')
self.secretkey = config.get(profile, 'secretkey')
self.apiurl = config.get(profile, 'url')
elif self.configProfileName != 'config':
# cloudmonkey > 5.2.x config with the commandline profile
# option
if self.DEBUG == 1:
print "Cloudmonkey > 5.2.x configfile found, profile option given"
self.apikey = config.get(self.configProfileName, 'apikey')
self.secretkey = config.get(
self.configProfileName,
'secretkey')
self.apiurl = config.get(self.configProfileName, 'url')
# Split it, because we use an older Marvin and a newer CloudMonkey
urlParts = urlparse(self.apiurl)
self.apiport = '443'
self.apiprotocol = 'https'
if urlParts.scheme != '':
self.apiprotocol = urlParts.scheme
if urlParts.port is not None:
self.apiport = urlParts.port
elif urlParts.scheme != '' and urlParts.scheme == 'http':
self.apiport = '80'
self.apiprotocol = 'http'
self.apiserver = urlParts.hostname
else:
# cloudmonkey < 5.2.x config
if self.DEBUG == 1:
print "Cloudmonkey < 5.2.x configfile found"
self.apikey = config.get('user', 'apikey')
self.secretkey = config.get('user', 'secretkey')
self.apiport = config.get('server', 'port')
self.apiprotocol = config.get('server', 'protocol')
self.apiserver = config.get('server', 'host')
self.apiurl = self.apiprotocol + '://' + self.apiserver + \
':' + self.apiport + config.get('server', 'path')
if self.DEBUG == 1:
print "URL: " + self.apiurl
# create connection to CloudStack API
def initCloudStackAPI(self):
self.readConfigFile()
log = logging.getLogger()
if self.DEBUG == 1:
print "Debug: apiserver=" + self.apiserver + " apiKey=" + self.apikey + " securityKey=" + self.secretkey + " port=" + str(self.apiport) + " scheme=" + self.apiprotocol
try:
self.cloudstack = cloudConnection(
self.apiserver,
apiKey=self.apikey,
securityKey=self.secretkey,
asyncTimeout=14400,
logging=log,
port=int(
self.apiport),
scheme=self.apiprotocol)
if self.DEBUG == 1:
print self.cloudstack
except:
print "Error connecting to CloudStack. Are you using the right Marvin version? See README file. Halting."
sys.exit(1)
# Print name of cloud we're connected to
print "Note: Connected to '" + self.getCloudName() + "'"
# Call the CloudStack API
def _callAPI(self, apicall):
# Valid api object?
if apicall is None:
return 1
try:
data = self.cloudstack.marvin_request(apicall)
if data is None and self.DEBUG == 1:
print "Warning: Received None object from CloudStack API"
if self.DEBUG == 1:
print "DEBUG: received data:"
print data
except Exception as err:
# org.apache.cloudstack.api.ApiErrorCode Enum Reference
if "errorCode: 432" in str(err):
print "Error: Please try again with --non-admin-credentials argument, or use admin API credentials."
print "Error: Unsupported API call: %s" % str(apicall)[1:str(apicall).index(" object at ")]
sys.exit()
else:
print "Error: " + str(err)
return 1
except urllib2.HTTPError as e:
print "Error: Command failed: " + str(e.msg)
return 1
return data
# Remove empty arguments
def remove_empty_values(self, d):
if isinstance(d, dict):
return dict(
(k,
self.remove_empty_values(v)) for k,
v in d.iteritems() if v and self.remove_empty_values(v))
else:
return d
# Check if a given CloudStack name exists and return its ID if it does
def checkCloudStackName(self, args):
# Handle arguments
csname = (args['csname']) if 'csname' in args else ''
csApiCall = (args['csApiCall']) if 'csApiCall' in args else ''
listAll = (args['listAll']) if 'listAll' in args else 'false'
isProjectVm = (
args['isProjectVm']) if 'isProjectVm' in args else 'false'
# Find out which API call to make
if csApiCall == "listVirtualMachines":
apicall = listVirtualMachines.listVirtualMachinesCmd()
elif csApiCall == "listClusters":
apicall = listClusters.listClustersCmd()
elif csApiCall == "listStoragePools":
apicall = listStoragePools.listStoragePoolsCmd()
elif csApiCall == "listRouters":
apicall = listRouters.listRoutersCmd()
elif csApiCall == "listDomains":
apicall = listDomains.listDomainsCmd()
elif csApiCall == "listProjects":
apicall = listProjects.listProjectsCmd()
isProjectVm = 'false'
elif csApiCall == "listHosts":
apicall = listHosts.listHostsCmd()
elif csApiCall == "listZones":
apicall = listZones.listZonesCmd()
elif csApiCall == "listPods":
apicall = listPods.listPodsCmd()
elif csApiCall == "listZones":
apicall = listZones.listZonesCmd()
else:
print "No API command to call"
sys.exit(1)
if isProjectVm == 'true':
apicall.projectid = "-1"
if csname.startswith('i-'):
apicall.keyword = str(csname)
else:
apicall.name = str(csname)
if listAll == 'true':
apicall.listAll = "true"
try:
data = self.cloudstack.marvin_request(apicall)
if (data is None or len(data) == 0) and self.DEBUG == 1:
print "Warning: Received None object from CloudStack API"
if self.DEBUG == 1:
print "DEBUG: received data:"
print data
# Check for a result
if data:
for d in data:
# And make sure it's the correct one
if csname == d.name or csname == d.instancename:
if self.DEBUG == 1:
print "Found in loop " + str(d.name)
csnameID = d.id
break
elif self.DEBUG == 1:
print "Not found in loop " + str(d.name)
if len(csnameID) < 1:
print "Warning: '%s' could not be located in CloudStack database using '%s' or is not unique -- Exit." % (csname, csApiCall)
sys.exit(1)
else:
print "Error: '%s' could not be located in CloudStack database using '%s' -- exit!" % (csname, csApiCall)
# Exit if not found
sys.exit(1)
except Exception as err:
print "Error: " + str(err)
return 1
except urllib2.HTTPError as e:
print "Error: Command failed: " + str(e.msg)
return 1
if self.DEBUG == 1:
print "DEBUG: Found: '%s' with ID %s." % (csname, csnameID)
return csnameID
# Find Random storagePool for Cluster
def getRandomStoragePool(self, clusterID):
apicall = listStoragePools.listStoragePoolsCmd()
apicall.clusterid = str(clusterID)
apicall.listAll = "true"
# Call CloudStack API
data = self._callAPI(apicall)
# Select a random storage pool that belongs to this cluster
toStorageData = choice(data)
targetStorageID = toStorageData.id
if self.DEBUG == 1:
print "DEBUG: Selected storage pool: " + targetStorageID + " (" + toStorageData.name + ")" + " for cluster " + clusterID
return targetStorageID
# Find storagePool for Cluster
def getStoragePool(self, clusterID):
apicall = listStoragePools.listStoragePoolsCmd()
apicall.clusterid = str(clusterID)
apicall.listAll = "true"
# Call CloudStack API
data = self._callAPI(apicall)
# Select a random storage pool that belongs to this cluster
return data
# Get storagePool data
def getStoragePoolData(self, storagepoolID):
apicall = listStoragePools.listStoragePoolsCmd()
apicall.id = str(storagepoolID)
apicall.listAll = "true"
# Call CloudStack API
return self._callAPI(apicall)
# Find all hosts in a given cluster
def getAllHostsFromCluster(self, clusterID):
apicall = listHosts.listHostsCmd()
apicall.clusterid = str(clusterID)
apicall.listAll = "true"
# Call CloudStack API
return self._callAPI(apicall)
# Find hosts in a given cluster
def getHostsFromCluster(self, clusterID):
apicall = listHosts.listHostsCmd()
apicall.clusterid = str(clusterID)
apicall.resourcestate = "Enabled"
apicall.listAll = "true"
# Call CloudStack API
return self._callAPI(apicall)
# Generic listVirtualMachines function
def listVirtualmachines(self, args):
args = self.remove_empty_values(args)
apicall = listVirtualMachines.listVirtualMachinesCmd()
apicall.listAll = (args['listAll']) if 'listAll' in args else 'true'
apicall.networkid = (
str(args['networkid'])) if 'networkid' in args else None
apicall.projectid = (
'-1') if 'isProjectVm' in args and args['isProjectVm'] == 'true' else None
apicall.hostid = (str(args['hostid'])) if 'hostid' in args else None
apicall.domainid = (
str(args['domainid'])) if 'domainid' in args else None
apicall.keyword = (
args['filterKeyword']) if 'filterKeyword' in args else None
# Call CloudStack API
return self._callAPI(apicall)
# Find volumes connected to a given vmid
def getVirtualmachineVolumes(self, vmid, isProjectVm='false'):
apicall = listVolumes.listVolumesCmd()
apicall.virtualmachineid = str(vmid)
apicall.listAll = "true"
if isProjectVm == 'true':
apicall.projectid = "-1"
# Call CloudStack API
return self._callAPI(apicall)
# Get virtualserver data
def getVirtualmachineData(self, vmid, isProjectVm='false'):
apicall = listVirtualMachines.listVirtualMachinesCmd()
apicall.id = str(vmid)
apicall.listAll = "true"
if isProjectVm == 'true':
apicall.projectid = "-1"
# Call CloudStack API
return self._callAPI(apicall)
# Get virtualrouter data
def getRouterData(self, args):
args = self.remove_empty_values(args)
apicall = listRouters.listRoutersCmd()
apicall.networkid = (
str(args['networkid'])) if 'networkid' in args else None
apicall.name = (str(args['name'])) if 'name' in args else None
apicall.listAll = (args['listAll']) if 'listAll' in args else 'true'
apicall.requiresupgrade = (
str(args['requiresupgrade'])) if 'requiresupgrade' in args else None
apicall.projectid = (
'-1') if 'isProjectVm' in args and args['isProjectVm'] == 'true' else None
apicall.hostid = (str(args['hostid'])) if 'hostid' in args else None
apicall.domainid = (
str(args['domainid'])) if 'domainid' in args else None
apicall.state = (str(args['state'])) if 'state' in args else None
# Call CloudStack API
return self._callAPI(apicall)
def getRedundantRouters(self, args):
args = self.remove_empty_values(args)
# Get all routers
routerData = self.getRouterData(args)
if routerData is None or routerData == 1:
return routerData
redRouters = {}
# Loop routers and look for redundant ones
for router in routerData:
if router.isredundantrouter == False:
continue
redRouters[
router.guestnetworkid] = self.getRouterPeerData(
router.name,
'false',
'true')
# Return the redundant routers
return redRouters
# Get systemvm data
def getSystemVmData(self, args):
args = self.remove_empty_values(args)
apicall = listSystemVms.listSystemVmsCmd()
apicall.name = (str(args['name'])) if 'name' in args else None
apicall.hostid = (str(args['hostid'])) if 'hostid' in args else None
apicall.state = (str(args['state'])) if 'state' in args else None
apicall.systemvmtype = (
str(args['systemvmtype'])) if 'systemvmtype' in args else None
apicall.zoneid = (str(args['zoneid'])) if 'zoneid' in args else None
# Call CloudStack API
return self._callAPI(apicall)
# Get the peer of the given router
def getRouterPeerData(
self,
routername,
projectParam='false',
silent='false'):
routerData = self.getRouterData(
{'name': routername, 'isProjectVm': projectParam})
router = routerData[0]
for nic in router.nic:
if nic.traffictype == "Guest":
routersOfNetwork = self.getRouterData(
{'networkid': nic.networkid, 'state': 'Running'})
if routersOfNetwork is None or len(routersOfNetwork) != 2:
if silent == 'True':
print "Error: Cannot find the redundant peer of this router. Please make sure it is running before continuing."
return 1
for redundantRouter in routersOfNetwork:
if routername == redundantRouter.name:
if silent == 'True':
print "Note: Double check OK for router " + routername + ": Found myself."
else:
routerPeerData = redundantRouter
peerHostData = self.getHostData(
{'hostname': routerPeerData.hostname})
if silent == 'True':
print "Note: The redundant peer of router " + routername + " is " + routerPeerData.name + " running on " + routerPeerData.hostname + " (" + peerHostData[0].clustername + " / " + peerHostData[0].podname + ")."
returnData = {
"guestnetworkid": router.guestnetworkid,
"router": router,
"routerPeer": routerPeerData,
"clustername": peerHostData[0].clustername,
"podname": peerHostData[0].podname}
return returnData
# Stop virtualrouter
def stopRouter(self, vmid):
apicall = stopRouter.stopRouterCmd()
apicall.id = str(vmid)
# Call CloudStack API
return self._callAPI(apicall)
# Start virtualrouter
def startRouter(self, vmid):
apicall = startRouter.startRouterCmd()
apicall.id = str(vmid)
# Call CloudStack API
return self._callAPI(apicall)
# Destroy virtualrouter
def destroyRouter(self, vmid):
apicall = destroyRouter.destroyRouterCmd()
apicall.id = str(vmid)
# Call CloudStack API
return self._callAPI(apicall)
# Reboot virtualrouter
def rebootRouter(self, vmid):
apicall = rebootRouter.rebootRouterCmd()
apicall.id = str(vmid)
# Call CloudStack API
return self._callAPI(apicall)
# Send an e-mail
def sendMail(self, mailfrom, mailto, subject, htmlcontent):
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = mailfrom
msg['To'] = mailto
# HTML part
htmlpart = MIMEText(htmlcontent, 'html')
msg.attach(htmlpart)
s = smtplib.SMTP(self.smtpserver)
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
# Stop virtualvirtualmachine
def stopVirtualMachine(self, vmid):
apicall = stopVirtualMachine.stopVirtualMachineCmd()
apicall.id = str(vmid)
apicall.forced = "false"
# Call CloudStack API
return self._callAPI(apicall)
# Start virtualvirtualmachine
def startVirtualMachine(self, vmid, hostid=""):
apicall = startVirtualMachine.startVirtualMachineCmd()
apicall.id = str(vmid)
apicall.forced = "false"
if len(hostid) > 0:
apicall.hostid = hostid
# Call CloudStack API
return self._callAPI(apicall)
# migrateVirtualMachine
def migrateVirtualMachine(self, vmid, hostid):
apicall = migrateVirtualMachine.migrateVirtualMachineCmd()
apicall.virtualmachineid = str(vmid)
apicall.hostid = str(hostid)
# Call CloudStack API
return self._callAPI(apicall)
# migrateSystemVm
def migrateSystemVm(self, vmid, hostid):
apicall = migrateSystemVm.migrateSystemVmCmd()
apicall.virtualmachineid = str(vmid)
apicall.hostid = str(hostid)
# Call CloudStack API
return self._callAPI(apicall)
# migrate volume
def migrateVolume(self, volid, storageid):
apicall = migrateVolume.migrateVolumeCmd()
apicall.volumeid = str(volid)
apicall.storageid = str(storageid)
# Call CloudStack API
return self._callAPI(apicall)
def getDomainAdminUserData(self, domainid):
apicall = listUsers.listUsersCmd()
apicall.domainid = str(domainid)
# Call CloudStack API
data = self._callAPI(apicall)
if data is None or data == 1:
return 1
for userdata in data:
# Return an admin account
if "admin" in userdata.username:
return userdata
else:
continue
# Otherwise return the first one found
return data[0]
# Get host data
def getHostData(self, args):
args = self.remove_empty_values(args)
apicall = listHosts.listHostsCmd()
apicall.id = (str(args['hostid'])) if 'hostid' in args else None
apicall.name = (str(args['hostname'])) if 'hostname' in args else None
# Call CloudStack API
return self._callAPI(apicall)
# Update host tags
def updateHostTags(self, hostid, hosttags):
apicall = updateHost.updateHostCmd()
apicall.id = hostid
apicall.hosttags = hosttags
# Call CloudStack API
return self._callAPI(apicall)
# Deploy virtual machine
def deployVirtualMachine(self, args):
args = self.remove_empty_values(args)
apicall = deployVirtualMachine.deployVirtualMachineCmd()
apicall.domainid = (
str(args['domainid'])) if 'domainid' in args else None
apicall.networkids = (
str(args['networkids'])) if 'networkids' in args else None
apicall.templateid = (
str(args['templateid'])) if 'templateid' in args else None
apicall.serviceofferingid = (
str(args['serviceofferingid'])) if 'serviceofferingid' in args else None
apicall.zoneid = (str(args['zoneid'])) if 'zoneid' in args else None
apicall.account = (str(args['account'])) if 'account' in args else None
apicall.name = (str(args['name'])) if 'name' in args else None
# Call CloudStack API
return self._callAPI(apicall)
# Generate a random name
def generateRandomName(self, prefix):
name = prefix + (''.join(random.choice(string.digits)
for i in range(5)))
return name
# Destroy VM
def destroyVirtualMachine(self, vmid):
apicall = destroyVirtualMachine.destroyVirtualMachineCmd()
apicall.id = vmid
apicall.expunge = "true"
# Call CloudStack API
return self._callAPI(apicall)
# Get setting
def getConfiguration(self, setting):
apicall = listConfigurations.listConfigurationsCmd()
apicall.name = setting
# Call CloudStack API
return self._callAPI(apicall)
# Get volumes
def listVolumes(self, storageid, isProjectVm):
apicall = listVolumes.listVolumesCmd()
apicall.storageid = storageid
if isProjectVm == 'true':
apicall.projectid = "-1"
# get default.page.size
result = self.getConfiguration("default.page.size")
apicall.listAll = "true"
apicall.pagesize = result[0].value
# Call API multiple times to get all volumes
page = 0
apicall.page = page
# As long as we receive useful output, keep going
volumes = []
while result is not None:
page = page + 1
apicall.page = page
result = self._listVolumesCall(apicall)
if result is not None:
if 'volumes' in locals():
volumes = volumes + result
else:
volumes = result
return volumes
# Internal function used by listVolumes
def _listVolumesCall(self, apicall):
try:
data = self.cloudstack.marvin_request(apicall)
if (data is None) and self.DEBUG == 1:
print "Warning: Received None object from CloudStack API"
if self.DEBUG == 1:
print "DEBUG: received data:"
print data
except Exception as err:
print "Error: " + str(err)
return 1
except urllib2.HTTPError as e:
print "Error: Command failed: " + str(e.msg)
return 1
return data
# Calculate storage usage of vm
def calculateVirtualMachineStorageUsage(self, vmid, isProjectVm):
# Get vm volume data
result = self.getVirtualmachineVolumes(vmid, isProjectVm)
storageSize = 0
if result is not None:
for vol in result:
storageSize = storageSize + (vol.size / 1024 / 1024 / 1024)
return storageSize
return 0
# list clusters
def listClusters(self, args):
args = self.remove_empty_values(args)
apicall = listClusters.listClustersCmd()
apicall.id = (str(args['clusterid'])) if 'clusterid' in args else None
apicall.zoneid = (str(args['zoneid'])) if 'zoneid' in args else None
apicall.podid = (str(args['podid'])) if 'podid' in args else None
apicall.allocationstate = (
str(args['allocationstate'])) if 'allocationstate' in args else None
apicall.clustertype = (
str(args['clustertype'])) if 'clustertype' in args else None
apicall.hypervisor = (
str(args['hypervisor'])) if 'hypervisor' in args else None
apicall.name = (str(args['name'])) if 'name' in args else None
# Call CloudStack API
return self._callAPI(apicall)
# list snapshots
def listSnapshots(self, volid, isProjectVm='false'):
apicall = listSnapshots.listSnapshotsCmd()
apicall.volumeid = volid
apicall.listAll = "true"
if isProjectVm == 'true':
apicall.projectid = "-1"
# Call CloudStack API
return self._callAPI(apicall)
# list snapshotPolicies
def listSnapshotPolicies(self, volid):
apicall = listSnapshotPolicies.listSnapshotPoliciesCmd()
apicall.volumeid = volid
# Call CloudStack API
return self._callAPI(apicall)
# create snapshot policy
def createSnapshotPolicy(self, args):
args = self.remove_empty_values(args)
apicall = createSnapshotPolicy.createSnapshotPolicyCmd()
apicall.volumeid = (str(args['volid'])) if 'volid' in args else None
apicall.intervaltype = (
str(args['intervaltype'])) if 'intervaltype' in args else None
apicall.maxsnaps = (
str(args['maxsnaps'])) if 'maxsnaps' in args else None
apicall.schedule = (
str(args['schedule'])) if 'schedule' in args else None
apicall.timezone = (
str(args['timezone'])) if 'timezone' in args else 'Europe/Amsterdam'
# Call CloudStack API
return self._callAPI(apicall)
# list networks
def listNetworks(self, networkid):
apicall = listNetworks.listNetworksCmd()
apicall.id = networkid
apicall.listAll = "true"
# Call CloudStack API
return self._callAPI(apicall)
# list vpcs
def listVPCs(self, vpcid):
apicall = listVPCs.listVPCsCmd()
apicall.id = vpcid
apicall.listAll = "true"
# Call CloudStack API
return self._callAPI(apicall)
# Translate id to name, because of CLOUDSTACK-6542
def translateIntervalType(self, intervaltype):
return {
0: 'HOURLY',
1: 'DAILY',
2: 'WEEKLY',
3: 'MONTHLY'
}.get(intervaltype, 0)
# list service offerings
def listServiceOfferings(self, args):
args = self.remove_empty_values(args)
apicall = listServiceOfferings.listServiceOfferingsCmd()
apicall.id = (
str(args['serviceofferingid'])) if 'serviceofferingid' in args else None
apicall.issystem = (
str(args['issystem'])) if 'issystem' in args else None
# Call CloudStack API
return self._callAPI(apicall)
# Get hosttags
def getServiceOfferingTags(self, serviceofferingid, tagtype):
# Service Offering
serviceOfferingData = self.listServiceOfferings(
{'serviceofferingid': serviceofferingid, 'issystem': 'true'})
# The required tags
if tagtype == "host":
tags = (serviceOfferingData[0].hosttags) if serviceOfferingData[
0].hosttags is not None else ''
elif tagtype == "storage":
tags = (serviceOfferingData[0].tags) if serviceOfferingData[
0].tags is not None else ''
else:
return 1
return tags
# Check storagetags
def checkStorageTags(self, args):
args = self.remove_empty_values(args)
toClusterID = (
str(args['toClusterID'])) if 'toClusterID' in args else None
routername = (
str(args['routername'])) if 'routername' in args else None
projectParam = (
str(args['projectParam'])) if 'projectParam' in args else 'false'
if routername is None:
print "Error: required field 'routername' not supplied."
return 1
if toClusterID is None:
print "Error: required field 'toClusterID' not supplied."
return 1
# get router data
routerData = self.getRouterData(
{'name': routername, 'isProjectVm': projectParam})
router = routerData[0]
# The required tags
storagetags = self.getServiceOfferingTags(
router.serviceofferingid,
"storage")
# Check tags
storagepooltags = self.getStoragePoolTags(toClusterID)
if self.DEBUG == 1:
print "Debug: storage tags of service offering: " + storagetags
print "Debug: storage tags of storage pool: " + storagepooltags
if storagetags == '':
print "Warning: router service offering has empty storage tags."
if storagetags != '' and storagepooltags != storagetags and self.FORCE == 0:
if self.DEBUG == 1:
print "Error: cannot do this: storage tags from provided storage pool '" + storagepooltags + "' do not match your vm's service offering '" + storagetags + "'"
return 1
elif storagetags != '' and storagepooltags != storagetags and self.FORCE == 1:
if self.DEBUG == 1:
print "Warning: storage tags from provided storage pool '" + storagepooltags + "' do not match your vm's service offering '" + storagetags + "'. Since you used --FORCE you probably know what you manually need to edit in the database."
elif self.DEBUG == 1:
print "Note: Storage tags look OK."
return 0
# Check hosttags
def checkHostTags(self, args):
args = self.remove_empty_values(args)
toClusterID = (
str(args['toClusterID'])) if 'toClusterID' in args else None
routername = (
str(args['routername'])) if 'routername' in args else None
projectParam = (
str(args['projectParam'])) if 'projectParam' in args else 'false'
if routername is None:
print "Error: required field 'routername' not supplied."
return 1
if toClusterID is None:
print "Error: required field 'toClusterID' not supplied."
return 1
# get router data
routerData = self.getRouterData(
{'name': routername, 'isProjectVm': projectParam})
router = routerData[0]
# The required tags
hosttags = self.getServiceOfferingTags(
router.serviceofferingid,
"host")
if self.DEBUG == 1:
print "Debug: host tags of router: " + hosttags
# Search for hosttags on the selected cluster
toClusterHostsData = self.getHostsFromCluster(toClusterID)
foundHostTag = False
if toClusterHostsData is not None:
for host in toClusterHostsData:
if self.DEBUG == 1:
print "Debug: Checking host tags of host " + host.name
if host.hosttags is not None:
if hosttags in host.hosttags:
foundHostTag = True
if hosttags != '' and foundHostTag == False and self.FORCE == 0:
if self.DEBUG == 1:
print "Error: cannot do this: the hosts in your selected cluster do not have the tags '" + hosttags + "' that are required by your router's service offering."
return 1