This file is indexed.

/usr/lib/pwrkap/ui_controller.py is in pwrkap-gui 7.30-5.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#!/usr/bin/python

"""GTK UI controller for pwrkap."""
# (C) Copyright IBM Corp. 2008-2009
# Licensed under the GPLv2.

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
import gobject
import thread
import ui_data
import datetime
import time
import threading
import traceback
import pwrkap_data
import sys

HAVE_MATPLOTLIB = True
try:
	from matplotlib.axes import Subplot
	from matplotlib.figure import Figure

	# uncomment to select /GTK/GTKAgg/GTKCairo
	#from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
	from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
	#from matplotlib.backends.backend_gtkcairo import FigureCanvasGTKCairo as FigureCanvas
except:
	HAVE_MATPLOTLIB = False

DEFAULT_TITLE = "Energy Consumption"
GRAPH_DRAW_INTERVAL = 5
UI_DRAW_INTERVAL = 2
DRAW_GRAPH = False

class ui_controller:
	"""Binding between gtk controls and various actions."""

	def __init__(self, hosts):
		"""Create a UI."""
		global DEFAULT_TITLE

		self.window_name = "monitor_window"
		try:
			self.window_tree = gtk.glade.XML("ui.glade", self.window_name)
		except:
			try:
				self.window_tree = gtk.glade.XML("/usr/share/pwrkap/ui.glade", self.window_name)
			except:
				print "Could not find UI file; is pwrkap installed correctly?"
				sys.exit(2)

		self.window = self.window_tree.get_widget(self.window_name)
		self.window.set_title(DEFAULT_TITLE)
		self.hosts = hosts

		# Set up the machine list model
		self.tree = self.window_tree.get_widget("host_names")
		model = gtk.TreeStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING, gobject.TYPE_STRING)

		renderer = gtk.CellRendererText()
		column = gtk.TreeViewColumn("Machine", renderer, text = 1)
		self.tree.append_column(column)
		column = gtk.TreeViewColumn("Domain", renderer, text = 2)
		self.tree.append_column(column)
		self.tree.set_model(model)

		self.all_iter = model.insert_before(None, None)
		model.set_value(self.all_iter, 0, (None, None))
		model.set_value(self.all_iter, 1, "All Systems")

		# GTK Event handling
		events = {
			"on_close_button_clicked": self.close_app,
			"on_set_cap_button_clicked": self.set_cap,
			"on_max_sample_age_changed": self.set_max_sample_age,
			"on_host_names_cursor_changed": self.select_power_object_later,
			"on_show_graph_toggled": self.show_graph_toggle}
		self.window_tree.signal_autoconnect(events)
		self.window.connect("destroy", self.close_app)

		# pwrkap event handling
		self.pwrkap_events = {
			ui_data.HOST_CONNECTED: self.host_connected,
			ui_data.HOST_DISCONNECTED: self.host_disconnected,
			ui_data.HOST_DOMAIN_DATA_RECEIVED: self.data_seen}

		# Create the graph
		graphs = self.create_graph()
		self.graph_lock = threading.Lock()
		vbox = self.window_tree.get_widget("main_vbox")
		if graphs != None:
			(self.fig, self.canvas) = graphs
			vbox.pack_start(self.canvas)
			vbox.reorder_child(self.canvas, 0)
		else:
			graph_checkbox = self.window_tree.get_widget("show_graph")
			graph_checkbox.set_sensitive(False)
			label = gtk.Label("Graphs unavailable because matplotlib is not installed.")
			vbox.pack_start(label)
			vbox.reorder_child(label, 0)

		# Other housekeeping variables
		self.cur_host = None
		self.cur_dom = None
		self.tree.set_cursor("0")
		self.selection_did_change = True
		self.graph_changed = True
		self.last_graph_draw_time = datetime.datetime.utcnow()
		self.last_ui_draw_time = datetime.datetime.utcnow()
		self.in_gtk_update = False
		self.in_draw_graph = False
		self.dom_cap = None
		self.dom_power = None
		self.dom_energy = None
		self.dom_util = None
		#self.window.set_size_request(1024, 768)

		self.window.show_all()

		self.connect_signal = threading.Condition()

	def close_app(self, widget):
		"""Close the program."""
		gtk.main_quit()

	def show_graph_toggle(self, widget):
		"""Enable or disable the graph via check box."""
		global DRAW_GRAPH

		new_value = widget.get_active()
		if new_value:
			dialog = gtk.Dialog("Slow graph warning", None, \
				gtk.DIALOG_MODAL, # | gtk.DIALOG_DESTROY_WITH_PARENT, 
				(gtk.STOCK_NO, gtk.RESPONSE_NO, gtk.STOCK_YES, gtk.RESPONSE_YES))
			label = gtk.Label("Graphing power use of a large number of power domains can\nbe very processor intensive!  Are you sure you want to proceed?")
			dialog.vbox.pack_start(label, padding = 15)
			dialog.vbox.set_border_width(15)
			label.show()
			res = dialog.run()
			dialog.hide()

			if res == gtk.RESPONSE_NO:
				widget.set_active(False)
				return

		DRAW_GRAPH = widget.get_active()
		thread.start_new_thread(self.selection_changed, ())

	def connect_hosts(self):
		"""Connect all hosts."""
		model = self.tree.get_model()
		for host in self.hosts:
			host.add_listener(self)
			iter = model.insert_after(None, self.all_iter)
			model.set_value(iter, 0, (host, None))
			model.set_value(iter, 1, "%s:%d" % (host.host, host.port))

		try:
			#thread.stack_size(65536)
			x = 3
		except:
			pass

		for host in self.hosts:
			thread.start_new_thread(host.control_loop, ())
			self.connect_signal.acquire()
			self.connect_signal.wait(10)
			self.connect_signal.release()

	def find_tree_iter_from_host(self, host):
		"""Return a tree iterator given a host object."""
		model = self.tree.get_model()
		root_iter = model.get_iter_root()
		while root_iter != None and model.get_value(root_iter, 0)[0] != host:
			root_iter = model.iter_next(root_iter)
		return root_iter

	def pwrkap_event(self, event_type, affected):
		"""Acknowledge a pwrkap host event."""
		handler = self.pwrkap_events[event_type]
		handler(affected)

	def host_connected(self, affected):
		"""Handle a host connection."""
		print "Host connected"
		self.connect_signal.acquire()
		self.connect_signal.notify()
		self.connect_signal.release()

		gtk.gdk.threads_enter()
		model = self.tree.get_model()
		host_iter = self.find_tree_iter_from_host(affected)
		print (affected, affected.host, affected.port)
		doms = []
		for domain_name in affected.domains.keys():
			domain_object = affected.domains[domain_name]
			doms.append(domain_object)
			iter = model.insert_after(host_iter, None)
			model.set_value(iter, 0, (affected, domain_object))
			model.set_value(iter, 2, domain_name)
		gtk.gdk.threads_leave()

		agg = ui_data.pwrkap_aggregate_domain(doms, "All Domains")
		gtk.gdk.threads_enter()
		(x, y) = model.get_value(host_iter, 0)
		model.set_value(host_iter, 0, (x, agg))
		gtk.gdk.threads_leave()

		self.update_all_aggregate()
		print "end processing new host"

	def host_disconnected(self, affected):
		"""Handle a host disconnection."""
		model = self.tree.get_model()
		host_iter = self.find_tree_iter_from_host(affected)
		dom_iter = model.iter_children(host_iter)
		gtk.gdk.threads_enter()
		while dom_iter != None:
			next = model.iter_next(dom_iter)
			model.remove(dom_iter)
			dom_iter = next
		(x, y) = model.get_value(host_iter, 0)
		model.set_value(host_iter, 0, (x, None))
		gtk.gdk.threads_leave()

		self.update_all_aggregate()

	def update_all_aggregate(self):
		"""Update the 'All Systems' aggregate."""
		doms = []
		model = self.tree.get_model()
		for host in self.hosts:
			for dom_name in host.domains.keys():
				dom = host.domains[dom_name]
				doms.append(dom)
		agg = None
		if len(doms) != 0:
			agg = ui_data.pwrkap_aggregate_domain(doms, "All Systems")

		gtk.gdk.threads_enter()
		(x, y) = model.get_value(self.all_iter, 0)
		model.set_value(self.all_iter, 0, (x, agg))
		gtk.gdk.threads_leave()

		self.select_power_object()

	def data_seen(self, affected):
		"""Handle incoming snapshot data."""
		if self.cur_dom != None and self.cur_dom.is_affected_by(affected):
			self.update_view()

	def create_graph(self):
		"""Connect matplotlib graph to our gtk/glade window."""
		global HAVE_MATPLOTLIB

		if not HAVE_MATPLOTLIB:
			return None

		# Extract GTK background color
		gtk_bgcolors = gtk.Style().bg
		bg_color_str = "#%X%X%X" % (round(float(gtk_bgcolors[2].red) / 65536 * 256),
					    round(float(gtk_bgcolors[2].green) / 65536 * 256),
					    round(float(gtk_bgcolors[2].blue) / 65536 * 256))

		# Create figure
		fig = Figure()
		fig.set_facecolor(bg_color_str)
		fig.set_edgecolor(bg_color_str)
		canvas = FigureCanvas(fig)
		return (fig, canvas)

	def select_power_object_later(self, widget):
		"""Select new object... later."""
		thread.start_new_thread(self.select_power_object, ())

	def select_power_object(self):
		"""Slide a new power-manageable object into view. \
NOTE: The GDK lock must be held before calling this function."""
		model = self.tree.get_model()
		(tree, iter) = self.tree.get_selection().get_selected()
		try:
			obj = model.get_value(iter, 0)
		except:
			return
		self.cur_host = obj[0]
		self.cur_dom = obj[1]
		self.selection_changed()

	def gtk_update_view(self, draw_graph):
		"""Update all GTK controls."""

		def time_to_age_string(time):
			"""Convert seconds to age string."""
			if time >= 86400:
				str = "%d Day" % (time / 86400)
			elif time >= 3600:
				str = "%d Hour" % (time / 3600)
			else:
				str = "%d Minute" % (time / 60)
			if str[0] != '1':
				str = str + "s"
			return str

		def fmt_energy(e):
			"""Render energy use as a string."""
			e = e / 3600

			if e == None:
				return "Unknown"
			elif e < 1000:
				return "%.3fWh" % e
			elif e < 1000000:
				return "%.3fKWH" % (e / 1000)
			elif e < 1000000000:
				return "%.3fMWH" % (e / 1000000)
			else:
				return "%.3fGWH" % (e / 1000000000)

		global DEFAULT_TITLE, DRAW_GRAPH, HAVE_MATPLOTLIB

		self.in_gtk_update = True
		# Update GTK control enablement and values
		if self.cur_dom != None:
			# Enable controls
			self.window_tree.get_widget("power_cap_field").set_sensitive(True)
			self.window_tree.get_widget("max_sample_age").set_sensitive(True)
			self.window_tree.get_widget("set_cap_button").set_sensitive(True)

			# Set max cap
			if self.cur_dom.get_cap() != None and self.selection_did_change:
				new_val = 0
				if self.dom_cap != None:
					new_val = self.dom_cap
				self.window_tree.get_widget("power_cap_field").set_value(new_val)

			# Set max record age
			widget = self.window_tree.get_widget("max_sample_age")
			if self.cur_dom.get_max_sample_age() == None:
				# Assume 30 minutes is ok (?)
				widget.set_active(2)
			else:
				age_str = time_to_age_string(self.cur_dom.get_max_sample_age())
				for i in range(0, len(widget.get_model())):
					if widget.get_model()[i][0] == age_str:
						widget.set_active(i)
						break
		else:
			# Disable controls
			self.window_tree.get_widget("power_cap_field").set_sensitive(False)
			self.window_tree.get_widget("max_sample_age").set_sensitive(False)
			self.window_tree.get_widget("set_cap_button").set_sensitive(False)

		# Update window title
		title = " - " + DEFAULT_TITLE
		if self.cur_host != None:
			title = self.cur_host.get_name() + title
		if self.cur_dom != None:
			sep = ""
			if self.cur_host != None:
				sep = " : "
			title = self.cur_dom.get_name() + sep + title
		self.window.set_title(title)

		# Update more controls
		if self.dom_cap == None:
			self.window_tree.get_widget("power_cap_label").set_text("")
			self.window_tree.get_widget("power_use_label").set_text("")
			self.window_tree.get_widget("energy_use_label").set_text("")
			self.window_tree.get_widget("domain_use_label").set_text("")
			self.window_tree.get_widget("overcap_label").set_text("")
		else:
			self.window_tree.get_widget("power_cap_label").set_text("%dW" % int(self.dom_cap))
			self.window_tree.get_widget("power_use_label").set_text("%dW" % int(self.dom_power))
			self.window_tree.get_widget("energy_use_label").set_text(fmt_energy(self.dom_energy))
			self.window_tree.get_widget("domain_use_label").set_text("%d%%" % self.dom_util)
			if self.dom_cap < self.dom_power:	
				self.window_tree.get_widget("overcap_label").set_markup("<span foreground='red'><b>Cap exceeded by %dW!</b></span>" % (self.dom_power - self.dom_cap))
			else:
				self.window_tree.get_widget("overcap_label").set_text("")

		# Draw graph
		if DRAW_GRAPH and self.graph_changed:
			atime=datetime.datetime.utcnow()
			self.canvas.draw()
			btime=datetime.datetime.utcnow()
			print ("elapsed draw time", (btime-atime))
		elif not DRAW_GRAPH and HAVE_MATPLOTLIB:
			self.fig.clear()
			self.canvas.draw()

		self.selection_did_change = False
		self.graph_changed = False
		self.in_gtk_update = False

	def selection_changed(self):
		"""Update the UI because the selection changed.
NOTE: The GDK lock must be held before calling this function."""

		self.selection_did_change = True
		self.update_view()

	def update_view(self):
		"""Update the view.
NOTE: The GDK lock must be held before calling this function."""
		global UI_DRAW_INTERVAL

		now = datetime.datetime.utcnow()
		if not self.selection_did_change and (now - self.last_ui_draw_time).seconds < UI_DRAW_INTERVAL:
			return

		self.draw_graph()

		if self.cur_dom != None:
			self.dom_cap = self.cur_dom.get_cap()
			self.dom_power = self.cur_dom.get_power()
			self.dom_energy = self.cur_dom.get_energy()
			self.dom_util = pwrkap_data.average_utilization(self.cur_dom.get_utilization_details())
		else:
			self.dom_cap = None
			self.dom_power = None
			self.dom_energy = None
			self.dom_util = None

		if not self.in_gtk_update:
			gobject.idle_add(self.gtk_update_view, ())
		self.last_ui_draw_time = datetime.datetime.utcnow()

	def set_cap(self, widget):
		"""Set a power cap due as a result of UI stimulus."""
		widget = self.window_tree.get_widget("power_cap_field")
		if self.cur_dom == None:
			return
		self.cur_dom.set_cap(widget.get_value_as_int())

	def set_max_sample_age(self, widget):
		"""Set max sample age due as a result of UI stimulus."""
		def age_to_time(age_string):
			"""Convert age string to seconds."""
			items = age_string.split()
			time = int(items[0])
			units = items[1]
			if units.startswith("Minute"):
				time = time * 60
			elif units.startswith("Hour"):
				time = time * 3600
			elif units.startswith("Day"):
				time = time * 86400
			return time
	
		if self.cur_dom == None:
			return
		
		age_str = widget.get_model()[widget.get_active()][0]
		age = age_to_time(age_str)
		self.cur_dom.set_max_sample_age(age)

	def draw_graph(self):
		"""Draw the graph.  NOTE: GDK lock must be held."""
		if self.in_draw_graph:
			return
		self.graph_lock.acquire()
		self.in_draw_graph = True
		self.__draw_graph()
		self.in_draw_graph = False
		self.graph_lock.release()

	def __draw_graph(self):
		"""Draw the graph.  NOTE: Graph and GDK lock must be held."""
		def time_to_age(time_list):
			"""Convert a list of absolute times to ages."""
			new_list = []
			now = datetime.datetime.utcnow()
			nows = time.mktime(now.timetuple())
			for t in time_list:
				new_list.append((nows - t) / 60)
			return new_list

		global GRAPH_DRAW_INTERVAL, DRAW_GRAPH, HAVE_MATPLOTLIB

		if not HAVE_MATPLOTLIB:
			return

		if self.cur_dom == None:
			self.fig.clear()
			return

		# Don't draw the graph too frequently if we can help it;
		# matplotlib is rather slow.
		now = datetime.datetime.utcnow()
		if not self.selection_did_change and (now - self.last_graph_draw_time).seconds < GRAPH_DRAW_INTERVAL:
			return

		self.last_graph_draw_time = now

		if not DRAW_GRAPH:
			return

		a_plot = datetime.datetime.utcnow()
		print "Start extract"

		res = self.cur_dom.get_historical_data_as_lists()
		if res == None:
			print "No results to plot?"
			return
		(times, cap, power, energy, util_details) = res
		times = time_to_age(times)

		b_plot = datetime.datetime.utcnow()
		print ("elapsed extract time", (b_plot - a_plot))
		# Add plot
		self.fig.clear()
		self.fig.subplots_adjust(hspace = 0.4)
		power_axes = self.fig.add_subplot(2, 1, 1)
		power_axes.grid(True)
		power_axes.axis('auto')

		# Plot power data
		cap_line = power_axes.plot(times, cap, 'r-o', linewidth = 2, aa = True)
		power_line = power_axes.plot(times, power, 'b-o', linewidth = 2, aa = True)
		(ymin, ymax) = power_axes.set_ylim()
		power_axes.set_ylim(ymin = ymin - 5, ymax = ymax + 5)
		power_axes.set_ylabel("Watts")
		power_axes.set_title("Power Use vs. Time")
		power_axes.yaxis.tick_left()

		# Plot utilization data
		util_axes = self.fig.add_subplot(2, 1, 2)
		util_axes.grid(True)

		colors = ["#7F0000", "#007F00", "#00007F", "#C0C0C0", "#CCCC00", "#00CCCC", "#CC00CC"]
		color_index = 0
		tr = times * 1
		tr.reverse()
		times_reversed = (times * 1).reverse()
		last_y = [0] * len(times)
		t = times + tr
		num_plots = len(util_details.keys())
		num_samples = len(times)
		for dev in util_details.keys():
			curr_y = []
			for i in range(0, num_samples):
				curr_y.append((util_details[dev][i] / num_plots) + last_y[i])
			last_y.reverse()
			u = curr_y + last_y
			util_axes.fill(t, u, facecolor = colors[color_index], \
				       linewidth = 0, alpha = 0.8)
			last_y = curr_y
			color_index = color_index + 1
			if color_index >= len(colors):
				color_index = 0

		util_line = util_axes.plot(times, last_y, '-o', color = "black", \
					   linewidth = 2, aa = True)

		util_axes.set_ylim(ymin = -5, ymax = 105)
		util_axes.set_title("Device Use vs. Time")
		util_axes.set_ylabel("Use (%)")
		util_axes.set_xlabel("Minutes Ago")

		# Labels for the plots
		power_axes.legend((cap_line, power_line), ('Cap', 'Usage'), 'best')
		util_axes.legend((util_line,), ('Overall Use',), 'best')

		c_plot = datetime.datetime.utcnow()
		print ("elapsed plot time", (c_plot - b_plot))

		#fp = file("/tmp/goo", "w")
		#for i in range(0, len(times)):
		#	fp.write("%f %d %d %d\n" % (times[i], cap[i], power[i], util[i]))
		#fp.close()

		#self.canvas.draw()
		self.graph_changed = True