outline vnode when listing qemu boxes
[infrastructure.git] / scripts / manage-infrastructure.py
1 #!/usr/bin/python
2
3 import os.path
4 import re
5 import subprocess
6 from optparse import OptionParser
7
8 class BuildBoxes:
9
10     # everything in the onelab.eu domain
11     domain = 'onelab.eu'
12     testmaster = 'testmaster'
13     build_boxes = [ "mirror", "liquid", "reed", "velvet", ]
14     plc_boxes = [ "testplc" ]
15     qemu_boxes = \
16         [ "testqemu%d"%i for i in range (1,4) ] + \
17         [ "testqemu32-%d"%i for i in range (1,6) ]
18     test_boxes = plc_boxes + qemu_boxes
19
20     def __init__ (self):
21         # dummy defaults
22         self.boxes = []
23         self.do_tracker = False
24
25     def fqdn (self, box):
26         return "%s.%s"%(box,self.domain)
27     @staticmethod
28     def root (box): return "root@%s"%box
29
30     def header (self,message):
31         print "===============",message
32
33     def run (self,argv,message):
34         if self.options.dry_run:
35             print 'DRY_RUN:',
36             print " ".join(argv)
37         else:
38             if message: self.header(message)
39             subprocess.call(argv)
40                 
41     def backquote (self, argv):
42         return subprocess.Popen(argv,stdout=subprocess.PIPE).communicate()[0]
43
44     def reboot (self,box):
45         command=['ssh',self.root(box),'shutdown','-r','now']
46         self.run (command,"Rebooting %s"%box)
47
48     def handle_trackers (self):
49         box = self.fqdn (self.testmaster)
50         if self.options.probe:
51             command=['ssh',self.root(box),"head","-100","tracker*"]
52             self.run(command,"Inspecting trackers on %s"%box)
53         else:
54             command=['ssh',self.root(box),"rm","-rf","tracker*"]
55             self.run(command,"Cleaning up trackers on %s"%box)
56
57     def handle_build_box (self,box):
58         if not self.options.probe:
59             self.reboot(box)
60         else:
61             command=['ssh',self.root(box),'pgrep','build']
62             if self.options.dry_run:
63                 self.run(command,None)
64             else:
65                 pids=self.backquote(command)
66                 if not pids:
67                     self.header ('No build process on %s'%box)
68                 else:
69                     command=['ssh',self.root(box),'ps'] + [ pid for pid in pids.split("\n") if pid]
70                     self.run(command,"Active build processes on %s"%box)
71
72     vplc_matcher = re.compile(".*(vplc[0-9]+$)")
73     def vplcname (self, vservername):
74         match = self.vplc_matcher.match(vservername)
75         if match: return match.groups(0)
76         else: return ""
77
78     def handle_plc_box (self,box):
79         if not self.options.probe:
80             self.reboot(box)
81         else:
82             command=['ssh',self.root(box),'vserver-stat']
83             if self.options.dry_run:
84                 self.run(command,"Active vservers on %s"%box)
85             else:
86                 # try to find fullname (vserver_stat truncates to a ridiculously short name)
87                 try:
88                     self.header ("vserver map on %s"%box)
89                     # fetch the contexts for all vservers on that box
90                     map_command=['ssh',self.root(box),'grep','.','/etc/vservers/*/context','/dev/null',]
91                     context_map=self.backquote (map_command)
92                     # at this point we have a set of lines like
93                     # /etc/vservers/2010.01.20--k27-f12-32-vplc03/context:40144
94                     ctx_dict={}
95                     for map_line in context_map.split("\n"):
96                         if not map_line: continue
97                         [path,xid] = map_line.split(':')
98                         ctx_dict[xid]=os.path.basename(os.path.dirname(path))
99                     # at this point ctx_id maps context id to vservername
100
101                     vserver_stat = self.backquote (command)
102                     for vserver_line in vserver_stat.split("\n"):
103                         if not vserver_line: continue
104                         context=vserver_line.split()[0]
105                         if context=="CTX": 
106                             print vserver_line
107                             continue
108                         longname=ctx_dict[context]
109                         plcname=self.vplcname(longname)
110                         if plcname: print "== %s =="%plcname
111                         print "%(vserver_line)s [=%(longname)s]"%locals()
112                 except:
113                     self.run(command,"Fine-grained method failed - fallback to plain vserver-stat")
114
115     vnode_matcher = re.compile(".*(vnode[0-9]+)")
116     def vnodename (self, ps_line):
117         match = self.vnode_matcher.match(ps_line)
118         if match: return match.groups(0)
119         else: return ""
120
121
122     def handle_qemu_box (self,box):
123         if not self.options.probe:
124             self.reboot(box)
125         else:
126             command=['ssh',self.root(box),'pgrep','qemu']
127             if self.options.dry_run:
128                 self.run(command,None)
129             else:
130                 pids=self.backquote(command)
131                 if not pids:
132                     self.header ('No qemu process on %s'%box)
133                 else:
134                     self.header ("Active qemu processes on %s"%box)
135                     command=['ssh',self.root(box),'ps'] + [ pid for pid in pids.split("\n") if pid]
136                     ps_lines = self.backquote (command).split("\n")
137                     for ps_line in ps_lines:
138                         if not ps_line or ps_line.find('PID') >=0 : continue
139                         node=self.vnodename(ps_line)
140                         if node: print "== %s =="%node
141                         print ps_line
142
143     def handle_box(self,box):
144         if box in self.qemu_boxes:
145             self.handle_qemu_box(self.fqdn(box))
146         elif box in self.plc_boxes:
147             self.handle_plc_box(self.fqdn(box))
148         else:
149             self.handle_build_box(self.fqdn(box))
150
151     def main (self):
152         usage="""%prog [options] [hostname..(s)]
153 Default is to act on test boxes only (with trackers clean)"""
154         parser = OptionParser (usage=usage)
155         parser.add_option ("-n","--dry-run",action="store_true",dest="dry_run",default=False,
156                            help="Dry run")
157         parser.add_option ("-r","--reboot", action="store_false",dest="probe",default=True,
158                            help="Actually reset/reboot stuff instead of just probing it")
159         # no need for -p = probe, as this is the default
160         parser.add_option ("-p","--plc", action="store_true",dest="plc_only",default=False,
161                            help="Acts on the plc box only")
162
163         parser.add_option ("-a","--all",action="store_true",dest="all_boxes",default=False,
164                            help="Acts on build and test boxes")
165         parser.add_option ("-b","--build",action="store_true",dest="build_only",default=False,
166                            help="Acts on build boxes only")
167         parser.add_option ("-q","--qemu",action="store_true",dest="qemu_only",default=False,
168                            help="Only acts on the qemu boxes")
169         parser.add_option ("-t","--trackers",action="store_true",dest="trackers_only",default=False,
170                            help="Only wipes trackers")
171
172         (self.options,args) = parser.parse_args()
173
174         # use given hostnames if provided
175         if args:
176             self.boxes=args
177             # if hostnames are specified, let's stay on the safe side and don't reset trackers
178             self.do_tracker = False
179         elif self.options.all_boxes:
180             self.boxes=self.build_boxes + self.test_boxes
181             self.do_tracker = True
182         elif self.options.build_only:
183             self.boxes=self.build_boxes
184             self.do_tracker = False
185         elif self.options.qemu_only:
186             self.boxes=self.qemu_boxes
187             self.do_tracker = False
188         elif self.options.plc_only:
189             self.boxes=self.plc_boxes
190             self.do_tracker = False
191         elif self.options.trackers_only:
192             self.boxes = []
193             self.do_tracker = True
194         # default
195         else:
196             self.boxes = self.test_boxes
197             self.do_tracker = True
198
199         if self.do_tracker:
200             self.handle_trackers ()
201         for box in self.boxes:
202             self.handle_box (box)
203
204
205 if __name__ == "__main__":
206     BuildBoxes().main()