-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy path__init__.py
More file actions
1897 lines (1555 loc) · 47.1 KB
/
__init__.py
File metadata and controls
1897 lines (1555 loc) · 47.1 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@
# Copyright (c) 2006 - 2019 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
#
# @rocks@
# Copyright (c) 2000 - 2010 The Regents of the University of California
# All rights reserved. Rocks(r) v5.4 www.rocksclusters.org
# https://github.com/Teradata/stacki/blob/master/LICENSE-ROCKS.txt
# @rocks@
import atexit
import fnmatch
import hashlib
import json
import marshal
import os
import pwd
import pymysql
import re
import socket
import string
import subprocess
import sys
import syslog
import threading
import time
from collections import namedtuple
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack
from itertools import groupby, cycle
from operator import itemgetter
from xml.sax import SAXParseException
from xml.sax import handler
from xml.sax import make_parser
import stack.graph
import stack
from stack.exception import CommandError, ParamRequired
from stack.bool import str2bool, bool2str
from stack.util import flatten
import stack.util
_logPrefix = ''
_debug = False
def Log(message, level=syslog.LOG_INFO):
"""
Send a message to syslog
"""
syslog.syslog(level, '%s%s' % (_logPrefix, message))
def Warn(message):
"""
Send a warning to syslog
"""
syslog.syslog(syslog.LOG_WARNING, f'{_logPrefix}{message}')
def Debug(message, level=syslog.LOG_DEBUG):
"""
If the environment variable STACKDEBUG is set,
send a message to syslog and stderr.
"""
if _debug:
m = ''
p = ''
for c in message.strip():
if c in string.whitespace and p in string.whitespace:
pass
else:
if c == '\n':
m += ' '
else:
m += c
p = c
Log(message, level)
sys.__stderr__.write('%s\n' % m)
class DocStringHandler(handler.ContentHandler,
handler.DTDHandler,
handler.EntityResolver,
handler.ErrorHandler):
def __init__(self, name='', users=[]):
handler.ContentHandler.__init__(self)
self.text = ''
self.name = name
self.users = users
self.section = {}
self.section['description'] = ''
self.section['optarg'] = []
self.section['reqarg'] = []
self.section['optparam'] = []
self.section['reqparam'] = []
self.section['example'] = []
self.section['related'] = []
self.parser = make_parser()
self.parser.setContentHandler(self)
def getDocbookText(self):
raise CommandError(self, '"docbook" no longer supported - use "markdown"')
def getUsageText(self, colors=None):
if colors:
bold = colors['bold']['code']
unbold = colors['reset']['code']
else:
bold = ''
unbold = ''
s = ''
for (name, type, rep, txt) in self.section['reqarg']:
if rep:
dots = ' ...'
else:
dots = ''
s += '{%s%s%s%s} ' % (bold, name, unbold, dots)
for (name, type, rep, txt) in self.section['optarg']:
if rep:
dots = ' ...'
else:
dots = ''
s += '[%s%s%s%s] ' % (bold, name, unbold, dots)
for (name, type, rep, txt) in self.section['reqparam']:
if rep:
dots = ' ...'
else:
dots = ''
s += '{%s%s%s=%s%s} ' % (bold, name, unbold, type, dots)
for (name, type, rep, txt) in self.section['optparam']:
if rep:
dots = ' ...'
else:
dots = ''
s += '[%s%s%s=%s%s] ' % (bold, name, unbold, type, dots)
if s and s[-1] == ' ':
return s[:-1]
else:
return s
def getPlainText(self, colors=None):
if 'root' in self.users:
prompt = '#'
else:
prompt = '$'
if colors:
bold = colors['bold']['code']
unbold = colors['reset']['code']
else:
bold = ''
unbold = ''
s = ''
s += 'stack %s %s' % (self.name, self.getUsageText(colors))
s += '\n\n%sDescription%s\n' % (bold, unbold)
s += self.section['description']
if self.section['reqarg'] or self.section['optarg']:
s += '\n%sArguments%s\n\n' % (bold, unbold)
for (name, type, rep, txt) in self.section['reqarg']:
if rep:
dots = ' ...'
else:
dots = ''
s += '\t{%s%s%s%s}\n%s\n' % (bold, name, unbold, dots, txt)
for (name, type, rep, txt) in self.section['optarg']:
if rep:
dots = ' ...'
else:
dots = ''
s += '\t[%s%s%s%s]\n%s\n' % (bold, name, unbold, dots, txt)
if self.section['reqparam'] or self.section['optparam']:
s += '\n%sParameters%s\n\n' % (bold, unbold)
for (name, type, rep, txt) in self.section['reqparam']:
if rep:
dots = ' ...'
else:
dots = ''
s += '\t{%s%s%s=%s%s}\n%s\n' % (bold, name, unbold, type, dots, txt)
for (name, type, rep, txt) in self.section['optparam']:
if rep:
dots = ' ...'
else:
dots = ''
s += '\t[%s%s%s=%s%s]\n%s\n' % (bold, name, unbold, type, dots, txt)
if self.section['example']:
s += '\n%sExamples%s\n\n' % (bold, unbold)
for (cmd, txt) in self.section['example']:
s += '\t%s stack %s\n' % (prompt, cmd)
s += '%s\n' % txt
if self.section['related']:
s += '\n%sRelated Commands%s\n\n' % (bold, unbold)
for related in self.section['related']:
s += '\tstack %s\n' % related
return s
def getParsedText(self):
return '%s' % self.section
def getMarkDown(self):
s = '## %s\n\n' % self.name
s = s + '### Usage\n\n'
cmd = "stack %s %s" % (self.name, self.getUsageText().strip())
s = s + '`%s`\n\n' % cmd.strip()
if self.section['description']:
s = s + '### Description\n\n'
m = self.section['description'].split('\n')
desc = '\n'.join(m)
s = s + desc + '\n\n'
if self.section['reqarg'] or self.section['optarg']:
s = s + '### Arguments\n\n'
for (name, type, rep, txt) in self.section['reqarg']:
s += '* `[%s]`\n' % name
for (name, type, rep, txt) in self.section['optarg']:
s += '* `{%s}`\n' % name
s += '\n %s\n\n' % txt.strip()
s = s + '\n'
if self.section['reqparam'] or self.section['optparam']:
s = s + '### Parameters\n'
for (name, type, rep, txt) in self.section['reqparam']:
s += '* `[%s=%s]`\n' % (name, type)
for (name, type, rep, txt) in self.section['optparam']:
s += '* `{%s=%s}`\n' % (name, type)
s += '\n %s\n' % txt.strip()
s = s + '\n'
if 'example' in self.section and self.section['example']:
s = s + '### Examples\n\n'
for (cmd, txt) in self.section['example']:
s += '* `stack %s`\n' % cmd.strip()
if txt:
s += '\n %s\n' % txt.strip()
s += '\n'
s = s + '\n'
if 'related' in self.section and self.section['related']:
s = s + '### Related\n'
for related in self.section['related']:
r = '-'.join(related.split()).strip()
s += '[%s](%s)\n\n' % (related, r)
s = s + '\n'
return s
def startElement(self, name, attrs):
if not self.section['description']:
self.section['description'] = self.text
self.key = None
self.text = ''
if name in ['arg', 'param']:
type = attrs.get('type')
if not type:
type = 'string'
try:
optional = int(attrs.get('optional'))
except:
if name == 'arg':
optional = 0
if name == 'param':
optional = 1
try:
repeat = int(attrs.get('repeat'))
except:
repeat = 0
name = attrs.get('name')
self.key = (name, type, optional, repeat)
elif name == 'example':
self.key = attrs.get('cmd')
def endElement(self, tag):
if tag == 'docstring':
# we are done so sort the param and related lists
self.section['reqparam'].sort()
self.section['optparam'].sort()
self.section['related'].sort()
elif tag == 'arg':
name, type, optional, repeat = self.key
if optional:
self.section['optarg'].append((name, type, repeat, self.text))
else:
self.section['reqarg'].append((name, type, repeat, self.text))
elif tag == 'param':
name, type, optional, repeat = self.key
if optional:
self.section['optparam'].append((name, type, repeat, self.text))
else:
self.section['reqparam'].append((name, type, repeat, self.text))
elif tag == 'example':
self.section['example'].append((self.key, self.text))
else:
if tag in self.section:
self.section[tag].append(self.text)
def characters(self, s):
self.text += s
def get_mysql_connection(user=None, password=None):
"""
Creates a connection to MySQL and returns it, or returns None if
it can't connect. The caller must call `close` on the connection.
"""
connection = None
try:
if user is None:
# Root connects as 'apache', everyone else as the user
# running the python command.
if os.geteuid() == 0:
user = 'apache'
else:
user = pwd.getpwuid(os.geteuid())[0]
if password is None:
# Try to read the apache user's password
password = ''
try:
with open('/etc/apache.my.cnf') as f:
for line in f:
if line.startswith('password'):
password = line.split('=')[1].strip()
break
except:
# Couldn't read the password, try connecting without one
pass
if os.path.exists('/var/run/mysql/mysql.sock'):
connection = pymysql.connect(
db='cluster',
user=user,
passwd=password,
host='localhost',
unix_socket='/var/run/mysql/mysql.sock',
autocommit=True
)
else:
connection = pymysql.connect(
db='cluster',
user=user,
passwd=password,
host='localhost',
port=40000,
autocommit=True
)
except pymysql.OperationalError:
# No database
pass
return connection
class DatabaseConnection:
"""
Wrapper class for all database access. The methods are based on
those provided from the pymysql library and some other Stack
specific methods are added. All StackCommands own an instance of
this object (self.db).
"""
cache = {}
_lookup_hostname_cache = {}
def _lookup_hostname(self, hostname):
"""
Looks up a hostname in a case-insenstive manner to get how it is
formarted in the DB, allowing MySQL LIKE patterns, and using the
DatabaseConnection cache when possible.
Returns None when the hostname doesn't exist.
"""
# See if we need to do MySQL LIKE
if '%' in hostname or '_' in hostname:
rows = self.select('name FROM nodes WHERE name LIKE %s', (hostname,))
if rows:
return rows[0][0]
elif not self.caching:
# If we aren't caching, just do a straight lookup
rows = self.select('name FROM nodes WHERE name = %s', (hostname,))
if rows:
return rows[0][0]
else:
# Build the cache if needed
if not DatabaseConnection._lookup_hostname_cache:
DatabaseConnection._lookup_hostname_cache = {
name.lower(): name
for name in flatten(self.select('name FROM nodes'))
}
# Return the hostname if it was in the database
if hostname.lower() in DatabaseConnection._lookup_hostname_cache:
return DatabaseConnection._lookup_hostname_cache[hostname.lower()]
# No match
return None
def __init__(self, database, *, caching=True):
# self.database : object returned from orginal connect call
# self.link : database cursor used by everyone else
if database:
self.database = database
self.name = database.db.decode() # name of the database
self.link = database.cursor()
else:
self.database = None
self.name = None
self.link = None
# Setup the global cache, new DatabaseConnections will all use
# this cache. The envinorment variable STACKCACHE can be used
# to override the optional CACHING arg.
#
# Note the cache is shared but the decision to cache is not.
#
# Each database has a unique cache, this way table names don't
# need to be unique. Currently we use only one connection, but
# that may change (thought about it for the shadow database)
# hence the code.
if self.name not in DatabaseConnection.cache:
DatabaseConnection.cache[self.name] = {}
if os.environ.get('STACKCACHE'):
self.caching = str2bool(os.environ.get('STACKCACHE'))
else:
self.caching = caching
def enableCache(self):
self.caching = True
def disableCache(self):
self.caching = False
self.clearCache()
def clearCache(self):
Debug('clearing cache of %d selects' % len(DatabaseConnection.cache[self.name]))
DatabaseConnection.cache[self.name] = {}
DatabaseConnection._lookup_hostname_cache = {}
def count(self, command, args=None ):
"""
Return a count of the number of matching items in the database.
The command query should start with the column in parentheses you
wish to count.
The return value will either be an int or None if something
unexpected happened.
Example: count('(ID) from subnets where name=%s', (name,))
"""
# Run our select count
rows = self.select(f'count{command.strip()}', args)
# We should always get a single row back
if len(rows) != 1:
return None
return rows[0][0]
def select(self, command, args=None, prepend_select=True):
if not self.link:
return []
rows = []
m = hashlib.md5()
m.update(command.strip().encode('utf-8'))
if args:
m.update(' '.join(str(arg) for arg in args).encode('utf-8'))
k = m.hexdigest()
if k in DatabaseConnection.cache[self.name]:
Debug('select %s' % k)
rows = DatabaseConnection.cache[self.name][k]
else:
if prepend_select:
command = f'select {command}'
try:
self.execute(command, args)
rows = self.fetchall()
except pymysql.OperationalError:
Debug('SQL ERROR: %s' % self.link.mogrify(command, args))
# Permission error return the empty set
# Syntax errors throw exceptions
rows = []
if self.caching:
DatabaseConnection.cache[self.name][k] = rows
return rows
def execute(self, command, args=None, many=False):
"""Executes the provided SQL command with the provided args.
If many is True, this will use executemany instead of execute to perform the command.
"""
command = command.strip()
if not command.lower().startswith('select'):
self.clearCache()
if self.link:
# pick the executor to use
if many:
executor = self.link.executemany
else:
executor = self.link.execute
try:
t0 = time.time()
result = executor(command, args)
t1 = time.time()
except pymysql.ProgrammingError:
# mogrify doesn't understand the executemany args, so we have to do some more work.
if many:
error = '\n'.join((self.link.mogrify(command, arg) for arg in args))
Debug(f'SQL ERROR: {error}')
else:
Debug(f'SQL ERROR: {self.link.mogrify(command, args)}')
raise pymysql.ProgrammingError
# Only spend cycles on mogrify if we are in debug mode
if stack.commands._debug:
# mogrify doesn't understand the executemany args, so we have to do some more work.
if many:
commands = '\n'.join((self.link.mogrify(command, arg) for arg in args))
Debug('SQL EX: %.4d rows in %.3fs <- %s' % (result, (t1 - t0), commands))
else:
Debug('SQL EX: %.4d rows in %.3fs <- %s' % (result, (t1 - t0), self.link.mogrify(command, args)))
return result
return None
def fetchone(self):
if self.link:
row = self.link.fetchone()
# Debug('SQL F1: %s' % row.__repr__())
return row
return None
def fetchall(self):
if self.link:
rows = self.link.fetchall()
# for row in rows:
# Debug('SQL F*: %s' % row.__repr__())
return rows
return None
def getHostOS(self, host):
"""
Return the OS name for the given host.
"""
for (name, osname) in self.select("""
n.name, o.name from boxes b, nodes n, oses o
where n.box=b.id and b.os=o.id
"""):
if name == host:
return osname
return None
def getHostAppliance(self, host):
"""
Returns the appliance for a given host.
"""
for (name, appliance) in self.select("""
n.name, a.name from nodes n, appliances a
where n.appliance=a.id
"""):
if name == host:
return appliance
return None
def getHostEnvironment(self, host):
"""
Returns the environment for a given host.
"""
for (name, environment) in self.select("""
n.name, e.name from nodes n, environments e
where n.environment=e.id
"""):
if name == host:
return environment
return None
def getHostBox(self, host):
"""
Returns the box for a given host.
"""
host = self.getHostname(host)
result = self.select("""boxes.name
FROM boxes, nodes
WHERE boxes.id=nodes.box
AND nodes.name=%s
""",
host)
if not result:
return None
return result[0][0]
def getNodeName(self, hostname, subnet=None):
if not subnet:
lookup = self._lookup_hostname(hostname)
if lookup:
hostname = lookup
return hostname
result = None
for (netname, zone) in self.select("""
net.name, s.zone from nodes n, networks net, subnets s
where n.name like %s and s.name like %s
and net.node = n.id and net.subnet = s.id
""", (hostname, subnet)):
# If interface exists, but name is not set
# infer name from nodes table, and append
# dns zone
if not netname:
netname = hostname
if zone:
result = '%s.%s' % (netname, zone)
else:
result = netname
return result
def getHostname(self, hostname=None, subnet=None):
"""
Returns the name of the given host as referred to in
the database. This is used to normalize a hostname before
using it for any database queries.
"""
# Look for the hostname in the database before trying to reverse
# lookup the IP address and map that to the name in the nodes
# table. This should speed up the installer w/ the restore pallet.
if hostname and self.link:
if self._lookup_hostname(hostname):
return self.getNodeName(hostname, subnet)
if not hostname:
hostname = socket.gethostname()
if hostname == 'localhost':
if self.link:
return ''
else:
return 'localhost'
try:
# Do a reverse lookup to get the IP address. Then do a
# forward lookup to verify the IP address is in DNS. This is
# done to catch evil DNS servers (timewarner) that have a
# catchall address. We've had several users complain about
# this one. Had to be at home to see it.
#
# If the resolved address is the same as the hostname then
# this function was called with an ip address, so we don't
# need the reverse lookup.
#
# For truly evil DNS (OpenDNS) that have catchall servers
# that are in DNS we make sure the hostname matches the
# primary or alias of the forward lookup Throw an Except, if
# the forward failed an exception was already thrown.
addr = socket.gethostbyname(hostname)
if not addr == hostname:
(name, aliases, addrs) = socket.gethostbyaddr(addr)
if hostname != name and hostname not in aliases:
raise NameError
except:
if hostname == 'localhost':
addr = '127.0.0.1'
else:
addr = None
if not addr:
if self.link:
if self._lookup_hostname(hostname):
return self.getNodeName(hostname, subnet)
# See if this is a MAC address
self.link.execute("""
select nodes.name from networks,nodes
where nodes.id=networks.node and networks.mac=%s
""", (hostname,))
try:
hostname, = self.link.fetchone()
return self.getNodeName(hostname, subnet)
except:
pass
# See if this is a FQDN. If it is FQDN,
# break it into name and domain.
n = hostname.split('.')
if len(n) > 1:
name = n[0]
domain = '.'.join(n[1:])
self.link.execute("""
select n.name from nodes n, networks nt, subnets s
where nt.subnet=s.id and nt.node=n.id
and s.zone=%s and (nt.name=%s or n.name=%s)
""", (domain, name, name))
try:
hostname, = self.link.fetchone()
return self.getNodeName(hostname, subnet)
except:
pass
# Check if the hostname is a basename and the FQDN is
# in /etc/hosts but not actually registered with DNS.
# To do this we need lookup the DNS search domains and
# then do a lookup in each domain. The DNS lookup will
# fail (already has) but we might find an entry in the
# /etc/hosts file.
#
# All this to handle the case when the user lies and gives
# a FQDN that does not really exist. Still a common case.
try:
with open('/etc/resolv.conf', 'r') as f:
domains = []
for line in f.readlines():
tokens = line[:-1].split()
if len(tokens) == 0:
continue
if tokens[0] == 'search':
domains = tokens[1:]
for domain in domains:
try:
name = '%s.%s' % (hostname, domain)
addr = socket.gethostbyname(name)
if addr:
return self.getHostname(name)
except:
pass
except (OSError, IOError):
pass
# HostArgProcessor has changed handling of
# appliances (and others) as hostnames. So do some work
# here to point the user to the new syntax.
message = None
if self.count('(id) from appliances where name=%s', (hostname,)):
message = f'use "a:{hostname}" for {hostname} appliances'
elif self.count('(id) from environments where name=%s', (hostname,)):
message = f'use "e:{hostname}" for hosts in the {hostname} environment'
elif self.count('(id) from oses where name=%s', (hostname,)):
message = f'use "o:{hostname}" for {hostname} hosts'
elif self.count('(id) from boxes where name=%s', (hostname,)):
message = f'use "b:{hostname}" for hosts using the {hostname} box'
elif self.count('(id) from groups where name=%s', (hostname,)):
message = f'use "g:{hostname}" for host in the {hostname} group'
elif hostname.find('rack') == 0:
message = f'use "r:{hostname}" for hosts in {hostname}'
if message:
raise CommandError(self, message)
raise CommandError(self, f'cannot resolve host "{hostname}"')
if addr == '127.0.0.1': # allow localhost to be valid
if self.link:
return self.getHostname(subnet=subnet)
else:
return 'localhost'
if self.link:
# Look up the IP address in the networks table to find the
# hostname (nodes table) of the node.
#
# If the IP address is not found also see if the hostname is
# in the networks table. This last check handles the case
# where DNS is correct but the IP address used is different.
rows = self.link.execute("""
select nodes.name from networks,nodes
where nodes.id=networks.node and ip=%s
""", (addr,))
if not rows:
rows = self.link.execute("""
select nodes.name from networks,nodes
where nodes.id=networks.node and networks.name=%s
""", (hostname,))
if not rows:
raise CommandError(self, f'host "{hostname}" is not in cluster')
hostname, = self.link.fetchone()
return self.getNodeName(hostname, subnet)
class Command:
"""
Base class for all Stack commands the general command line
form is as follows:
stack ACTION COMPONENT OBJECT [ <ARGNAME ARGS> ... ]
ACTION(s):
add
create
list
load
sync
"""
MustBeRoot = 1
def __init__(self, database, *, debug=None):
"""
Creates a DatabaseConnection for the StackCommand to use.
This is called for all commands, including those that do not
require a database connection.
"""
if debug is not None:
stack.commands._debug = debug
# create a contextmanager to which commands can append cleanup jobs
# add its closing to run atexit, so we know it will run
# There is another ExitStack in stack.py which closes the database!
# that means anything in self.deferred can make db calls since the
# db is not yet closed
self.deferred = ExitStack()
atexit.register(self.deferred.close)
self.db = DatabaseConnection(database)
self.text = []
self.bytes = []
self._exec = stack.util._exec
self.output = []
self.arch = os.uname()[4]
if self.arch in ['i386', 'i486', 'i586', 'i686']:
self.arch = 'i386'
elif self.arch in ['armv7l']:
self.arch = 'armv7hl'
if os.path.exists('/etc/centos-release') or os.path.exists('/etc/redhat-release'):
self.os = 'redhat'
elif os.path.exists('/etc/SuSE-release') or os.path.exists('/etc/SUSE-brand'):
self.os = 'sles'
else:
self.os = os.uname()[0].lower()
if self.os == 'linux':
self.os = 'UNKNOWN_LINUX_DISTRO'
self._args = None
self._params = None
self.rc = None # return code
self.level = 0
# List of loaded implementations.
self.impl_list = {}
# Figure out the width of the terminal
self.width = 0
if sys.stdout.isatty():
try:
c, r = os.get_terminal_size()
self.width = int(c)
except:
pass
# Look up terminal colors safely using tput, uncolored if this fails.
self.colors = {
'bold': { 'tput': 'bold', 'code': '' },
'reset': { 'tput': 'sgr0', 'code': '' },
'beginline': { 'tput': 'smul', 'code': ''},
'endline': { 'tput': 'rmul', 'code': ''}
}
if sys.stdout.isatty() and False:
# TODO(p3) - figure out why we aren't capturing the tput code
# correctly. We get data but not the full escape seq
for key in self.colors.keys():
c = 'tput %s' % self.colors[key]['tput']
try:
p = subprocess.Popen(c.split(), stdout=subprocess.PIPE)
except:
continue
(o, e) = p.communicate()
if p.returncode == 0:
self.colors[key]['code'] = o
def fillParams(self, names, params=None):
"""
Returns a list of variables with either default values of the
values in the PARAMS dictionary.
NAMES - list of (KEY, DEFAULT) tuples.
KEY - key name of PARAMS dictionary
DEFAULT - default value if key in not in dict
PARAMS - optional dictionary
REQUIRED - optional boolean (True means param is required)
For example:
(svc, comp) = self.fillParams(
('service', None),
('component', None))
Can also be written as:
(svc, comp) = self.fillParams(('service',), ('component', ))
"""
# make sure names is a list or tuple
if not type(names) in [type([]), type(())]:
names = [names]
# for each element in the names list make sure it is also
# a tuple. If the second element (default value) is missing
# use None. If the third element is missing assume the
# parameter is not required.
pdlist = []
for e in names:
if type(e) in [type([]), type(())]:
if len(e) == 3:
tuple = ( e[0], e[1], e[2] )
elif len(e) == 2:
tuple = ( e[0], e[1], False )
elif len(e) == 1:
tuple = ( e[0], None, False )
else:
assert len(e) in [1, 2, 3]
else:
tuple = ( e[0], None, False )
pdlist.append(tuple)
if not params:
params = self._params
list = []
for (key, default, required) in pdlist:
if key in params:
list.append(params[key])
else: