def doShowGUI(self, arg): lg.out(2, 'initializer.doShowGUI') if settings.NewWebGUI(): from web import control d = control.init() else: from web import webcontrol d = webcontrol.init() try: from system.tray_icon import USE_TRAY_ICON except: USE_TRAY_ICON = False lg.exc() if USE_TRAY_ICON: from system import tray_icon if settings.NewWebGUI(): # tray_icon.SetControlFunc(control.on_tray_icon_command) tray_icon.SetControlFunc(self._on_tray_icon_command) else: tray_icon.SetControlFunc(webcontrol.OnTrayIconCommand) if not settings.NewWebGUI(): webcontrol.ready() if self.flagGUI or not self.is_installed: if settings.NewWebGUI(): def _show_gui(wsgiport): reactor.callLater(0.1, control.show) d.addCallback(_show_gui) # reactor.callLater(0.1, control.show) else: d.addCallback(webcontrol.show)
def doUpdate(self, arg): if not settings.NewWebGUI(): from web import webcontrol reactor.callLater(0, webcontrol.OnUpdateStartingPage) else: from web import control control.request_update()
def state_changed(self, oldstate, newstate, event, arg): """ Method to catch the moment when automat's state were changed. """ if not settings.NewWebGUI(): from web import webcontrol webcontrol.OnServiceStateChanged(self.service_name)
def start(self): from storage import backup_fs from storage import backup_control from storage import backup_matrix from storage import backup_monitor from main import settings from main.config import conf from p2p import p2p_connector backup_fs.init() backup_control.init() backup_matrix.init() if settings.NewWebGUI(): from web import control backup_matrix.SetBackupStatusNotifyCallback( control.on_backup_stats) backup_matrix.SetLocalFilesNotifyCallback( control.on_read_local_files) else: from web import webcontrol backup_matrix.SetBackupStatusNotifyCallback( webcontrol.OnBackupStats) backup_matrix.SetLocalFilesNotifyCallback( webcontrol.OnReadLocalFiles) backup_monitor.A('init') backup_monitor.A('restart') conf().addCallback('services/backups/keep-local-copies-enabled', self._on_keep_local_copies_modified) conf().addCallback('services/backups/wait-suppliers-enabled', self._on_wait_suppliers_modified) p2p_connector.A().addStateChangedCallback( self._on_p2p_connector_state_changed, 'INCOMMING?', 'CONNECTED') p2p_connector.A().addStateChangedCallback( self._on_p2p_connector_state_changed, 'MY_IDENTITY', 'CONNECTED') return True
def start(self): from storage import restore_monitor from web import webcontrol from main import settings restore_monitor.init() if not settings.NewWebGUI(): restore_monitor.OnRestorePacketFunc = webcontrol.OnRestoreProcess restore_monitor.OnRestoreBlockFunc = webcontrol.OnRestoreSingleBlock restore_monitor.OnRestoreDoneFunc = webcontrol.OnRestoreDone return True
def doRepaint(self, arg): """ Action method. """ if not settings.NewWebGUI(): from web import webcontrol webcontrol.OnAliveStateChanged(self.idurl) else: from web import control control.request_update([('contact', self.idurl)])
def doSubstituteSupplier(self, arg): """ Action method. """ new_idurl = arg current_suppliers = list(contactsdb.suppliers()) if new_idurl in current_suppliers: raise Exception('%s is already supplier' % new_idurl) position = -1 old_idurl = None for i in range(len(current_suppliers)): if current_suppliers[i].strip() == '': position = i break if current_suppliers[i] in self.dismiss_list: # self.dismiss_list.remove(current_suppliers[i]) position = i old_idurl = current_suppliers[i] break lg.out(10, 'fire_hire.doSubstituteSupplier position=%d' % position) if position < 0: current_suppliers.append(new_idurl) else: current_suppliers[position] = new_idurl contactsdb.update_suppliers(current_suppliers) contactsdb.save_suppliers() misc.writeSupplierData( new_idurl, 'connected', time.strftime('%d-%m-%Y %H:%M:%S'), my_id.getLocalID(), ) if settings.NewWebGUI(): from web import control control.on_suppliers_changed(current_suppliers) else: from web import webcontrol webcontrol.OnListSuppliers() if position < 0: lg.out(2, '!!!!!!!!!!! ADDED NEW SUPPLIER : %s' % (new_idurl)) events.send('supplier-modified', dict( new_idurl=new_idurl, old_idurl=None, position=(len(current_suppliers) - 1), )) else: if old_idurl: lg.out(2, '!!!!!!!!!!! SUBSTITUTE EXISTING SUPPLIER %d : %s->%s' % (position, old_idurl, new_idurl)) events.send('supplier-modified', dict( new_idurl=new_idurl, old_idurl=old_idurl, position=position, )) else: lg.out(2, '!!!!!!!!!!! REPLACE EMPTY SUPPLIER %d : %s' % (position, new_idurl)) events.send('supplier-modified', dict( new_idurl=new_idurl, old_idurl=None, position=position, )) self.restart_interval = 1.0
def doUpdate(self, arg): # lg.out(4, 'installer.doUpdate') if not settings.NewWebGUI(): from web import webcontrol reactor.callLater(0, webcontrol.OnUpdateInstallPage) else: from web import control control.request_update([ { 'state': self.state }, ])
def show(): """ Just calls ``p2p.webcontrol.show()`` to open the GUI. """ from main import settings if settings.NewWebGUI(): from web import control control.show() else: from web import webcontrol webcontrol.show() return 0
def state_changed(self, oldstate, newstate, event, arg): if newstate == 'CONTACTS' and oldstate == 'STORAGE': self.event('next', {}) # TODO: # here just skip Contacts page! # we do not need that now, but can back to that soon when add chat if not settings.NewWebGUI(): from web import webcontrol reactor.callLater(0, webcontrol.OnUpdateInstallPage) else: from web import control control.request_update() installer.A('install_wizard.state', newstate)
def shutdown(x=None): """ This is a top level method which control the process of finishing the program. Calls method ``shutdown()`` in other modules. """ lg.out(2, "shutdowner.shutdown " + str(x)) from services import driver from main import settings from main import events from logs import weblog from logs import webtraffic from system import tmpfile from system import run_upnpc from raid import eccmap from lib import net_misc from updates import git_proc from interface import api_jsonrpc_server from interface import api_rest_http_server from interface import ftp_server from userid import my_id from crypt import my_keys dl = [] my_keys.shutdown() my_id.shutdown() ftp_server.shutdown() api_jsonrpc_server.shutdown() api_rest_http_server.shutdown() driver.shutdown() eccmap.shutdown() run_upnpc.shutdown() net_misc.shutdown() git_proc.shutdown() events.clear_subscribers() tmpfile.shutdown() if settings.NewWebGUI(): from web import control dl.append(control.shutdown()) else: from web import webcontrol dl.append(webcontrol.shutdown()) weblog.shutdown() webtraffic.shutdown() for a in automat.objects().values(): if a.name != 'shutdowner': a.event('shutdown') return DeferredList(dl)
def doRemoveSuppliers(self, arg): """ Action method. """ current_suppliers = contactsdb.suppliers() desired_suppliers = settings.getSuppliersNumberDesired() if len(current_suppliers) < desired_suppliers: lg.warn('must have more suppliers %d<%d' % (len(current_suppliers), desired_suppliers)) removed_suppliers = [] for supplier_idurl in self.dismiss_list: if supplier_idurl not in current_suppliers: lg.warn('%s not a supplier' % supplier_idurl) continue pos = current_suppliers.index(supplier_idurl) # current_suppliers.remove(supplier_idurl) current_suppliers[pos] = '' removed_suppliers.append(( pos, supplier_idurl, )) misc.writeSupplierData( supplier_idurl, 'disconnected', time.strftime('%d-%m-%Y %H:%M:%S'), my_id.getLocalID(), ) current_suppliers = current_suppliers[:desired_suppliers] contactsdb.update_suppliers(current_suppliers) contactsdb.save_suppliers() if settings.NewWebGUI(): from web import control control.on_suppliers_changed(current_suppliers) else: from web import webcontrol webcontrol.OnListSuppliers() for position, supplier_idurl in removed_suppliers: events.send( 'supplier-modified', dict( new_idurl=None, old_idurl=supplier_idurl, position=position, )) lg.out(2, '!!!!!!!!!!! REMOVE SUPPLIERS : %d' % len(self.dismiss_list))
def state_changed(self, oldstate, newstate, event, arg): global_state.set_global_state('INSTALL ' + newstate) initializer.A('installer.state', newstate) if not settings.NewWebGUI(): from web import webcontrol reactor.callLater(0, webcontrol.OnUpdateInstallPage)
def main(executable_path=None): """ THIS IS THE ENTRY POINT OF THE PROGRAM! """ global AppDataDir import warnings warnings.filterwarnings("ignore", message="You do not have a working installation of the service_identity module") try: from logs import lg except: dirpath = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path.insert(0, os.path.abspath(os.path.join(dirpath, '..'))) # sys.path.insert(0, os.path.abspath(os.path.join(dirpath, '..', '..'))) from distutils.sysconfig import get_python_lib sys.path.append(os.path.join(get_python_lib(), 'bitdust')) try: from logs import lg except: print 'ERROR! can not import working code. Python Path:' print '\n'.join(sys.path) return 1 # init IO module, update locale from system import bpio bpio.init() # sys.excepthook = lg.exception_hook if not bpio.isFrozen(): try: from twisted.internet.defer import setDebugging setDebugging(True) # from twisted.python import log as twisted_log # twisted_log.startLogging(sys.stdout) except: lg.warn('python-twisted is not installed') pars = parser() (opts, args) = pars.parse_args() if opts.appdir: appdata = opts.appdir AppDataDir = appdata else: curdir = os.getcwd() # os.path.dirname(os.path.abspath(sys.executable)) appdatafile = os.path.join(curdir, 'appdata') defaultappdata = os.path.join(os.path.expanduser('~'), '.bitdust') appdata = defaultappdata if os.path.isfile(appdatafile): try: appdata = os.path.abspath(open(appdatafile, 'rb').read().strip()) except: appdata = defaultappdata if not os.path.isdir(appdata): appdata = defaultappdata AppDataDir = appdata cmd = '' if len(args) > 0: cmd = args[0].lower() # ask to count time for each log line from that moment, not absolute time lg.life_begins() # try to read debug level value at the early stage - no problem if fail here try: if cmd == '' or cmd == 'start' or cmd == 'go' or cmd == 'show' or cmd == 'open': lg.set_debug_level(int( bpio._read_data( os.path.abspath( os.path.join(appdata, 'config', 'logs', 'debug-level'))))) except: pass if opts.no_logs: lg.disable_logs() #---logpath--- logpath = os.path.join(appdata, 'logs', 'start.log') if opts.output: logpath = opts.output need_redirecting = False if bpio.Windows() and not bpio.isConsoled(): need_redirecting = True if logpath != '': lg.open_log_file(logpath) lg.out(2, 'bpmain.main log file opened ' + logpath) if bpio.Windows() and bpio.isFrozen(): need_redirecting = True if need_redirecting: lg.stdout_start_redirecting() lg.out(2, 'bpmain.main redirecting started') # TODO: temporary solution to record run-time errors try: if os.path.isfile(os.path.join(appdata, 'logs', 'exception.log')): os.remove(os.path.join(appdata, 'logs', 'exception.log')) except: pass if opts.debug or str(opts.debug) == '0': lg.set_debug_level(opts.debug) # if opts.quite and not opts.verbose: # lg.disable_output() if opts.verbose: copyright_text() lg.out(2, 'bpmain.main started ' + time.asctime()) overDict = override_options(opts, args) lg.out(2, 'bpmain.main args=%s' % str(args)) #---start--- if cmd == '' or cmd == 'start' or cmd == 'go': appList = bpio.find_main_process(pid_file_path=os.path.join(appdata, 'metadata', 'processid')) if appList: lg.out(0, 'BitDust already started, found another process: %s\n' % str(appList)) bpio.shutdown() return 0 UI = '' # if cmd == 'show' or cmd == 'open': # UI = 'show' try: ret = run(UI, opts, args, overDict, executable_path) except: lg.exc() ret = 1 bpio.shutdown() return ret #---daemon--- elif cmd == 'detach' or cmd == 'daemon' or cmd == 'background': appList = bpio.find_main_process(pid_file_path=os.path.join(appdata, 'metadata', 'processid')) if len(appList) > 0: lg.out(0, 'main BitDust process already started: %s\n' % str(appList)) bpio.shutdown() return 0 from lib import misc lg.out(0, 'new BitDust process will be started in daemon mode, finishing current process\n') bpio.shutdown() result = misc.DoRestart(detach=True) if result is not None: try: result = int(result) except: try: result = result.pid except: pass return 0 #---restart--- elif cmd == 'restart' or cmd == 'reboot': appList = bpio.find_main_process(pid_file_path=os.path.join(appdata, 'metadata', 'processid')) ui = False if len(appList) > 0: lg.out(0, 'found main BitDust process: %s, sending "restart" command ... ' % str(appList), '') def done(x): lg.out(0, 'DONE\n', '') from twisted.internet import reactor if reactor.running and not reactor._stopped: reactor.stop() def failed(x): ok = str(x).count('Connection was closed cleanly') > 0 from twisted.internet import reactor if ok and reactor.running and not reactor._stopped: lg.out(0, 'DONE\n', '') reactor.stop() return lg.out(0, 'FAILED while killing previous process - do HARD restart\n', '') try: kill() except: lg.exc() from lib import misc reactor.addSystemEventTrigger('after', 'shutdown', misc.DoRestart, param='show' if ui else '', detach=True) reactor.stop() try: from twisted.internet import reactor # from interface.command_line import run_url_command # d = run_url_command('?action=restart', False) # from interface import cmd_line # d = cmd_line.call_xmlrpc_method('restart', ui) from interface import cmd_line_json d = cmd_line_json.call_jsonrpc_method('restart', ui) d.addCallback(done) d.addErrback(failed) reactor.run() bpio.shutdown() return 0 except: lg.exc() bpio.shutdown() return 1 else: ui = '' if cmd == 'restart': ui = 'show' try: ret = run(ui, opts, args, overDict, executable_path) except: lg.exc() ret = 1 bpio.shutdown() return ret #---show--- elif cmd == 'show' or cmd == 'open': from main import settings if not bpio.isGUIpossible() and not settings.NewWebGUI(): lg.out(0, 'BitDust GUI is turned OFF\n') bpio.shutdown() return 0 if bpio.Linux() and not bpio.X11_is_running(): lg.out(0, 'this operating system not supported X11 interface\n') bpio.shutdown() return 0 appList = bpio.find_main_process(pid_file_path=os.path.join(appdata, 'metadata', 'processid')) if len(appList) == 0: try: ret = run('show', opts, args, overDict, executable_path) except: lg.exc() ret = 1 bpio.shutdown() return ret lg.out(0, 'found main BitDust process: %s, start the GUI\n' % str(appList)) ret = show() bpio.shutdown() return ret #---stop--- elif cmd == 'stop' or cmd == 'kill' or cmd == 'shutdown': appList = bpio.find_main_process(pid_file_path=os.path.join(appdata, 'metadata', 'processid')) if len(appList) > 0: lg.out(0, 'found main BitDust process: %s, sending command "exit" ... ' % str(appList), '') try: from twisted.internet import reactor # from interface.command_line import run_url_command # url = '?action=exit' # run_url_command(url, False).addBoth(wait_then_kill) # reactor.run() # bpio.shutdown() def _stopped(x): lg.out(0, 'BitDust process finished correctly\n') reactor.stop() bpio.shutdown() # from interface import cmd_line # cmd_line.call_xmlrpc_method('stop').addBoth(_stopped) from interface import cmd_line_json cmd_line_json.call_jsonrpc_method('stop').addBoth(_stopped) reactor.run() return 0 except: lg.exc() ret = kill() bpio.shutdown() return ret else: lg.out(0, 'BitDust is not running at the moment\n') bpio.shutdown() return 0 #---uninstall--- elif cmd == 'uninstall': def do_spawn(x=None): from main.settings import WindowsStarterFileName starter_filepath = os.path.join(bpio.getExecutableDir(), WindowsStarterFileName()) lg.out(0, "bpmain.main bitstarter.exe path: %s " % starter_filepath) if not os.path.isfile(starter_filepath): lg.out(0, "ERROR: %s not found\n" % starter_filepath) bpio.shutdown() return 1 cmdargs = [os.path.basename(starter_filepath), 'uninstall'] lg.out(0, "bpmain.main os.spawnve cmdargs=" + str(cmdargs)) ret = os.spawnve(os.P_DETACH, starter_filepath, cmdargs, os.environ) bpio.shutdown() return ret def do_reactor_stop_and_spawn(x=None): lg.out(0, 'BitDust process finished correctly\n') reactor.stop() ret = do_spawn() bpio.shutdown() return ret lg.out(0, 'bpmain.main UNINSTALL!') if not bpio.Windows(): lg.out(0, 'This command can be used only under OS Windows.\n') bpio.shutdown() return 0 if not bpio.isFrozen(): lg.out(0, 'You are running BitDust from sources, uninstall command is available only for installable version.\n') bpio.shutdown() return 0 appList = bpio.find_process(['bitdust.exe', ]) if len(appList) > 0: lg.out(0, 'found main BitDust process... ', '') try: # from twisted.internet import reactor # from interface.command_line import run_url_command # url = '?action=exit' # run_url_command(url).addBoth(do_reactor_stop_and_spawn) # reactor.run() # bpio.shutdown() # from interface import cmd_line # cmd_line.call_xmlrpc_method('stop').addBoth(do_reactor_stop_and_spawn) from interface import cmd_line_json cmd_line_json.call_jsonrpc_method('stop').addBoth(do_reactor_stop_and_spawn) reactor.run() return 0 except: lg.exc() ret = do_spawn() bpio.shutdown() return ret #---command_line--- # from interface import command_line as cmdln # from interface import cmd_line as cmdln from interface import cmd_line_json as cmdln ret = cmdln.run(opts, args, pars, overDict, executable_path) if ret == 2: print usage_text() bpio.shutdown() return ret