forked from rocksclusters/base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
2040 lines (1788 loc) · 55.9 KB
/
__init__.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
#!/opt/rocks/bin/python
#
# @Copyright@
#
# Rocks(r)
# www.rocksclusters.org
# version 6.2 (SideWinder)
#
# Copyright (c) 2000 - 2014 The Regents of the University of California.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice unmodified and in its entirety, this list of conditions and the
# following disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# 3. All advertising and press materials, printed or electronic, mentioning
# features or use of this software must display the following acknowledgement:
#
# "This product includes software developed by the Rocks(r)
# Cluster Group at the San Diego Supercomputer Center at the
# University of California, San Diego and its contributors."
#
# 4. Except as permitted for the purposes of acknowledgment in paragraph 3,
# neither the name or logo of this software nor the names of its
# authors may be used to endorse or promote products derived from this
# software without specific prior written permission. The name of the
# software includes the following terms, and any derivatives thereof:
# "Rocks", "Rocks Clusters", and "Avalanche Installer". For licensing of
# the associated name, interested parties should contact Technology
# Transfer & Intellectual Property Services, University of California,
# San Diego, 9500 Gilman Drive, Mail Code 0910, La Jolla, CA 92093-0910,
# Ph: (858) 534-5815, FAX: (858) 534-7345, E-MAIL:invent@ucsd.edu
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# @Copyright@
#
# $Log: __init__.py,v $
# Revision 1.109 2013/01/15 00:44:27 clem
# fix for when /etc/resolve.conf has some empty lines
#
# Revision 1.108 2012/11/27 00:48:09 phil
# Copyright Storm for Emerald Boa
#
# Revision 1.107 2012/09/18 23:35:58 phil
# more inclusive pattern match
#
# Revision 1.106 2012/08/21 19:42:21 phil
# re-implementation of previous fix to force
# flag="values possibly with spaces" pattern match. No spaces to first equal.
# flag (parameters) names can have letters and numbers only.
#
# Revision 1.105 2012/08/14 04:51:45 phil
# Generate ssh_known_hosts file.
# Works when hosts are multi-homed (like Triton)
#
# Revision 1.104 2012/07/31 23:20:10 phil
# Generate a cluster-wide ssh [rsa,dsa] keys and put them in
# the secure attributes database. These are different from frontend's host keys.
# Place these on nodes with rocks sync host sec_attr (new sec_attr plugins).
# Add list global sec_attr command
#
# Revision 1.103 2012/07/31 00:13:11 clem
# arguments are parsed correctly now
#
# Now it checks that when we have:
# nameagr=valuearg
# namearg must be only one word
#
# Revision 1.102 2012/05/06 05:48:18 phil
# Copyright Storm for Mamba
#
# Revision 1.101 2012/05/05 16:38:27 phil
# When printing a python dictionary, suppress newline
#
# Revision 1.100 2012/03/13 18:41:43 phil
# Back-out previous change. Bad idea. Or worse -- breaks things.
#
# Revision 1.99 2012/03/13 06:09:02 phil
# Be more tolerant -- or don't emit errors in particular benign cases
#
# Revision 1.98 2011/11/02 21:10:54 phil
# Some tweaks and updates to bootstrap0 so that bootstrap works properly
#
# Revision 1.97 2011/07/23 02:30:24 phil
# Viper Copyright
#
# Revision 1.96 2011/06/03 02:34:39 anoop
# Added code for secure_attributes
#
# Revision 1.95 2011/05/28 06:39:50 phil
# properly handle the wildcarded index.
#
# Revision 1.94 2011/05/28 05:34:53 phil
# allow wildcards for categories so that rocks list firewall appliance
# gives the rules for all indices at the appliance level
#
# Revision 1.93 2011/05/27 19:06:47 phil
# First edition of new firewall add rule.
# Still needs error handling/checking.
#
# Revision 1.92 2011/05/10 05:12:46 anoop
# Move shadow attributes out of attributes tables.
# Seperate secure attributes table for all attributes
# that we want to hide. These attributes will never
# be passed through kickstart.
#
# Revision 1.91 2011/04/14 23:04:50 anoop
# Add appliance and membership as internal attributes
#
# Revision 1.90 2011/02/11 16:48:37 mjk
# getHostname changes
# - Bug Fix: Can now use IP addresses as hostnames again. The code to handle
# bad DNS servers broke this (been broken for a few releases).
# - Enhancement: Handles the case of hostnames that are not in local DNS, or
# real DNS, but are in the /etc/hosts file.
#
# Revision 1.2 2010/12/08 00:13:14 bruno
# get the right commands
#
# Revision 1.89 2010/10/20 21:30:46 mjk
# - fix typos
# - added rocks-channel and librocks packages
# - librocks must be built/installed before channel
#
# Revision 1.88 2010/10/13 23:18:05 bruno
# if an attribute doesn't exist (that is, its value is None), then just
# return 0 from str2bool
#
# Revision 1.87 2010/10/12 17:14:11 mjk
# add precedes method for plugins
#
# Revision 1.86 2010/09/07 23:52:49 bruno
# star power for gb
#
# Revision 1.85 2010/07/31 01:02:02 bruno
# first stab at putting in 'shadow' values in the database that non-root
# and non-apache users can't read
#
# Revision 1.84 2010/06/30 17:37:32 anoop
# Overhaul of the naming system. We now support
# 1. Multiple zone/domains
# 2. Serving DNS for multiple domains
# 3. No FQDN support for network names
# - FQDN must be split into name & domain.
# - Each piece information will go to a
# different table
# Hopefully, I've covered the basics, and not broken
# anything major
#
# Revision 1.83 2010/05/27 00:11:32 bruno
# firewall fixes
#
# Revision 1.82 2010/05/20 00:31:44 bruno
# gonna get some serious 'star power' off this commit.
#
# put in code to dynamically configure the static-routes file based on
# networks (no longer the hardcoded 'eth0').
#
# Revision 1.81 2010/05/07 23:13:31 bruno
# clean up the help info for the firewall commands
#
# Revision 1.80 2010/04/30 22:02:46 bruno
# added getNetworkName() method. it is used by the firewall commands
#
# Revision 1.79 2010/02/22 23:11:03 mjk
# - rocks iterface host using os.system not popen
# - can now be used like cluster-fork
# - rocks host iterate compute | ssh -f % cmd
# - getHostname() now handles another f'd up case where DNS is correct (fw/bw)
# but the IP address is completely different. This happens when the public
# name maps to a private address behind some insane firewall.
#
# Revision 1.78 2010/01/13 23:01:13 bruno
# fix for '%' wildcard. thanks to Tom Rockwell for the fix.
#
# Revision 1.77 2009/11/12 06:16:10 mjk
# dns owes me 2 days
#
# Revision 1.76 2009/11/11 19:54:56 mjk
# - Adding the "rocks list host yahoo.com" bug back in
# - The fix broke frontend installs when name not in DNS
# - Need to rethink this one
#
# Revision 1.75 2009/09/17 22:33:29 mjk
# fix bug fix
#
# Revision 1.74 2009/09/17 22:31:08 mjk
# Abort when trying to process a valid hostname that is not part
# of the cluster (e.g. "rocks list host yahoo.com")
# Bug reported by Daniel Hansen
#
# Revision 1.73 2009/09/03 05:12:26 bruno
# added 'var' support back
#
# Revision 1.72 2009/08/17 21:24:24 bruno
# nuke the 'site' references
#
# Revision 1.71 2009/06/04 19:24:44 bruno
# fixing bugs with mason -- extreme programming!
#
# Revision 1.70 2009/05/01 19:06:50 mjk
# chimi con queso
#
# Revision 1.69 2009/03/28 01:28:10 anoop
# Change the way managed_only flag is determined.
# Instead of hardcoding appliances to determine
# managed_only, use appliance and host attributes.
#
# Revision 1.68 2009/03/13 19:44:09 mjk
# - added add.appliance.route
# - added add.os.route
#
# Revision 1.66 2009/03/13 00:02:59 mjk
# - checkpoint for route commands
# - gateway is dead (now a default route)
# - removed comment rows from schema (let's see what breaks)
# - removed short-name from appliance (let's see what breaks)
# - dbreport static-routes is dead
#
# Revision 1.65 2009/03/04 19:48:59 bruno
# return the value
#
# Revision 1.64 2009/03/03 21:57:57 mjk
# pylib style db connections
#
# Revision 1.63 2009/02/24 00:53:04 bruno
# add the flag 'managed_only' to getHostnames(). if managed_only is true and
# if no host names are provide to getHostnames(), then only machines that
# traditionally have ssh login shells will be in the list returned from
# getHostnames()
#
# Revision 1.62 2009/02/10 20:11:59 mjk
# solaris -> sunos
#
# Revision 1.61 2009/02/10 20:11:20 mjk
# os attr stuff for anoop
#
# Revision 1.60 2009/01/24 02:04:28 mjk
# - more ROCKDEBUG stuff (now to stderr)
# - os attr commands (still incomplete)
# - fix ssl code
#
# Revision 1.59 2009/01/23 23:46:50 mjk
# - continue to kill off the var tag
# - can build xml and kickstart files for compute nodes (might even work)
#
# Revision 1.58 2008/10/18 00:55:48 mjk
# copyright 5.1
#
# Revision 1.57 2008/08/19 19:33:33 bruno
# a MAC address is now a valid key to look up a host.
#
# also, one more tweak to get the 'output-col' flag working
#
# Revision 1.56 2008/07/01 21:23:56 bruno
# added the command 'rocks remove roll' and tweaked the other roll commands
# to handle 'arch' flag.
#
# thank to Brandon Davidson from the University of Oregon for these changes.
#
# Revision 1.55 2008/03/06 23:41:33 mjk
# copyright storm on
#
# Revision 1.54 2008/03/06 23:12:55 mjk
# Added column level filtering of output for list commands.
#
# New params
# output-header=BOOL
# output-col=NAME,NAME,...
#
# Now can turn off the header line with output-header=no and can select
# which columns get printed with output-col. For example:
#
# rocks list roll output-col=arch output-header=no
#
# Will just print the arch (not even roll name) for all the rolls on the
# cluster.
#
# TODO: Where to document, not going to touch every list command!
#
# Revision 1.53 2007/11/09 22:08:42 anoop
# Remove annoyance with duplicating multiple roll names
#
# Revision 1.52 2007/07/05 19:09:50 mjk
# - ArgumentProcessors work on empty tables
#
# Revision 1.51 2007/07/05 18:11:36 mjk
# - self.abort() prints command usage (w/o command name)
# - HostArgumentProcessor accepts % again
#
# Revision 1.50 2007/07/04 01:47:37 mjk
# embrace the anger
#
# Revision 1.48 2007/06/29 06:24:49 phil
# escape any XML characters in descriptions when creating docbook format.
#
# Revision 1.47 2007/06/27 21:30:34 bruno
# cleanup distribution commands
#
# Revision 1.46 2007/06/26 20:21:15 bruno
# touch ups
#
# added 'fillParameters' -- now, every command will have fillParameters,
# fillPositionalArgs or neither.
#
# Revision 1.45 2007/06/25 19:25:35 bruno
# need a list, not a list of tuples
#
# Revision 1.44 2007/06/25 18:36:00 bruno
# get the variables in the correct order (reverse the 'vars')
#
# Revision 1.43 2007/06/23 03:54:51 mjk
# - first pass at consistency
# - still needs some docstrings
# - argument processors take SQL wildcards
# - add cannot run twice (must use set)
# - dump does sets not just adds
#
# Revision 1.41 2007/06/19 16:42:40 mjk
# - fix add host interface docstring xml
# - update copyright
#
# Revision 1.40 2007/06/17 00:08:47 phil
# Fix naming of networks.
#
# Revision 1.39 2007/06/16 23:49:20 phil
# Add some helper functions for parameter,argument processing when wanting to
# support named arguments. Cleaned up set host interface mac
#
# Revision 1.38 2007/06/16 02:39:50 mjk
# - added list roll commands (used for docbook)
# - docstrings should now be XML
# - added parser for docstring to ASCII or DocBook
# - ditched Phil's Network regex stuff (will come back later)
# - updated several docstrings
#
# Revision 1.36 2007/06/12 18:01:17 bruno
# kats spels gud
#
# Revision 1.35 2007/06/12 01:33:40 mjk
# - added NetworkArgumentProcessor
# - updated rocks list network
#
# Revision 1.34 2007/06/11 19:26:56 mjk
# - apache counts as root
# - alphabetized some help flags
# - rocks dump error on arguments
#
# Revision 1.33 2007/06/08 03:26:24 mjk
# - plugins call self.owner.addText()
# - non-existant bug was real, fix plugin graph stuff
# - add set host cpus|membership|rack|rank
# - add list host (not /etc/hosts, rather the nodes table)
# - fix --- padding for only None fields not 0 fields
# - list host interfaces is cool works for incomplete hosts
#
# Revision 1.32 2007/06/07 21:23:03 mjk
# - command derive from verb.command class
# - default is MustBeRoot
# - list.command / dump.command set MustBeRoot = 0
# - removed plugin non-bugfix
#
# Revision 1.31 2007/06/07 18:20:02 bruno
# make sure the first plugin get put in the 'dict' dictionary. otherwise, it
# will never be run.
#
# Revision 1.30 2007/06/07 17:21:50 mjk
# - added RollArgumentProcessor
# - added trimOwner option to the endOutput method
# - roll based commands are uniform
#
# Revision 1.29 2007/06/07 16:43:02 mjk
# - moved host(s) argument processing into a top level class
# - list/dump/set host commands now use this
#
# Revision 1.28 2007/06/07 16:19:10 mjk
# - add "rocks add host"
# - add "rocks dump host"
# - add "rocks dump host interface"
# - remove "rocks add host new"
# - add mysql db init script to foundation-mysql
# - more flexible hostname lookup for the command line
#
# Revision 1.27 2007/06/01 23:43:10 mjk
# fix extra space at end of line for endOutput
#
# Revision 1.26 2007/05/25 03:12:30 mjk
# - help takes a flag instead of an argument
# - added bash/readline completion
#
# Revision 1.25 2007/05/10 20:37:00 mjk
# - massive rocks-command changes
# -- list host is standardized
# -- usage simpler
# -- help is the docstring
# -- host groups and select statements
# - added viz commands
#
# Revision 1.23 2007/04/19 23:01:09 bruno
# pretty print rocks command line output with addOutput() and endOutput()
#
# Revision 1.22 2007/03/29 00:16:30 mjk
# - added self.os to base command
# - list.host.profile ready for solaris code
#
# Revision 1.21 2007/03/28 22:33:49 mjk
# - add getHostname() method to base command class
# - fix bad try block for default args in list.node.xml
# - list.node.xml works as standalone
#
# Revision 1.20 2007/03/02 01:14:37 mjk
# fix node specific app_globals
#
# Revision 1.19 2007/02/28 03:06:28 mjk
# - "rocks list host xml" replaces kpp
# - kickstart.cgi uses "rocks list host xml"
# - indirects in node xml now works
#
# Revision 1.18 2007/02/27 21:23:53 mjk
# checkpoint
#
# Revision 1.17 2007/02/27 01:53:57 mjk
# - run(self, args) => run(self, flags, args)
# - replaced rocks list host xml with more complete code
# - replaced rocks lust node xml with kpp shell (not a command now)
#
# Revision 1.16 2007/02/20 18:51:41 mjk
# Added getGlobalVars() method
#
# Revision 1.15 2007/02/13 19:17:39 mjk
# recursive xml for app_global vars
#
# Revision 1.14 2007/02/12 22:55:33 mjk
# start of indirects
#
# Revision 1.13 2007/02/08 17:48:48 mjk
# - single syslog open/close
# - log plug-ins
#
# Revision 1.12 2007/02/08 17:31:25 mjk
# Added root check for root-only commands
# Added syslog tracking to record changes to the cluster
#
# Revision 1.11 2007/02/05 23:29:19 mjk
# added 'rocks add roll'
# added plugin_* facility
# added 'rocks sync user' (plugin-able)
#
# Revision 1.10 2007/02/05 18:55:09 mjk
# fix to 80-col
#
# Revision 1.9 2007/01/17 02:11:39 anoop
# createEntitiesFromDB now replaced by getEntities()
# Minor correction for code that uses the database
#
# Revision 1.8 2007/01/10 17:32:05 mjk
# added list node interfaces|memberships
# minor tweaks
#
# Revision 1.7 2006/12/07 00:29:48 mjk
# might work this time
#
# Revision 1.6 2006/12/07 00:28:14 mjk
# might work this time
#
# Revision 1.5 2006/12/07 00:20:57 mjk
# might work
#
# Revision 1.4 2006/12/06 23:45:11 mjk
# added xxxText methods
#
# Revision 1.3 2006/12/01 22:25:43 bruno
# one world, one cursor
#
# Revision 1.2 2006/11/22 02:15:46 mjk
# working version
#
# Revision 1.1 2006/11/02 21:49:46 mjk
# prototype
#
import json
import os
import socket
import string
import re
import syslog
import pwd
import types
import sys
import sqlalchemy.engine.result
import traceback
import rocks
import rocks.graph
import xml
from xml.sax import saxutils
from xml.sax import handler
from xml.sax import make_parser
from xml.sax._exceptions import SAXParseException
def Abort(message, doExit=1):
"""Print a standard error message and throw a
rocks.util.CommandError"""
syslog.syslog(syslog.LOG_ERR, message)
raise rocks.util.CommandError(message)
class OSArgumentProcessor:
"""An Interface class to add the ability to process os arguments."""
def getOSNames(self, args=None):
"""Returns a list of OS names. For each arg in the ARGS list
normalize the name to one of either 'linux' or 'sunos' as
they are the only supported OSes. If the ARGS list is empty
return a list of all supported OS names.
"""
list = []
for arg in args:
s = arg.lower()
if s == 'linux':
list.append(s)
elif s == 'sunos':
list.append(s)
else:
self.abort('unknown os "%s"' % arg)
if not list:
list.append('linux')
list.append('sunos')
return list
class MembershipArgumentProcessor:
"""An Interface class to add the ability to process membership
arguments."""
def getMembershipNames(self, args=None):
"""Returns a list of membership names from the database.
For each arg in the ARGS list find all the membership
names that match the arg (assume SQL regexp). If an
arg does not match anything in the database we Abort. If the
ARGS list is empty return all membership names.
"""
list = []
if not args:
args = [ '%' ] # find all memberships
for arg in args:
rows = self.db.execute("""select name from memberships
where name like '%s'""" % arg)
if rows == 0 and arg == '%': # empty table is OK
continue
if rows < 1:
self.abort('unknown membership "%s"' % arg)
for name, in self.db.fetchall():
list.append(name)
return list
class DistributionArgumentProcessor:
"""An Interface class to add the ability to process distribution
arguments."""
def getDistributionNames(self, args=None):
"""Returns a list of distribution names from the database.
For each arg in the ARGS list find all the distribution
names that match the arg (assume SQL regexp). If an
arg does not match anything in the database we Abort. If the
ARGS list is empty return all distribution names.
"""
list = []
if not args:
args = [ '%' ] # find all distributions
for arg in args:
rows = self.db.execute("""select name from
distributions where name like '%s'""" % arg)
if rows == 0 and arg == '%': # empty table is OK
continue
if rows < 1:
if arg == '%':
# special processing for when the table
# is empty
continue
else:
self.abort('unknown distribution "%s"' % arg)
for name, in self.db.fetchall():
list.append(name)
return list
class NetworkArgumentProcessor:
"""An Interface class to add the ability to process network (subnet)
argument."""
def getNetworkNames(self, args=None):
"""Returns a list of network (subnet) names from the database.
For each arg in the ARGS list find all the network
names that match the arg (assume SQL regexp). If an
arg does not match anything in the database we Abort. If the
ARGS list is empty return all network names.
"""
list = []
if not args:
args = [ '%' ] # find all networks
for arg in args:
rows = self.db.execute("""select name from subnets
where name like '%s'""" % arg)
if rows == 0 and arg == '%': # empty table is OK
continue
if rows < 1:
self.abort('unknown network "%s"' % arg)
for name, in self.db.fetchall():
list.append(name)
return list
def getNetworkName(self, netid):
"""Returns a network (subnet) name from the database that
is associated with the id 'netid'.
"""
if not netid:
return ''
rows = self.db.execute("""select name from subnets where
id = %s""" % netid)
if rows > 0:
netname, = self.db.fetchone()
else:
netname = ''
return netname
class RollArgumentProcessor:
"""An Interface class to add the ability to process roll arguments."""
def getRollNames(self, args, params):
"""Returns a list of (name, version) tuples from the roll
table in the database. If the PARAMS['version'] is provided
only Rolls of that version are included otherwise no filtering
on version number is performed. If the ARGS list is empty then
all Roll names are returned. SQL regexps acan be used in
both the version parameter and arg list, but must expand to
something.
"""
if params.has_key('version'):
version = params['version']
else:
version = '%' # SQL wildcard
list = []
if not args:
args = [ '%' ] # find all roll names
for arg in args:
rows = self.db.execute("""select distinct name,version
from rolls where name like '%s' and
version like '%s'""" % (arg, version))
if rows == 0 and arg == '%': # empty table is OK
continue
if rows < 1:
self.abort('unknown roll name "%s"' % arg)
for (name, ver) in self.db.fetchall():
list.append((name, ver))
return list
class HostArgumentProcessor:
"""An Interface class to add the ability to process host arguments."""
def getHostnames(self, names=None, managed_only=0):
"""Expands the given list of names to valid cluster
hostnames. A name can be a hostname, IP address, our
group (membership name), or a MAC address. Any combination of
these is valid.
If the names list is empty a list of all hosts in the cluster
is returned.
The following groups are recognized:
rackN - All non-frontend host in rack N
appliancename - All appliances of a given type (e.g. compute)
select ... - an SQL statement that returns a list of hosts
The 'managed_only' flag means that the list of hosts will
*not* contain hosts that traditionally don't have ssh login
shells (for example, the following appliances usually don't
have ssh login access: 'Ethernet Switches', 'Power Units',
'Remote Management')
"""
# Handle the simple case first and just return a complete
# list of hosts in the cluster if no list of names was
# provided
list = []
if not names:
query = 'select name from nodes'
self.db.execute(query)
for host, in self.db.fetchall():
list.append(host)
# If we're looking for managed nodes only, filter out
# the unmanaged ones using host attributes
if managed_only:
managed_list = []
for hostname in list:
if self.db.getHostAttr(hostname,
'managed') == 'true':
managed_list.append(hostname)
return managed_list
return list
# The names list was not empty so we now need to build
# a list of acceptable group names based on the rack numbers
# and appliance names (not membership names). This
# convention follows the original idea (but not code) for
# "dbreport tentakel".
groups = {}
self.db.execute('select min(rack), max(rack) from nodes')
min,max = self.db.fetchone()
for i in range(min, max+1): # racks
self.db.execute("""select n.name from
nodes n, memberships m, appliances a where
n.membership=m.id and m.appliance=a.id and
a.name!="frontend" and n.rack=%d""" % i)
l = []
for node, in self.db.fetchall():
l.append(node)
groups['rack%d' % i] = l
self.db.execute('select name from appliances')
for name, in self.db.fetchall(): # appliances
self.db.execute("""select n.name from
nodes n, memberships m, appliances a where
n.membership=m.id and m.appliance=a.id and
a.name="%s" """ % name)
l = []
for node, in self.db.fetchall():
l.append(node)
groups[name] = l
# Iterate through the list and expand all names to a list of
# host names. Also handle any names that start with 'select'
# and expand them as an SQL queury. Populate a dictionary
# to make sure we only have one entry for each host.
# Then return a sorted list of keys.
#
# We may want to add other expansion rules like the old
# FDS style %d stuff here.
dict = {}
for name in names:
if name.find('select') == 0: # SQL select
self.db.execute(name)
for host, in self.db.fetchall():
dict[host] = 1
elif name.find('%') >= 0: # SQL % pattern
self.db.execute("""select name from nodes where
name like '%s'""" % name)
for h, in self.db.fetchall():
dict[h] = 1
elif groups.has_key(name): # group name
for host in groups[name]:
dict[host] = 1
else: # host name
dict[self.db.getHostname(name)] = 1
list = dict.keys()
list.sort()
return list
class CategoryArgumentProcessor(HostArgumentProcessor):
"""An Interface class to add the ability to process Category=Member arguments."""
def getCategoryIndices(self, args=None, wildcard=0):
"""Returns a list of tuples (category,index),
based upon those available in the database
Special case: args=None, args[0]='global=',
args[0]='global' returns the tuple ('global','global').
An empty list signifies category or index not found
"""
indexList=[]
if args is None or len(args) == 0 :
if wildcard:
indexList.append(('%','%'))
else:
indexList.append(('global','global'))
return indexList
if len(args[0].split('=',1)) == 2:
(category,index) = args[0].split('=',1)
else:
category = args[0]
index=None
if wildcard:
indexList.append((category,'%'))
return indexList
if category == 'global':
indexList.append(('global','global'))
return indexList
if index is None:
self.abort('Cannot have a Null index for category:%s' % category)
# Check of category is valid
rows = self.db.execute("""SELECT ID FROM categories
WHERE name='%s'""" % category)
if rows < 1:
self.abort('unknown category "%s"' % category)
# Check if member of category is valid
# ?? handling of wild-carded hosts for category=host
#
if category == 'host':
hostlist=index.split()
print "host list:" ,hostlist
for index in self.getHostnames(hostlist):
print "checking for host" ,index
rows = self.db.execute("""SELECT ID FROM vcatindex
WHERE catindex='%s' and category='%s'""" % (index,category))
if rows < 1:
self.abort('Unknown index "%s" of category "%s"' % (index,category))
indexList.append((category,index))
else:
rows = self.db.execute("""SELECT ID FROM vcatindex
WHERE catindex='%s' and category='%s'""" % (index,category))
if rows < 1:
self.abort('Unknown index "%s" of category "%s"' % (index,category))
indexList.append((category,index))
return indexList
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['arg'] = []
self.section['param'] = []
self.section['example'] = []
self.section['related'] = []
self.parser = make_parser()
self.parser.setContentHandler(self)
def getDocbookText(self):
s = ''
s += '<section id="rocks-%s" xreflabel="%s">\n' % \
(string.join(self.name.split(' '), '-'), self.name)
s += '<title>%s</title>\n' % self.name
s += '<cmdsynopsis>\n'
s += '\t<command>rocks %s</command>\n' % self.name
for ((name, type, opt, rep), txt) in self.section['arg']:
if opt:
choice = 'opt'
else:
choice = 'req'
if rep:
repeat = 'repeat'
else:
repeat = 'norepeat'
s += '\t<arg rep="%s" choice="%s">%s</arg>\n' % \
(repeat, choice, name)
for ((name, type, opt, rep), txt) in self.section['param']:
if opt:
choice = 'opt'
else:
choice = 'req'
if rep:
repeat = 'repeat'
else:
repeat = 'norepeat'
s += '\t<arg rep="%s" choice="%s">' % (repeat, choice)
s += '%s=<replaceable>%s</replaceable>' % (name, type)
s += '</arg>\n'
s += '</cmdsynopsis>\n'
s += '<para>\n'
s += saxutils.escape(self.section['description'])
s += '\n</para>\n'
if self.section['arg']:
s += '<variablelist><title>arguments</title>\n'
for ((name, type, opt, rep), txt) in \
self.section['arg']:
s += '\t<varlistentry>\n'
if opt:
term = '<optional>%s</optional>' % name
else:
term = name
s += '\t<term>%s</term>\n' % term
s += '\t<listitem>\n'
s += '\t<para>\n'
s += saxutils.escape(txt)
s += '\n\t</para>\n'
s += '\t</listitem>\n'
s += '\t</varlistentry>\n'
s += '</variablelist>\n'
if self.section['param']:
s += '<variablelist><title>parameters</title>\n'
for ((name, type, opt, rep), txt) in \
self.section['param']:
s += '\t<varlistentry>\n'
if opt:
optStart = '<optional>'
optEnd = '</optional>'
else:
optStart = ''
optEnd = ''
key = '%s=' % name
val = '<replaceable>%s</replaceable>' % type
s += '\t<term>%s%s%s%s</term>\n' % \
(optStart, key, val, optEnd)
s += '\t<listitem>\n'
s += '\t<para>\n'
s += saxutils.escape(txt)
s += '\n\t</para>\n'
s += '\t</listitem>\n'
s += '\t</varlistentry>\n'
s += '</variablelist>\n'
if self.section['example']:
s += '<variablelist><title>examples</title>\n'
for (cmd, txt) in self.section['example']:
s += '\t<varlistentry>\n'
s += '\t<term>\n'
if 'root' in self.users:
s += '# '
else:
s += '$ '
s += 'rocks %s' % cmd
s += '\n\t</term>\n'
s += '\t<listitem>\n'
s += '\t<para>\n'
s += saxutils.escape(txt)
s += '\n\t</para>\n'
s += '\t</listitem>\n'
s += '\t</varlistentry>\n'
s += '</variablelist>\n'
if self.section['related']:
s += '<variablelist><title>related commands</title>\n'
for related in self.section['related']:
s += '\t<varlistentry>\n'
s += '\t<term>'
s += '<xref linkend="rocks-%s">' % \
string.join(related.split(' '), '-')
s += '</term>\n'
s += '\t<listitem>\n'
s += '\t<para>\n'
s += '\n\t</para>\n'
s += '\t</listitem>\n'
s += '\t</varlistentry>\n'
s += '</variablelist>\n'
s += '</section>'
return s
def getUsageText(self):
s = ''
for ((name, type, opt, rep), txt) in self.section['arg']:
if opt:
s += '[%s]' % name
else: