enable builds of k22/f12 thanks to tag -39-2
[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),'uptime']
62             uptime=self.backquote(command).strip()
63
64             command=['ssh',self.root(box),'pgrep','build']
65             if self.options.dry_run:
66                 self.run(command,None)
67             else:
68                 pids=self.backquote(command)
69                 if not pids:
70                     self.header ('No build process on %s (%s)'%(box,uptime))
71                 else:
72                     command=['ssh',self.root(box),'ps','-o','pid,command'] + [ pid for pid in pids.split("\n") if pid]
73                     self.run(command,"Active build processes on %s (%s)"%(box,uptime))
74
75     vplc_matcher = re.compile(".*(vplc[0-9]+$)")
76     def vplcname (self, vservername):
77         match = self.vplc_matcher.match(vservername)
78         if match: return match.groups(0)
79         else: return ""
80
81     def handle_plc_box (self,box):
82         if not self.options.probe:
83             self.reboot(box)
84         else:
85             command=['ssh',self.root(box),'vserver-stat']
86             if self.options.dry_run:
87                 self.run(command,"Active vservers on %s"%box)
88             else:
89                 # try to find fullname (vserver_stat truncates to a ridiculously short name)
90                 try:
91                     self.header ("vserver map on %s"%box)
92                     # fetch the contexts for all vservers on that box
93                     map_command=['ssh',self.root(box),'grep','.','/etc/vservers/*/context','/dev/null',]
94                     context_map=self.backquote (map_command)
95                     # at this point we have a set of lines like
96                     # /etc/vservers/2010.01.20--k27-f12-32-vplc03/context:40144
97                     ctx_dict={}
98                     for map_line in context_map.split("\n"):
99                         if not map_line: continue
100                         [path,xid] = map_line.split(':')
101                         ctx_dict[xid]=os.path.basename(os.path.dirname(path))
102                     # at this point ctx_id maps context id to vservername
103
104                     vserver_stat = self.backquote (command)
105                     for vserver_line in vserver_stat.split("\n"):
106                         if not vserver_line: continue
107                         context=vserver_line.split()[0]
108                         if context=="CTX": 
109                             print vserver_line
110                             continue
111                         longname=ctx_dict[context]
112                         plcname=self.vplcname(longname)
113                         if plcname: print "== %s =="%plcname
114                         print "%(vserver_line)s [=%(longname)s]"%locals()
115                 except:
116                     self.run(command,"Fine-grained method failed - fallback to plain vserver-stat")
117
118     vnode_matcher = re.compile(".*(vnode[0-9]+)")
119     def vnodename (self, ps_line):
120         match = self.vnode_matcher.match(ps_line)
121         if match: return match.groups(0)
122         else: return ""
123
124
125     def handle_qemu_box (self,box):
126         if not self.options.probe:
127             self.reboot(box)
128         else:
129             command=['ssh',self.root(box),'pgrep','qemu']
130             if self.options.dry_run:
131                 self.run(command,None)
132             else:
133                 pids=self.backquote(command)
134                 if not pids:
135                     self.header ('No qemu process on %s'%box)
136                 else:
137                     self.header ("Active qemu processes on %s"%box)
138                     command=['ssh',self.root(box),'ps','-o','pid,command'] + [ pid for pid in pids.split("\n") if pid]
139                     ps_lines = self.backquote (command).split("\n")
140                     for ps_line in ps_lines:
141                         if not ps_line or ps_line.find('PID') >=0 : continue
142                         node=self.vnodename(ps_line)
143                         if node: print "== %s =="%node
144                         print ps_line
145
146     def handle_box(self,box):
147         if box in self.qemu_boxes:
148             self.handle_qemu_box(self.fqdn(box))
149         elif box in self.plc_boxes:
150             self.handle_plc_box(self.fqdn(box))
151         else:
152             self.handle_build_box(self.fqdn(box))
153
154     def main (self):
155         usage="""%prog [options] [hostname..(s)]
156 Default is to act on test boxes only (with trackers clean)"""
157         parser = OptionParser (usage=usage)
158         parser.add_option ("-n","--dry-run",action="store_true",dest="dry_run",default=False,
159                            help="Dry run")
160         parser.add_option ("-r","--reboot", action="store_false",dest="probe",default=True,
161                            help="Actually reset/reboot stuff instead of just probing it")
162         # no need for -p = probe, as this is the default
163         parser.add_option ("-p","--plc", action="store_true",dest="plc_only",default=False,
164                            help="Acts on the plc box only")
165
166         parser.add_option ("-a","--all",action="store_true",dest="all_boxes",default=False,
167                            help="Acts on build and test boxes")
168         parser.add_option ("-b","--build",action="store_true",dest="build_only",default=False,
169                            help="Acts on build boxes only")
170         parser.add_option ("-q","--qemu",action="store_true",dest="qemu_only",default=False,
171                            help="Only acts on the qemu boxes")
172         parser.add_option ("-t","--trackers",action="store_true",dest="trackers_only",default=False,
173                            help="Only wipes trackers")
174
175         (self.options,args) = parser.parse_args()
176
177         # use given hostnames if provided
178         if args:
179             self.boxes=args
180             # if hostnames are specified, let's stay on the safe side and don't reset trackers
181             self.do_tracker = False
182         elif self.options.all_boxes:
183             self.boxes=self.test_boxes + self.build_boxes
184             self.do_tracker = True
185         elif self.options.build_only:
186             self.boxes=self.build_boxes
187             self.do_tracker = False
188         elif self.options.qemu_only:
189             self.boxes=self.qemu_boxes
190             self.do_tracker = False
191         elif self.options.plc_only:
192             self.boxes=self.plc_boxes
193             self.do_tracker = False
194         elif self.options.trackers_only:
195             self.boxes = []
196             self.do_tracker = True
197         # default
198         else:
199             self.boxes = self.test_boxes
200             self.do_tracker = True
201
202         if self.do_tracker:
203             self.handle_trackers ()
204         for box in self.boxes:
205             self.handle_box (box)
206
207
208 if __name__ == "__main__":
209     BuildBoxes().main()