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("-v", "--verbose", action="store_true", dest="verbose", help="Be verbose (default: %default)")
18 (options, args) = parser.parse_args()
20 # If user is specified but password is not
21 if options.user is not None and options.password is None:
23 options.password = getpass()
24 except (EOFError, KeyboardInterrupt):
30 def __init__(self, options):
32 # if options are specified use them
33 # otherwise use options from config file
34 if options.config: config_file = options.config
35 else: config_file = '/usr/share/planetlab/tests/nst/nst_config'
38 execfile(config_file, self.__dict__)
40 raise "Could not find nst config in " + config_file
42 if options.url: self.NST_API_SERVER = options.url
43 if options.slice: self.NST_SLICE = options.slice
44 if options.key: self.NST_KEY_PATH = options.key
45 if options.user: self.NST_USER = options.user
46 if options.password: self.NST_PASSWORD = options.password
47 if options.nodes: self.NST_NODES = options.nodes
48 else: self.NST_NODES = None
50 self.api = xmlrpclib.Server(self.NST_API_SERVER)
52 self.auth['Username'] = self.NST_USER
53 self.auth['AuthString'] = self.NST_PASSWORD
54 self.auth['AuthMethod'] = 'password'
55 self.key = self.NST_KEY_PATH
56 self.slice = self.NST_SLICE
57 self.nodes = self.NST_NODES
58 self.verbose = options.verbose
60 self.data_path = '/usr/share/planetlab/tests/nst/data/'
61 self.plots_path = '/usr/share/planetlab/tests/nst/plots/'
64 # get formatted tic string for gnuplot
65 def getTimeTicString(t1, t2, step):
66 first_hour = list(time.localtime(t1))
67 if not first_hour[4] == first_hour[5] == 0:
71 first_hour_time = int(time.mktime(first_hour))
72 first_hour_time += 3600
74 backsteps = (first_hour_time - t1)
76 start = first_hour_time - backsteps * step
81 tics.append("\"%s\" %d" % \
82 (time.strftime("%H:%M", time.localtime(thistime)), thistime))
85 ticstr = ", ".join(tics)
89 # count total number of nodes in PlanetLab, according to the api
90 # count total number of nodes in slice, according to the api
91 def count_nodes_by_api(config):
94 all_nodes = config.api.GetNodes(config.auth, {}, ['node_id', 'slice_ids'])
95 all_nodes_output = "%d\t%d" % (round(time.time()), len(all_nodes))
97 # count all nodes in slice
98 if config.slice == 'root':
99 nodes_in_slice = all_nodes
100 nodes_in_slice_output = all_nodes_output
102 slice_id =config.api.GetSlices(config.auth, {'name': config.slice}, ['slice_id'])[0]['slice_id']
103 nodes_in_slice = [row['node_id'] for row in \
104 all_nodes if slice_id in row['slice_ids']]
105 nodes_in_slice_output = "%d\t%d" % (round(time.time()), len(nodes_in_slice))
107 # write result to datafiles
108 all_nodes_file_name = config.data_path + os.sep + "nodes"
109 all_nodes_file = open(all_nodes_file_name, 'w')
110 all_nodes_file.write(all_nodes_output)
111 all_nodes_file.close()
113 nodes_in_slice_file_name = config.data_path + os.sep + "nodes_in_slice"
114 nodes_in_slice_file = open(nodes_in_slice_file_name, 'w')
115 nodes_in_slice_file.write(nodes_in_slice_output)
116 nodes_in_slice_file.close()
119 print "all node: " + all_nodes_output
120 print "nodes in slice: " + nodes_in_slice_output
123 # count total number of "good" nodes, according to CoMon
124 def count_nodes_good_by_comon(config):
127 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)'")
128 good_nodes = comon.readlines()
130 comon_output = "%d\t%d" % (round(time.time()), len(good_nodes))
131 nodes_good_comon_file_name = config.data_path + os.sep + "nodes_good"
132 nodes_good_comon_file = open(nodes_good_comon_file_name, 'a')
133 nodes_good_comon_file.write(comon_output)
134 nodes_good_comon_file.close()
137 print "comon: " + comon_output
139 # count total number of nodes reachable by ssh
140 def count_nodes_can_ssh(config):
145 verbose = config.verbose
151 print "Creating list of nodes to ssh to"
153 verbose_text = ">/dev/null 2>&1"
156 all_nodes = api.GetNodes(auth, {}, ['hostname', 'boot_state', 'last_updated'])
158 for node in all_nodes:
159 node_dict[node['hostname']] = node
163 nodes_file = open(nodes, 'r')
164 nodes_filename = nodes_file.name
165 lines = nodes_file.readlines()
166 node_list = [node.replace('\n', '') for node in lines]
170 node_list = node_dict.keys()
171 nodes_filename = tempfile.mktemp()
172 nodes_file = open(nodes_filename, 'w')
173 for node in node_list:
174 nodes_file.write("%(node)s\n" % locals())
179 for node in all_nodes:
180 node_dict[node['hostname']] = node
182 private_key = key.split(".pub")[0]
186 print "Attemptng to ssh to nodes in " + nodes_filename
188 ssh_filename = tempfile.mktemp()
189 ssh_file = open(ssh_filename, 'w')
191 export MQ_SLICE="%(slice)s"
192 export MQ_NODES="%(nodes_filename)s"
194 eval `ssh-agent` >/dev/null 2>&1
195 trap "kill $SSH_AGENT_PID" 0
196 ssh-add %(private_key)s >/dev/null 2>&1
198 multiquery 'hostname' 2>/dev/null |
203 ssh_results = os.popen("bash %(ssh_filename)s" % locals()).readlines()
204 from pprint import pprint
206 if len(ssh_results) > 0:
207 ssh_result = eval(ssh_results[0].replace('\\n', ''))
211 #if os.path.exists(nodes_filename): os.unlink(nodes_filename)
212 #if os.path.exists(ssh_filename): os.unlink(ssh_filename)
214 # create a list of hostname out of results that are not empty
216 for result in ssh_result:
217 if result.find("bytes") > -1:
218 result_parts = result.split(":")
219 hostname = result_parts[0]
220 good_nodes.append(hostname)
222 # count number of node we can ssh into
223 ssh_count = len(good_nodes)
225 # determine whince nodes are dead:
226 dead_nodes = set(node_list).difference(good_nodes)
228 # write dead nodes to file
229 curr_time = round(time.time())
230 dead_node_count_output = "%d\t%d" % (curr_time, len(dead_nodes))
231 dead_nodes_file_name = config.data_path + os.sep + "dead_nodes"
232 dead_nodes_file = open(dead_nodes_file_name, 'a')
233 for hostname in dead_nodes:
234 boot_state = node_dict[hostname]['boot_state']
236 if node_dict[hostname]['last_updated']:
237 last_updated = node_dict[hostname]['last_updated']
238 dead_nodes_file.write("%(curr_time)d\t%(hostname)s\t%(boot_state)s\t%(last_updated)d\n" % \
240 dead_nodes_file.close()
242 # write good node count
243 ssh_result_output = "%d\t%d" % (round(time.time()), ssh_count)
244 nodes_can_ssh_file_name = config.data_path + os.sep + "nodes_can_ssh"
245 nodes_can_ssh_file = open(nodes_can_ssh_file_name, 'a')
246 nodes_can_ssh_file.write(ssh_result_output)
247 nodes_can_ssh_file.close()
250 print "nodes that can ssh: " + ssh_result_output
251 print "dead nodes: " + dead_node_count_output
254 # remove all nodes from a slice
255 def empty_slice(config):
258 print "Removing %s from all nodes" % config.slice
260 all_nodes = [row['node_id'] for row in config.api.GetNodes(config.auth, {}, ['node_id'])]
261 config.api.DeleteSliceFromNodes(config.auth, config.slice, all_nodes)
264 # add slice to all nodes.
265 # make sure users key is up to date
266 def init_slice(config):
271 key_path = config.key
272 verbose = config.verbose
273 slices = api.GetSlices(auth, [slice], \
274 ['slice_id', 'name', 'person_ids'])
276 raise "No such slice %s" % slice
279 # make sure user is in slice
280 person = api.GetPersons(auth, auth['Username'], \
281 ['person_id', 'email', 'slice_ids', 'key_ids'])[0]
282 if slice['slice_id'] not in person['slice_ids']:
283 raise "%s not in %s slice. Must be added first" % \
284 (person['email'], slice['name'])
286 # make sure user key is up to date
287 current_key = open(key_path, 'r').readline().strip()
288 if len(current_key) == 0:
289 raise "Key cannot be empty"
291 keys = api.GetKeys(auth, person['key_ids'])
294 print "Adding new key " + key_path
295 api.AddPersonKey(auth, person['person_id'], \
296 {'key_type': 'ssh', 'key': current_key})
298 elif not filter(lambda k: k['key'] == current_key, keys):
300 print "%s was modified or is new. Updating PLC"
302 api.UpdateKey(auth, old_key['key_id'], \
303 {'key': current_key})
307 # add slice to all nodes
309 print "Generating list of all nodes "
310 all_nodes = [row['node_id'] for row in \
311 api.GetNodes(auth, {}, ['node_id'])]
313 print "Adding %s to all nodes" % slice['name']
314 api.AddSliceToNodes(auth, slice['slice_id'], all_nodes)
317 # create the fill/empty plot
318 def plot_fill_empty():
319 #ticstep = 3600 # 1 hour
320 #plotlength = 36000 # 10 hours
324 plots_path = config.plots_path
326 all_nodes_file_name = config.data_path + os.sep + "nodes"
327 nodes_in_slice_file_name = config.data_path + os.sep + "nodes_in_slice"
328 nodes_can_ssh_file_name = config.data_path + os.sep + "nodes_can_ssh"
329 nodes_good_comon_file_name = config.data_path + os.sep + "nodes_good"
331 tmpfilename = tempfile.mktemp()
332 tmpfile = open(tmpfilename, 'w')
336 for datafilename in [all_nodes_file_name,
337 nodes_in_slice_file_name, \
338 nodes_can_ssh_file_name, \
339 nodes_good_comon_file_name]:
340 datafile = open(datafilename, 'r')
341 line1 = datafile.readline()
343 line2 = datafile.readlines().pop()
344 thisstarttime = int(line1.split("\t")[0])
345 if starttime == -1 or thisstarttime < starttime:
346 starttime = thisstarttime
347 thisstoptime = int(line2.split("\t")[0])
348 if stoptime == -1 or thisstoptime > stoptime:
349 stoptime = thisstoptime
352 startx = max(starttime, stopx - plotlength)
355 tics = getTimeTicString(starttime, stoptime, ticstep)
357 startdate = time.strftime("%b %m, %Y - %H:%M", time.localtime(startx))
358 stopdate = time.strftime("%H:%M", time.localtime(stopx))
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_file_name)s" u 1:2 w lines title "Total Nodes", \
373 "%(nodes_in_slice_file_name)s" u 1:2 w lines title "Nodes in Slice", \
374 "%(nodes_good_comon_file_name)s" u 1:2 w lines title \
375 "Healthy Nodes (according to CoMon)", \
376 "%(nodes_can_ssh_file_name)s" u 1:2 w lines title "Nodes Reachable by SSH"
382 os.system("%s %s" % (gnuplot_path, tmpfilename))
384 if os.path.exists(tmpfilename):
385 os.unlink(tmpfilename)
389 config = Config(options)
392 if config.slice == 'root':
395 print "Logging in as root"
397 # set up slice and add it to nodes
401 print "Waiting %(sleep_time)d seconds for nodes to update" % locals()
402 # wait 15 mins for nodes to get the data
406 count_nodes_can_ssh(config)
407 count_nodes_by_api(config)
408 count_nodes_good_by_comon(config)
412 #os.system("cp plots/*.png ~/public_html/planetlab/tests")