This repository has been archived by the owner on Jul 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
vminute.py
executable file
·1583 lines (1407 loc) · 57.8 KB
/
vminute.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
# -*- coding: utf-8 -*-
import fcntl
import getopt
import math
import os
import random
import re
import subprocess
import sys
import termios
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from prettytable import PrettyTable
try:
from urllib import urlopen
except ImportError:
from urllib.request import urlopen
try:
from cinderclient import client as cinder_client
from cinderclient import exceptions as cinder_exceptions
from heatclient import client as heat_client
from heatclient import exc as heat_exceptions
from neutronclient.neutron import client as neutron_client
from novaclient import client as nova_client
from novaclient import exceptions as nova_exceptions
from keystoneauth1 import loading as keystoneLoading
from keystoneauth1 import session as keystoneSession
from keystoneclient.v3 import client as keystone_client
from glanceclient import client as glance_client
import xmltodict
except ImportError as ie:
sys.stderr.write(str(ie) + "\n")
sys.stderr.write("The list of required modules are in requires.txt.\n")
sys.exit(1)
try:
# Python 2.7
from functools import wraps
except Exception:
# Python 2.4
from backports.functools import wraps
CONF_DIR = '~/.5minute'
USER = os.environ["USER"]
DEBUG = False
DISABLE_CATCH = False
PROGRESS = None
# -----------------------------------------------------------
# Helpers functions
# -----------------------------------------------------------
def die(message, excode=1, exception=None):
"""
Print error message into stdErr
:param message: message
:param excode: exitcode
:param exception: exception for debugging mode
"""
global PROGRESS
if PROGRESS is not None:
if sys.stderr.isatty():
progress(result="\x1b[31;01mFAIL\x1b[39;49;00m")
else:
progress(result="FAIL")
global DEBUG
if exception and DEBUG:
exc_type, exc_value, exc_traceback = sys.exc_info()
sys.stderr.write("\n\x1b[92;01m")
traceback.print_tb(exc_traceback)
sys.stderr.write("\x1b[39;49;00m\n")
if sys.stderr.isatty():
sys.stderr.write("\n\x1b[31;01m%s\x1b[39;49;00m\n\n" % message)
else:
sys.stderr.write("\n%s\n\n" % message)
sys.exit(excode)
def warning(message, answer=None):
"""
Print warning message into srdErr and may can for answer
:param message: message
:param answer: list of supported options. Default is first item.
"""
c = ""
if sys.stderr.isatty():
sys.stderr.write("\n\x1b[92;01m%s " % message)
else:
sys.stderr.write("\n%s " % message)
if answer:
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
break
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
c = ("%s" % c).lower()
if sys.stderr.isatty():
sys.stderr.write(" %s\x1b[39;49;00m\n\n" % c)
else:
sys.stderr.write(" %s\n\n" % c)
if answer:
for it in answer:
if c in it:
return c
return answer.pop(0)
def progress(title=None, result=None):
"""
Function for displaying of progress bar.
Example of using:
progress(title="Name of action")
for i in range(0, 30):
progress()
progress(result="GOOD")
"""
CHARS = ('.', '-', '=', '_')
global PROGRESS
if title:
PROGRESS = 0
sys.stdout.write("%s" % title.ljust(40, " "))
if result:
if sys.stderr.isatty():
sys.stdout.write("%s\x1b[92;01m%s\x1b[39;49;00m\n" %
("\b" * (PROGRESS % 20), result.ljust(20, " ")))
else:
sys.stdout.write("%s%s\n" %
("\b" * (PROGRESS % 20), result.ljust(20, " ")))
PROGRESS = None
if title is None and result is None:
PROGRESS += 1
if PROGRESS % 20 == 0:
sys.stdout.write("\b" * 19)
PROGRESS += 1
sys.stdout.write(CHARS[int(math.ceil(PROGRESS / 20)) % len(CHARS)])
sys.stdout.flush()
def catch_exception(text=None, type=Exception):
""" Decorator for catch exception """
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
catch_message = text
try:
return func(*args, **kwargs)
except type as ex:
if not DISABLE_CATCH:
if catch_message is None:
catch_message = str(ex)
die(catch_message, exception=ex)
else:
raise ex
return wrapper
return decorate
class disable_catch_exception:
""" Disable decorator for catch exception. """
def __enter__(self):
global DISABLE_CATCH
DISABLE_CATCH = True
def __exit__(self, type, value, traceback):
global DISABLE_CATCH
DISABLE_CATCH = False
def get_FQDN_from_IP(ip):
# If we want to support old version of OpenStack, we have to update this function and
# solve it via serviceman
return "ci-vm-{0}-{1}-{2}-{3}.hosted.upshift.rdu2.redhat.com".format(*ip.split("."))
# -----------------------------------------------------------
# Classes
# -----------------------------------------------------------
class BaseClass(object):
__nova = None
__keystone = None
__cinder = None
__heat = None
__session = None
__neutron = None
__first_check = False
__tmpconf = "/tmp/5minute.conf"
__profiles = "profiles/"
__scenarios = "scenarios/"
__check_env_done = False
key_name = USER
@catch_exception(
"The configuration file ~/.5minute/config does not exist.\n"
"Please download the OpenStack RC file from OpenStack WebUI (Access & Security > API Access "
"> Download OpenStack RC file) and save it to ~/.5minute/config.\n")
def __load_configuration(self):
if not os.path.isfile(self.__tmpconf):
subprocess.check_call("source {config_loc}/config; env | grep OS_ >> {tmpfile}"
.format(config_loc=CONF_DIR, tmpfile=self.__tmpconf), shell=True)
lines = []
with open(os.path.expanduser(self.__tmpconf), "r") as fd:
lines = fd.readlines()
rx2 = re.compile(r'^\s*([A-z_]*)="?([^"]*)"?\s*$')
for it in lines:
res = rx2.search(it)
if res:
key, value = res.groups()
os.environ[key] = value.strip()
def __checkenv(self):
if self.__check_env_done:
return
if not os.environ.get('OS_AUTH_URL') or \
not os.environ.get('OS_PROJECT_NAME') or \
not os.environ.get('OS_USERNAME') or \
not os.environ.get('OS_PASSWORD'):
if not self.__first_check:
self.__load_configuration()
self.__first_check = True
self.__checkenv()
else:
die("The configuration file %s/config doesn't contain all required variables.\n" % CONF_DIR)
if not os.path.isdir(os.path.expanduser(os.path.join(CONF_DIR, self.__profiles))):
try:
os.makedirs(os.path.expanduser(os.path.join(CONF_DIR, self.__profiles)))
except OSError:
die("Problem while creating the profiles folder '%s'." % os.path.join(CONF_DIR, self.__profiles))
if not os.path.isdir(os.path.expanduser(os.path.join(CONF_DIR, self.__scenarios))):
try:
os.makedirs(os.path.expanduser(os.path.join(CONF_DIR, self.__scenarios)))
except OSError:
die("Problem while creating the scenarios folder '%s'." % os.path.join(CONF_DIR, self.__scenarios))
self.__check_env_done = True
@catch_exception("Your SSL pub-key is not uploaded to the server yet. "
"Please use: 5minute key ~/.ssh/id_dsa.pub")
def _check_key(self):
self.nova.keypairs.get(self.key_name)
def __get_cinder(self):
if not self.__cinder:
self.__cinder = cinder_client.Client(2, session=self.__get_session())
return self.__cinder
def __get_heat(self):
if not self.__heat:
self.__heat = heat_client.Client(1, session=self.__get_session())
return self.__heat
def __get_keystone(self):
if not self.__keystone:
self.__checkenv()
self.__keystone = keystone_client.Client(session=self.__get_session())
return self.__keystone
def __get_glance(self):
if not self.__glance:
self.__glance = glance_client.Client(2, session=self.__get_session())
return self.__glance
def __get_nova(self):
if self.__nova:
return self.__nova
self.__checkenv()
import novaclient
nc_maj_ver, nc_ver_discard = novaclient.__version__.split('.', 1)
# this is work around a change that occurred in
# novaclient somewhere between version 6 and 9.
# Possibly this needs to be changed to check
# against version 8 or 7.
if int(nc_maj_ver) < 9:
self.__nova = nova_client.Client(2,
username=os.environ.get('OS_USERNAME'),
password=os.environ.get('OS_PASSWORD'),
project_id=os.environ.get('OS_PROJECT_NAME'),
app_version=os.environ.get('OS_IDENTITY_API_VERSION'),
auth_url=os.environ.get('OS_AUTH_URL'))
else:
self.__nova = nova_client.Client(2, session=self.__get_session())
return self.__nova
def __get_session(self):
if not self.__session:
self.__checkenv()
loader = keystoneLoading.get_plugin_loader('password')
auth = loader.load_from_options(username=os.environ.get('OS_USERNAME'),
password=os.environ.get('OS_PASSWORD'),
project_id=os.environ.get('OS_PROJECT_ID'),
user_domain_name=os.environ.get('OS_USER_DOMAIN_NAME'),
project_domain_id=os.environ.get('OS_PROJECT_DOMAIN_ID'),
auth_url=os.environ.get('OS_AUTH_URL'))
self.__session = keystoneSession.Session(auth=auth)
return self.__session
def __get_neutron(self):
if not self.__neutron:
self.__neutron = neutron_client.Client('2.0', session=self.__get_session())
return self.__neutron
def __get_endpoint(self, name):
endpoints = self.keystone.service_catalog.get_endpoints()
if name not in endpoints:
die("This endpoint '%s' is not known" % name)
return endpoints.get(name)[0]['publicURL']
def __getattr__(self, name):
if name == 'cinder':
return self.__get_cinder()
elif name == 'heat':
return self.__get_heat()
elif name == 'nova':
return self.__get_nova()
elif name == 'keystone':
return self.__get_keystone()
elif name == 'neutron':
return self.__get_neutron()
elif name == 'glance':
return self.__get_glance()
return None
@catch_exception("The problem parsing profile XML file. ")
def __get_scenario(self, filename):
xml = None
try:
xml = urlopen('https://example.com/scenarios/%s' % filename).read()
except Exception:
warning("Profile '%s' doesn't exist." % filename)
return dict()
return xmltodict.parse(xml)
def cmd(self, argv):
self.help()
def help(self):
print("""
Usage: 5minute <-d|--debug> [COMMAND]
Manager for your OpenStack machines.
OPTIONS:
-d, --debug - enable debugging mode.
COMMANDS:
help - this help
key - upload your SSH key to the server
images - the list of accessible images
flavors - the list of flavors
list - the list of instances
delete - delete a quest
boot - create a new quest
snapshot - create s snapshot of the instance
scenario - working with scenarios
Examples:
5minute help
5minute key ~/.ssh/id_dsa.pub
5minute images
5minute images -h
5minute images --all
5minute images satellite
5minute flavors
5minute list
5minute list --all
5minute list satellite
5minute boot --help
5minute boot 5minute-RHEL6
5minute boot --name myRHEL6 5minute-RHEL6
5minute snapshot --help
5minute scenarios --help
""")
class KeyClass(BaseClass):
@catch_exception("The problem with public key upload.")
def __upload_key(self, key):
if not os.access(key, os.R_OK):
die("SSL key '%s' is not readable." % key)
keypairs = self.nova.keypairs.list()
for keypair in keypairs:
if (keypair.name == self.key_name):
die("You already have keypair with name %s" % self.key_name)
with open(key) as fd:
self.nova.keypairs.create(self.key_name, fd.read())
print(("The key %s was uploaded successfully." % key))
def cmd(self, argv):
if len(argv) == 0 or argv[0] in ('help', '--help', '-h'):
self.help()
else:
self.__upload_key(argv[0])
def help(self):
print("""
Usage: 5minute key <SSH-PUB-KEY>
Upload your SSH key to the OpenStack server.
Examples:
5minute key ~/.ssh/id_dsa.pub
""")
class ImagesClass(BaseClass):
__filter = None
__default_filter = r"^(5minute-|%s-)" % USER
@catch_exception("Problem getting the list of images.")
def __images(self):
# This is time optimization, it is 5-times faster.
ff = {}
if self.__filter == self.__default_filter:
# Call simple method for create session object
self.nova.api_version.is_null()
ff = {'filters': {'owner': os.environ.get('OS_PROJECT_ID')}}
# Somewhere between novaclient version 6 and
# version 9, images was deprecated and replaced
# with glance. If glance exists, use it.
# Otherwise fall back to the legacy images.
try:
images = self.glance.images.list(**ff)
except AttributeError:
images = self.nova.images.list()
x = PrettyTable(["Name", "ID", "Status"])
x.align["Name"] = "l"
rx = re.compile(self.__filter, re.IGNORECASE)
for img in images:
if rx.search(img.name):
row = [img.name, img.id, img.status]
x.add_row(row)
print((x.get_string(sortby="Name")))
def cmd(self, argv):
self.__filter = self.__default_filter
if len(argv) > 0:
if argv[0] in ('help', '--help', '-h'):
self.help()
return 0
elif argv[0] in ('--all', '-a'):
self.__filter = ""
else:
self.__filter = argv[0]
self.__images()
def help(self):
print("""
Usage: 5minute images [PARAM]
Show the list of accessible images. By default, it shows only 5minute images.
PARAM:
-a, --all show all accessible images
<REGEXP> we can use a regular expression for the result filtering
Examples:
5minute images
5minute images --all
5minute images satellite
5minute images fedora
""")
class FlavorClass(BaseClass):
@catch_exception("Problem getting list of flavors.")
def __flavors(self):
flavors = self.nova.flavors.list()
x = PrettyTable(["Name", "CPU", "RAM", "HDD", "ephemeral", "swap"])
x.align["Name"] = "l"
for flav in flavors:
row = [flav.name, flav.vcpus,
"%s MB" % flav.ram,
"%s GB" % flav.disk,
"%s GB" % flav.ephemeral,
"%s MB" % flav.swap if flav.swap else ""]
x.add_row(row)
print(x)
def cmd(self, argv):
if len(argv) > 0:
if argv[0] in ('help', '--help', '-h'):
self.help()
return 0
self.__flavors()
def help(self):
print("""
Usage: 5minute flavors
Show the list of accessible flavors.
Examples:
5minute flavors
""")
class ServerClass(BaseClass):
private_network_filter = '^default-'
@catch_exception("The instance doesn't exist.", nova_exceptions.NotFound)
@catch_exception("Name of the instance is ambiguous, please use ID.", nova_exceptions.NoUniqueMatch)
def get_instances(self, id):
if re.match(r'^[0-9a-f\-]+$', id) is None:
return self.nova.servers.find(name=id)
else:
return self.nova.servers.get(id)
@catch_exception("The image doesn't exist.", nova_exceptions.NotFound)
@catch_exception("Name of the image is ambiguous, please use ID.", nova_exceptions.NoUniqueMatch)
def get_image(self, id):
return self.nova.glance.find_image(id)
@catch_exception("The volume doesn't exist.", cinder_exceptions.NotFound)
@catch_exception("Name of the volume is ambiguous, please use ID.", cinder_exceptions.NoUniqueMatch)
def get_volume(self, id):
if re.match(r'^[0-9a-f\-]+$', id) is None:
return self.cinder.volumes.find(name=id)
else:
return self.cinder.volumes.get(id)
@catch_exception("The snapshot doesn't exist.")
def get_snapshot(self, id):
if re.match(r'^[0-9a-f\-]+$', id) is None:
return self.cinder.volume_snapshots.find(name=id)
else:
return self.cinder.volume_snapshots.get(id)
@catch_exception("The flavor doesn't exist.", nova_exceptions.NotFound)
@catch_exception("The flavor is ambiguous, please use ID.", nova_exceptions.NoUniqueMatch)
def get_flavor(self, id):
if re.match(r'^[0-9a-f\-]+$', id) is None:
return self.nova.flavors.find(name=id)
else:
return self.nova.flavors.get(id)
@catch_exception("Problem getting list of networks.")
def get_networks(self, filter=None):
def test_net(net, filter):
if filter is None:
return True
for key, val in list(filter.items()):
if isinstance(val, str):
if re.search(val, net.get(key, "")) is None:
return False
elif val != net.get(key):
return False
return True
res = list()
for net in self.neutron.list_networks()['networks']:
if test_net(net, filter) and len(net.get('subnets')) > 0:
res.append(net)
return res
def get_stable_private_network(self):
def get_count_free_ip(cidr, flist):
address_size = 32
ip_pool_mask = int(cidr.split("/")[1])
ip_pool_bit_size = address_size - ip_pool_mask
max_pool_size = 2 ** ip_pool_bit_size - 2
return max_pool_size - len([ip_addr for ip_addr in flist if
ip_addr.get('floating_ip_address') == cidr])
nets = self.get_networks(filter={'name': self.private_network_filter, "router:external": False})
max_network_space = 0
flist = self.neutron.list_floatingips().get('floatingips')
res = list()
for net in nets:
pub_net = self.__get_external_for_private_network(net)
if pub_net:
sub = self.neutron.list_subnets(id=net['subnets'].pop(0))
if len(sub.get('subnets')) > 0:
cidr = sub['subnets'][0]['cidr']
network_free_space = get_count_free_ip(cidr, flist)
if network_free_space > max_network_space:
max_network_space = network_free_space
res = list()
res.append({'private': net, 'free_ip': network_free_space, 'public': pub_net})
elif network_free_space > 0 and network_free_space == max_network_space:
res.append({'private': net, 'free_ip': network_free_space, 'public': pub_net})
return random.choice(res)
def __get_external_for_private_network(self, pnet):
"""
This function returns public network for private network,
if the router is present between these nets.
"""
ports = self.neutron.list_ports(network_id=pnet['id'],
device_owner='network:router_interface_distributed').get('ports')
if len(ports) == 0:
return None
router = self.neutron.show_router(ports.pop(0)['device_id'])
return self.neutron.show_network(router['router']['external_gateway_info']['network_id'])['network']
def cmd(self, argv):
pass
def help(self):
pass
class ListInstancesClass(ServerClass):
"""
This is only view on the ServerClass for getting of list of instances.
"""
def cmd(self, argv):
filter = None
if len(argv) == 0:
filter = "%s-" % USER
else:
if argv[0] in ('help', '--help', '-h'):
self.help()
return 0
elif argv[0] not in ('--all', '-a'):
filter = argv[0]
self.list_instances(filter)
@catch_exception("Problem getting list of instances.")
def list_instances(self, filter):
instances = self.nova.servers.list(search_opts={"name": filter})
x = PrettyTable(["Name", "ID", "Status", "FQDN"])
x.align["Name"] = "l"
x.align["FQDN"] = "l"
for ins in instances:
row = [ins.name, ins.id, ins.status, ins.metadata.get('fqdn', "")]
x.add_row(row)
print((x.get_string(sortby="Name")))
def help(self):
print("""
Usage: 5minute list [PARAM]
Show the list of instances. By default, it shows only your instances.
PARAM:
-a, --all show all accessible instances
<REGEXP> we can use a regular expression the result filtering
Examples:
5minute list
5minute list --all
5minute list satellite
5minute list fedora
""")
class DeleteInstanceClass(ServerClass):
"""
This is only view on the ServerClass for deleting of instance.
"""
def __parse_params(self, opts, argv):
params = {}
for key, val in opts:
if key in ('--help', '-h'):
params['help'] = True
return params
elif key in ('--skip-volume', '-s'):
params['skip-volume'] = True
else:
die("Bad parameter '%s'. Please try 5minute "
"kill --help." % key)
if len(argv) < 1:
die("Missing name or ID of the instance.")
return params
@catch_exception("Bad parameter. Please try 5minute kill help.")
def cmd(self, argv):
opts, argv = \
getopt.gnu_getopt(argv, "hs", ['help', 'skip-volume'])
if 'help' not in argv:
self.params = self.__parse_params(opts, argv)
if 'help' in argv or 'help' in self.params:
self.help()
return 0
for it in argv:
self.kill_instances(it)
@catch_exception("The problem deleting of the instances.")
def kill_instances(self, id):
server = self.get_instances(id)
progress(title="Release floating IP:")
# This is stupid method for checking of lock, if it is activated
k, fips = server.addresses.popitem()
fids = []
for fip in fips:
if (fip.get('OS-EXT-IPS:type') == 'floating'):
idip = self.neutron. \
list_floatingips(floating_ip_address=fip.get('addr')) \
.get('floatingips')[0].get('id')
self.neutron.update_floatingip(idip, {"floatingip": {
'port_id': None}})
fids.append(idip)
progress(result="DONE")
vols = self.nova.volumes.get_server_volumes(server.id)
if len(vols) > 0:
progress(title="Release volumes:")
for vol in vols:
progress()
self.cinder.volumes.get(vol.id).detach()
# self.cinder.volumes.begin_detaching(cvol)
# self.cinder.volumes.detach(cvol)
progress(result="DONE")
progress(title="Delete instance:")
done = False
try:
server.delete()
done = True
while len(self.nova.servers.findall(id=server.id)) > 0:
time.sleep(1)
progress()
progress(result="DONE")
except Exception as e:
if 'locked' in str(e):
progress(result="\x1b[31;01mLOCKED\x1b[39;49;00m")
else:
progress(result="FAIL")
for fi in fids:
if done:
self.neutron.delete_floatingip(fi)
else:
interface = server.interface_list().pop()
if interface:
self.neutron.update_floatingip(fi, {"floatingip": {
'port_id': interface.port_id}})
if 'skip-volume' not in self.params:
for vol in vols:
cvol = self.cinder.volumes.get(vol.id)
if done:
progress(title="Delete volume:")
cvol.delete()
while len(self.cinder.volumes.findall(id=cvol.id)) > 0:
time.sleep(1)
progress()
progress(result="DONE")
else:
self.cinder.volumes.roll_detaching(cvol)
def help(self):
print("""
Usage: 5minute (del|kill|delete) [PARAM] <NAME|ID>
Delete instance.
PARAM:
--skip-volume - skip deleting of the volume
<NAME|ID> Name or ID of instance
Examples:
5minute delete 5minute-RHEL6
5minute kill 5minute-RHEL6
""")
class SnapshotInstanceClass(ServerClass):
"""
This is only view on the ServerClass for snapshot of instance.
"""
def __parse_params(self, opts, argv):
params = {}
params['metadata'] = None
for key, val in opts:
if key in ('--help', '-h'):
params['help'] = True
return params
elif key in ('--name', '-n'):
params['name'] = "%s" % val
elif key in ('--metadata', '-m'):
if params['metadata'] is None:
params['metadata'] = {}
try:
for it in val.split(';'):
col, val = it.split('=')
params['metadata'][col] = val.replace(',', ' ')
except Exception:
die("The problem with parsing of metadata parameter. "
"Please try 5minute snapshot --help.")
elif key in ('--umount', '-u'):
params['umount'] = True
elif key in ('--volume'):
params['volume'] = True
elif key in ('--shutdown', '-s'):
params['shutdown'] = True
elif key in ('--delete'):
params['delete'] = True
else:
die("Bad parameter '%s'. Please try 5minute "
"snapshot --help." % key)
if 'delete' in params:
if len(argv) != 1:
die("Name of the snapshot is ambiguous or empty.")
params['snapshot'] = self.get_image(argv.pop(0))
else:
if len(argv) != 1:
die("Name of the instance is ambiguous or empty.")
params['instance'] = self.get_instances(argv.pop(0))
return params
@catch_exception("Bad parameter. Please try 5minute snapshot help.")
def cmd(self, argv):
opts, argv = \
getopt.gnu_getopt(argv, "husn:m:",
['help', 'volume', 'umount', 'name=', 'metadata=',
'shutdown', 'delete'])
if 'help' not in argv:
self.params = self.__parse_params(opts, argv)
if 'help' in argv or 'help' in self.params:
self.help()
return 0
if self.params.get('delete'):
self.delete_snapshot()
else:
self.shapshot_instance()
def delete_snapshot(self):
snapshot = self.params.get("snapshot")
svols = snapshot.to_dict().get('volumes', "").split()
progress(title="Delete snapshot:")
self.glance.images.delete(snapshot.id)
try:
while self.nova.glance.find_image(snapshot.id):
time.sleep(1)
progress()
except Exception:
pass
progress(result="DONE")
if self.params.get("volume"):
for it in svols:
try:
progress(title="Delete volume snapshot:")
svol = self.get_snapshot(it)
svol.delete()
while len(self.nova
.volume_snapshots.findall(id=svol.id)) > 0:
time.sleep(1)
progress()
progress(result="DONE")
except Exception:
progress(result="FAIL")
def shapshot_instance(self):
server = self.params.get("instance")
vols = None
if self.params.get('umount') is not None:
vols = self.nova.volumes.get_server_volumes(server.id)
if len(vols) > 0:
progress(title="Release volumes:")
for vol in vols:
progress()
self.cinder.volumes.get(vol.id).detach()
# self.cinder.volumes.begin_detaching(cvol)
# self.cinder.volumes.detach(cvol)
progress(result="DONE")
if self.params.get('shutdown') is not None:
progress(title="Shut down the instance:")
if server.status != 'SHUTOFF':
server.stop()
status = server.status
while status != 'SHUTOFF':
time.sleep(1)
progress()
status = self.nova.servers.get(server.id).status
progress(result="DONE")
name = self.params.get('name', "%s_%s" % (
server.name,
datetime.now().strftime("%Y-%m-%d_%X")))
if self.params.get('volume') is not None and vols is not None:
progress(title="Snapshotting the volume:")
for vol in vols:
progress()
snap = self.cinder.volume_snapshots.create(vol.id,
display_name=name)
while snap.status in ['creating', ]:
time.sleep(1)
progress()
snap = self.cinder.volume_snapshots.get(snap.id)
if snap.status == 'available':
progress(result="DONE")
progress(title="Vol. snapshot ID:")
progress(result=snap.id)
self.params['metadata']['volumes'] = snap.id
else:
progress(result="FAIL")
progress(title="Create snapshot:")
image_id = server.create_image(name, self.params.get('metadata'))
status = self.nova.glance.find_image(image_id).status.upper()
while status in ['SAVING', 'QUEUED']:
time.sleep(1)
progress()
status = self.nova.glance.find_image(image_id).status.upper()
if status == 'ACTIVE':
progress(result="DONE")
progress(title="Snapshot ID:")
progress(result=image_id)
progress(title="Snapshot Name:")
progress(result=self.nova.glance.find_image(image_id).name)
else:
progress(result="FAIL")
def help(self):
print("""
Usage: 5minute snapshot [PARAM] <NAME|ID>
Create or delete snapshot of the instance.
PARAM:
-n, --name name of the snapshot
--delete delete snapshot (with / without snapshot of the volume)
-u, --umount umount all volumes
--volume create/delete a snapshot of the volume and assign it to the snapshot of the instance
-s, --shutdown shutdown the instance before snapshot
-m, --metadata metadata for image, pair key=val separated by semicolon
<NAME|ID> Name or ID of instance / snapshot (deleting)
Examples:
5minute snapshot user-5minute-RHEL6
5minute snapshot --delete --volume 5minute-RHEL6_20170520
If you want to create new 5minute image (universal template), please
clean the instance.
Ex. for RHEL6:
rm -rf /etc/ssh/ssh_host_*
rm -rf /etc/sysconfig/rhn/systemid
subscription-manager unregister
sed -i '/HWADDR=*/d' /etc/sysconfig/network-scripts/ifcfg-*
sed -i -e '/net/d' -e '/virtio-pci)/d' /etc/udev/rules.d/70-persistent-net.rules
[ -e /etc/redhat-ddns/hosts ] && echo "" > /etc/redhat-ddns/hosts
echo "" > ~/.bash_history
echo "" > /etc/motd
""")
class BootInstanceClass(ServerClass):
"""
This is only view on the ServerClass for booting of instance.
"""
ufile = ""
default_flavor = "m1.medium"
variables = None
created_volume = False
cinit_ending_text = "===============_CLOUD_INIT_FINISHED_==============="
check_console_exit_re = r".*login:\s*$"
output_cache = []
output_compare_lines = 5
output_len = 0
def __parse_params(self, opts, argv):
params = {}
for key, val in opts:
if key in ('--help', '-h') or 'help' in argv:
params['help'] = True
return params
elif key in ('--flavor', '-f'):
params['flavor'] = val
elif key in ('--console', '-c'):
params['console'] = True
elif key in ('--name', '-n'):
params['name'] = val
elif key in ('--volume', '-v'):
params['volume'] = val
elif key in ('--profile', '-p'):
params['profile'] = val
elif key == '--novolume':
params['novolume'] = True
elif key == '--noip':
params['noip'] = True
elif key == '--userdata':
params['userdata'] = val
else:
die("Bad parameter '%s'. Please try 5minute boot --help." % key)