fewer output lines
[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_qemus = False
24         self.do_tracker_plcs = False
25
26     def fqdn (self, box):
27         return "%s.%s"%(box,self.domain)
28     @staticmethod
29     def root (box): return "root@%s"%box
30
31     def header (self,message):
32         print "===============",message
33
34     def run (self,argv,message, trash_err=False):
35         if self.options.dry_run:
36             print 'DRY_RUN:',
37             print " ".join(argv)
38         else:
39             if message: self.header(message)
40             if not trash_err:
41                 subprocess.call(argv)
42             else:
43                 subprocess.call(argv,stderr=file('/dev/null','w'))
44                 
45     def backquote (self, argv, trash_err=False):
46         if not trash_err:
47             return subprocess.Popen(argv,stdout=subprocess.PIPE).communicate()[0]
48         else:
49             null = open('/dev/null','w')
50             result = subprocess.Popen(argv,stdout=subprocess.PIPE,stderr=null).communicate()[0]
51             null.close()
52             return result
53
54     def reboot (self,box):
55         command=['ssh',self.root(box),'shutdown','-r','now']
56         self.run (command,"Rebooting %s"%box)
57
58     def handle_tracker_file (self,filename):
59         box = self.fqdn (self.testmaster)
60         if self.options.probe:
61             command=['ssh',self.root(box),"head","-v","--lines=100",filename]
62             self.run(command,"++++++++++ Inspecting %s on %s"%(filename,box))
63         else:
64             command=['ssh',self.root(box),"rm","-rf",filename]
65             self.run(command,"Cleaning up %s on %s"%(filaneme,box))
66
67     def handle_tracker_plcs (self):
68         self.handle_tracker_file("tracker-plcs")
69     def handle_tracker_qemus (self):
70         self.handle_tracker_file("tracker-qemus")
71     def handle_trackers (self):
72         self.handle_tracker_plcs()
73         self.handle_tracker_qemus()
74
75     def handle_build_box (self,box):
76         if not self.options.probe:
77             self.reboot(box)
78         else:
79             command=['ssh',self.root(box),'uptime']
80             uptime=self.backquote(command,True).strip()
81
82             command=['ssh',self.root(box),'pgrep','build']
83             if self.options.dry_run:
84                 self.run(command,None)
85             else:
86                 pids=self.backquote(command,True)
87                 if not pids:
88                     self.header ('No build process on %s (%s)'%(box,uptime))
89                 else:
90                     command=['ssh',self.root(box),'ps','-o','pid,command'] + [ pid for pid in pids.split("\n") if pid]
91                     self.run(command,"Active build processes on %s (%s)"%(box,uptime),True)
92
93     vplc_matcher = re.compile(".*(vplc[0-9]+$)")
94     def vplcname (self, vservername):
95         match = self.vplc_matcher.match(vservername)
96         if match: return match.groups(0)
97         else: return ""
98
99     def handle_plc_box (self,box):
100         if not self.options.probe:
101             self.reboot(box)
102         else:
103             command=['ssh',self.root(box),'vserver-stat']
104             if self.options.dry_run:
105                 self.run(command,"Active vservers on %s"%box)
106             else:
107                 # try to find fullname (vserver_stat truncates to a ridiculously short name)
108                 try:
109                     self.header ("vserver map on %s"%box)
110                     # fetch the contexts for all vservers on that box
111                     map_command=['ssh',self.root(box),'grep','.','/etc/vservers/*/context','/dev/null',]
112                     context_map=self.backquote (map_command)
113                     # at this point we have a set of lines like
114                     # /etc/vservers/2010.01.20--k27-f12-32-vplc03/context:40144
115                     ctx_dict={}
116                     for map_line in context_map.split("\n"):
117                         if not map_line: continue
118                         [path,xid] = map_line.split(':')
119                         ctx_dict[xid]=os.path.basename(os.path.dirname(path))
120                     # at this point ctx_id maps context id to vservername
121
122                     vserver_stat = self.backquote (command)
123                     format="%-14s"
124                     for vserver_line in vserver_stat.split("\n"):
125                         if not vserver_line: continue
126                         context=vserver_line.split()[0]
127                         if context=="CTX": 
128                             print format%"",vserver_line
129                             continue
130                         longname=ctx_dict[context]
131                         plcname=self.vplcname(longname)
132                         header="== %s =="%plcname
133                         print format%header,"%(vserver_line)s [=%(longname)s]"%locals()
134                 except:
135                     self.run(command,"Fine-grained method failed - fallback to plain vserver-stat")
136
137     vnode_matcher = re.compile(".*(vnode[0-9]+)")
138     def vnodename (self, ps_line):
139         match = self.vnode_matcher.match(ps_line)
140         if match: return match.groups(0)
141         else: return ""
142
143
144     def handle_qemu_box (self,box):
145         if not self.options.probe:
146             self.reboot(box)
147         else:
148             command=['ssh',self.root(box),'pgrep','qemu']
149             if self.options.dry_run:
150                 self.run(command,None)
151             else:
152                 pids=self.backquote(command)
153                 if not pids:
154                     self.header ('No qemu process on %s'%box)
155                 else:
156                     format="%-14s"
157                     self.header ("Active qemu processes on %s"%box)
158                     command=['ssh',self.root(box),'ps','-o','pid,command'] + [ pid for pid in pids.split("\n") if pid]
159                     ps_lines = self.backquote (command).split("\n")
160                     for ps_line in ps_lines:
161                         if not ps_line or ps_line.find('PID') >=0 : continue
162                         header=self.vnodename(ps_line)
163                         print format%header, ps_line
164
165     def handle_box(self,box,type):
166         if box in self.qemu_boxes:
167             if type=="qemu": self.handle_qemu_box(self.fqdn(box))
168         elif box in self.plc_boxes:
169             if type=="plc":  self.handle_plc_box(self.fqdn(box))
170         elif type=="build":
171             self.handle_build_box(self.fqdn(box))
172
173     def main (self):
174         usage="""%prog [options] [hostname..(s)]
175 Default is to act on test boxes only (with trackers clean)"""
176         parser = OptionParser (usage=usage)
177         parser.add_option ("-n","--dry-run",action="store_true",dest="dry_run",default=False,
178                            help="Dry run")
179         parser.add_option ("-r","--reboot", action="store_false",dest="probe",default=True,
180                            help="Actually reset/reboot stuff instead of just probing it")
181         # no need for -p = probe, as this is the default
182         parser.add_option ("-p","--plc", action="store_true",dest="plc_only",default=False,
183                            help="Acts on the plc box only")
184
185         parser.add_option ("-a","--all",action="store_true",dest="all_boxes",default=False,
186                            help="Acts on build and test boxes")
187         parser.add_option ("-b","--build",action="store_true",dest="build_only",default=False,
188                            help="Acts on build boxes only")
189         parser.add_option ("-q","--qemu",action="store_true",dest="qemu_only",default=False,
190                            help="Only acts on the qemu boxes")
191         parser.add_option ("-t","--trackers",action="store_true",dest="trackers_only",default=False,
192                            help="Only wipes trackers")
193
194         (self.options,args) = parser.parse_args()
195
196         # use given hostnames if provided
197         if args:
198             self.boxes=args
199             # if hostnames are specified, let's stay on the safe side and don't reset trackers
200             self.do_tracker_plcs = False
201             self.do_tracker_qemus = False
202         elif self.options.all_boxes:
203             self.boxes=self.test_boxes + self.build_boxes
204             self.do_tracker_plcs = True
205             self.do_tracker_qemus = True
206         elif self.options.build_only:
207             self.boxes=self.build_boxes
208             self.do_tracker_plcs = False
209             self.do_tracker_qemus = False
210         elif self.options.qemu_only:
211             self.boxes=self.qemu_boxes
212             self.do_tracker_plcs = False
213             self.do_tracker_qemus = True
214         elif self.options.plc_only:
215             self.boxes=self.plc_boxes
216             self.do_tracker_plcs = True
217             self.do_tracker_qemus = False
218         elif self.options.trackers_only:
219             self.boxes = []
220             self.do_tracker_plcs = True
221             self.do_tracker_qemus = True
222         # default
223         else:
224             self.boxes = self.test_boxes
225             self.do_tracker_plcs = True
226             self.do_tracker_qemus = True
227
228         # ALL OTHERS
229         for box in self.boxes:  self.handle_box (box,"build")
230         # PLCS
231         if self.do_tracker_plcs:self.handle_tracker_plcs ()
232         for box in self.boxes:  self.handle_box (box,"plc")
233         # QEMU
234         if self.do_tracker_qemus:self.handle_tracker_qemus ()
235         for box in self.boxes:  self.handle_box (box,"qemu")
236
237 if __name__ == "__main__":
238     BuildBoxes().main()