1#!/usr/bin/python -u
2
3import sys
4import gobject
5import dbus
6import dbus.service
7import dbus.mainloop.glib
8import subprocess
9from obmc.dbuslib.bindings import get_dbus
10
11
12FLASH_DOWNLOAD_PATH = '/tmp'
13DBUS_NAME = 'org.openbmc.managers.Download'
14OBJ_NAME = '/org/openbmc/managers/Download'
15TFTP_PORT = 69
16
17class DownloadManagerObject(dbus.service.Object):
18	def __init__(self,bus,name):
19		dbus.service.Object.__init__(self,bus,name)
20		bus.add_signal_receiver(self.DownloadHandler,
21			dbus_interface = "org.openbmc.Flash",
22			signal_name = "Download", path_keyword = "path")
23		bus.add_signal_receiver(self.TftpDownloadHandler,
24			signal_name = "TftpDownload", path_keyword = "path")
25
26
27	@dbus.service.signal(DBUS_NAME,signature='ss')
28	def DownloadComplete(self,outfile,filename):
29		print "Download Complete: "+outfile
30		return outfile
31
32	@dbus.service.signal(DBUS_NAME,signature='s')
33	def DownloadError(self,filename):
34		pass
35
36	def TftpDownloadHandler(self,ip,filename,path = None):
37		try:
38			filename = str(filename)
39			print "Downloading: "+filename+" from "+ip
40			outfile = FLASH_DOWNLOAD_PATH+"/"+filename
41			rc = subprocess.call(["tftp", "-l",outfile,"-r",filename,"-g",ip])
42			if (rc == 0):
43				self.DownloadComplete(outfile,filename)
44			else:
45				self.DownloadError(filename)
46
47
48		except Exception as e:
49			print "ERROR DownloadManager: "+str(e)
50			self.DownloadError(filename)
51
52
53	## TODO: this needs to be deprecated.  Shouldn't call flash interface from here
54	def DownloadHandler(self,url,filename,path = None):
55		try:
56			filename = str(filename)
57			print "Downloading: "+filename+" from "+url
58			outfile = FLASH_DOWNLOAD_PATH+"/"+filename
59			subprocess.call(["tftp", "-l",outfile,"-r",filename,"-g",url])
60			obj = bus.get_object("org.openbmc.control.Flash",path)
61			intf = dbus.Interface(obj,"org.openbmc.Flash")
62			intf.update(outfile)
63
64		except Exception as e:
65			print "ERROR DownloadManager: "+str(e)
66			obj = bus.get_object("org.openbmc.control.Flash",path)
67			intf = dbus.Interface(obj,"org.openbmc.Flash")
68			intf.error("Download Error: "+filename)
69
70
71if __name__ == '__main__':
72    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
73    bus = get_dbus()
74    obj = DownloadManagerObject(bus, OBJ_NAME)
75    mainloop = gobject.MainLoop()
76    name = dbus.service.BusName(DBUS_NAME, bus)
77
78    print "Running Download Manager"
79    mainloop.run()
80
81