3 import time, sys, urllib, os, tempfile, random
5 from optparse import OptionParser
6 from getpass import getpass
9 parser = OptionParser()
10 parser.add_option("-c", "--config", action="store", dest="config", help="Path to alternate config file")
11 parser.add_option("-x", "--url", action="store", dest="url", help = "API URL")
12 parser.add_option("-s", "--slice", action="store", dest="slice", help = "Name of slice to use")
13 parser.add_option("-n", "--nodes", action="store", dest="nodes", help = "File that contains a list of nodes to try to access")
14 parser.add_option("-k", "--key", action="store", dest="key", help = "Path to alternate public key")
15 parser.add_option("-u", "--user", action="store", dest="user", help = "API user name")
16 parser.add_option("-p", "--password", action="store", dest="password", help = "API password")
17 parser.add_option("-g", "--graph-only", action="store_true", dest="graph_only", help = "Only plot the current data, then exit")
18 parser.add_option("-l", "--plot-length", action="store", dest="plot_length", help = "Plot x-axis (time) length in seconds")
19 parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Be verbose (default: %default)")
20 (options, args) = parser.parse_args()
22 # If user is specified but password is not
23 if options.user is not None and options.password is None:
25 options.password = getpass()
26 except (EOFError, KeyboardInterrupt):
32 def __init__(self, options):
34 # if options are specified use them
35 # otherwise use options from config file
36 if options.config: config_file = options.config
37 else: config_file = '/usr/share/planetlab/tests/node-ssh/nst_config'
40 execfile(config_file, self.__dict__)
42 raise "Could not find nst config in " + config_file
44 if options.url: self.url = self.NST_API_SERVER = options.url
45 if options.slice: self.NST_SLICE = options.slice
46 if options.key: self.NST_KEY_PATH = options.key
47 if options.user: self.NST_USER = options.user
48 if options.password: self.NST_PASSWORD = options.password
49 if options.nodes: self.NST_NODES = options.nodes
50 else: self.NST_NODES = None
51 if options.plot_length: self.NST_PLOT_LENGTH = options.plot_length
53 self.api = xmlrpclib.Server(self.NST_API_SERVER)
55 self.auth['Username'] = self.NST_USER
56 self.auth['AuthString'] = self.NST_PASSWORD
57 self.auth['AuthMethod'] = 'password'
58 self.key = self.NST_KEY_PATH
59 self.slice = self.NST_SLICE
60 self.nodes = self.NST_NODES
61 self.plot_length = self.NST_PLOT_LENGTH
63 self.verbose = options.verbose
66 self.data_path = '/var/lib/planetlab/tests/node-ssh/data/'
67 self.plots_path = '/var/lib/planetlab/tests/node-ssh/plots/'
70 self.all_nodes_filename = self.data_path + os.sep + "nodes"
71 self.nodes_in_slice_filename = self.data_path + os.sep + "nodes_in_slice"
72 self.nodes_can_ssh_filename = self.data_path + os.sep + "nodes_can_ssh"
73 self.nodes_good_comon_filename = self.data_path + os.sep + "nodes_good"
76 # get formatted tic string for gnuplot
77 def getTimeTicString(t1, t2, step):
78 first_hour = list(time.localtime(t1))
79 if not first_hour[4] == first_hour[5] == 0:
83 first_hour_time = int(time.mktime(first_hour))
84 first_hour_time += 3600
86 backsteps = (first_hour_time - t1)
88 start = first_hour_time - backsteps * step
93 tics.append("\"%s\" %d" % \
94 (time.strftime("%H:%M", time.localtime(thistime)), thistime))
97 ticstr = ", ".join(tics)
101 # count total number of nodes in PlanetLab, according to the api
102 # count total number of nodes in slice, according to the api
103 def count_nodes_by_api(config, current_time, all_nodes):
106 all_nodes_output = "%d\t%d" % (current_time, len(all_nodes))
108 # count all nodes in slice
109 if config.slice == 'root':
110 nodes_in_slice = all_nodes
111 nodes_in_slice_output = all_nodes_output
113 slice_id =config.api.GetSlices(config.auth, {'name': config.slice}, ['slice_id'])[0]['slice_id']
114 nodes_in_slice = [row['node_id'] for row in \
115 all_nodes if slice_id in row['slice_ids']]
116 nodes_in_slice_output = "%d\t%d" % (current_time, len(nodes_in_slice))
118 # write result to datafiles
119 all_nodes_file = open(config.all_nodes_filename, 'a')
120 all_nodes_file.write(all_nodes_output + "\n")
121 all_nodes_file.close()
123 nodes_in_slice_file = open(config.nodes_in_slice_filename, 'a')
124 nodes_in_slice_file.write(nodes_in_slice_output + "\n")
125 nodes_in_slice_file.close()
128 print "all node: " + all_nodes_output
129 print "nodes in slice: " + nodes_in_slice_output
132 # count total number of "good" nodes, according to CoMon
133 def count_nodes_good_by_comon(config, current_time):
136 comon = urllib.urlopen("http://summer.cs.princeton.edu/status/tabulator.cgi?table=table_nodeviewshort&format=nameonly&select='resptime%20%3E%200%20&&%20((drift%20%3E%201m%20||%20(dns1udp%20%3E%2080%20&&%20dns2udp%20%3E%2080)%20||%20gbfree%20%3C%205%20||%20sshstatus%20%3E%202h)%20==%200)'")
137 good_nodes = comon.readlines()
139 comon_output = "%d\t%d" % (current_time, len(good_nodes))
140 nodes_good_comon_file = open(config.nodes_good_comon_filename, 'a')
141 nodes_good_comon_file.write(comon_output + "\n")
142 nodes_good_comon_file.close()
145 print "comon: " + comon_output
147 # count total number of nodes reachable by ssh
148 def count_nodes_can_ssh(config, current_time, all_nodes):
153 verbose = config.verbose
159 print "Creating list of nodes to ssh to"
161 verbose_text = ">/dev/null 2>&1"
165 for node in all_nodes:
166 node_dict[node['hostname']] = node
170 nodes_file = open(nodes, 'r')
171 nodes_filename = nodes_file.name
172 lines = nodes_file.readlines()
173 node_list = [node.replace('\n', '') for node in lines]
177 node_list = node_dict.keys()
178 nodes_filename = tempfile.mktemp()
179 nodes_file = open(nodes_filename, 'w')
180 for node in node_list:
181 nodes_file.write("%(node)s\n" % locals())
186 for node in all_nodes:
187 node_dict[node['hostname']] = node
189 private_key = key.split(".pub")[0]
193 print "Attemptng to ssh to nodes in " + nodes_filename
195 ssh_filename = tempfile.mktemp()
196 ssh_file = open(ssh_filename, 'w')
198 export MQ_SLICE="%(slice)s"
199 export MQ_NODES="%(nodes_filename)s"
201 eval `ssh-agent` >/dev/null 2>&1
202 trap "kill $SSH_AGENT_PID" 0
203 ssh-add %(private_key)s >/dev/null 2>&1
205 multiquery 'hostname' 2>/dev/null |
210 ssh_results = os.popen("bash %(ssh_filename)s" % locals()).readlines()
211 good_nodes= [result.split(':')[0] for result in ssh_results]
214 if os.path.exists(nodes_filename): os.unlink(nodes_filename)
215 if os.path.exists(ssh_filename): os.unlink(ssh_filename)
217 # count number of node we can ssh into
218 ssh_count = len(good_nodes)
220 # determine whince nodes are dead:
221 dead_nodes = set(node_list).difference(good_nodes)
223 # write dead nodes to file
224 dead_node_count_output = "%d\t%d" % (current_time, len(dead_nodes))
225 dead_nodes_file_name = config.data_path + os.sep + "dead_nodes"
226 dead_nodes_file = open(dead_nodes_file_name, 'w')
228 for hostname in dead_nodes:
229 boot_state = node_dict[hostname]['boot_state']
231 if node_dict[hostname]['last_contact']:
232 last_contact = node_dict[hostname]['last_contact']
233 dead_nodes_file.write("%(current_time)d\t%(hostname)s\t%(boot_state)s\t%(last_contact)d\n" % \
235 dead_nodes_file.close()
237 # write good node count
238 ssh_result_output = "%d\t%d" % (current_time, ssh_count)
239 nodes_can_ssh_file = open(config.nodes_can_ssh_filename, 'a')
240 nodes_can_ssh_file.write(ssh_result_output + "\n")
241 nodes_can_ssh_file.close()
244 print "nodes that can ssh: " + ssh_result_output
245 print "dead nodes: " + dead_node_count_output
248 # remove all nodes from a slice
249 def empty_slice(config, all_nodes):
252 print "Removing %s from all nodes" % config.slice
254 all_node_ids = [row['node_id'] for row in all_nodes]
255 config.api.DeleteSliceFromNodes(config.auth, config.slice, all_node_ids)
258 # add slice to all nodes.
259 # make sure users key is up to date
260 def init_slice(config, all_nodes):
265 key_path = config.key
266 verbose = config.verbose
267 slices = api.GetSlices(auth, [slice], \
268 ['slice_id', 'name', 'person_ids', 'node_ids'])
270 raise "No such slice %s" % slice
273 # make sure user is in slice
274 person = api.GetPersons(auth, auth['Username'], \
275 ['person_id', 'email', 'slice_ids', 'key_ids'])[0]
276 if slice['slice_id'] not in person['slice_ids']:
277 raise "%s not in %s slice. Must be added first" % \
278 (person['email'], slice['name'])
280 # make sure user key is up to date
281 current_key = open(key_path, 'r').readline().strip()
282 if len(current_key) == 0:
283 raise "Key cannot be empty"
285 keys = api.GetKeys(auth, person['key_ids'])
288 print "Adding new key " + key_path
289 api.AddPersonKey(auth, person['person_id'], \
290 {'key_type': 'ssh', 'key': current_key})
292 elif not filter(lambda k: k['key'] == current_key, keys):
294 print "%s was modified or is new. Updating PLC"
296 api.UpdateKey(auth, old_key['key_id'], \
297 {'key': current_key})
299 # add slice to all nodes
301 print "Generating list of all nodes not in slice"
302 all_node_ids = [row['node_id'] for row in all_nodes]
304 new_nodes = set(all_node_ids).difference(slice['node_ids'])
306 print "Adding %s to nodes: %r " % (slice['name'], new_nodes)
308 api.AddSliceToNodes(auth, slice['slice_id'], list(new_nodes))
311 # create the fill/empty plot
312 def plot_fill_empty(config):
313 #ticstep = 3600 # 1 hour
314 #plotlength = 36000 # 10 hours
316 plotlength = int(config.plot_length)
317 plots_path = config.plots_path
319 all_nodes_filename = config.all_nodes_filename
320 nodes_in_slice_filename = config.nodes_in_slice_filename
321 nodes_can_ssh_filename = config.nodes_can_ssh_filename
322 nodes_good_comon_filename = config.nodes_good_comon_filename
324 tmpfilename = tempfile.mktemp()
325 tmpfile = open(tmpfilename, 'w')
329 for datafilename in [all_nodes_filename,
330 nodes_in_slice_filename, \
331 nodes_can_ssh_filename, \
332 nodes_good_comon_filename]:
333 datafile = open(datafilename, 'r')
334 lines = datafile.readlines()
336 line_start = lines[0]
337 line_end = lines[len(lines) -1]
341 thisstarttime = int(line_start.split("\t")[0])
342 if starttime == -1 or thisstarttime < starttime:
343 starttime = thisstarttime
344 thisstoptime = int(line_end.split("\t")[0])
345 if stoptime == -1 or thisstoptime > stoptime:
346 stoptime = thisstoptime
349 startx = max(starttime, stopx - plotlength)
352 tics = getTimeTicString(starttime, stoptime, ticstep)
354 startdate = time.strftime("%b %m, %Y - %H:%M", time.localtime(startx))
355 stopdate = time.strftime("%H:%M", time.localtime(stopx))
358 print "plotting data with start date: %(startdate)s and stop date: %(stopdate)s" % locals()
362 set output "%(plots_path)s/fill_empty.png"
364 set title "Number of Nodes / Time - %(startdate)s to %(stopdate)s"
366 set ylabel "Number of Nodes"
369 set xrange[%(startx)d:%(stopx)d]
372 plot "%(all_nodes_filename)s" u 1:2 w lines title "Total Nodes", \
373 "%(nodes_in_slice_filename)s" u 1:2 w lines title "Nodes in Slice", \
374 "%(nodes_good_comon_filename)s" u 1:2 w lines title \
375 "Healthy Nodes (according to CoMon)", \
376 "%(nodes_can_ssh_filename)s" u 1:2 w lines title "Nodes Reachable by SSH"
379 tmpfile.write(plot_output % locals())
383 print plot_output % locals()
385 os.system("gnuplot %s" % tmpfilename)
387 if os.path.exists(tmpfilename): os.unlink(tmpfilename)
392 config = Config(options)
394 if options.graph_only:
395 plot_fill_empty(config)
398 current_time = round(time.time())
399 all_nodes = config.api.GetNodes(config.auth, {}, \
400 ['node_id', 'boot_state', 'hostname', 'last_contact', 'slice_ids'])
403 # if root is specified we will ssh into root context, not a slice
404 # so no need to add a slice to all nodes
405 if config.slice == 'root':
408 print "Logging in as root"
410 # set up slice and add it to nodes
411 init_slice(config, all_nodes)
414 print "Waiting %d seconds for nodes to update" % config.sleep_time
416 # wait for nodes to get the data
417 sleep(config.sleep_time)
421 count_nodes_can_ssh(config, current_time, all_nodes)
422 count_nodes_by_api(config, current_time, all_nodes)
423 count_nodes_good_by_comon(config, current_time)
426 plot_fill_empty(config)
427 #os.system("cp plots/*.png ~/public_html/planetlab/tests")
430 empty_slice(config, all_nodes)