示例#1
0
def kill():
    """
    Kill all running BitDust processes (except current).
    """
    from logs import lg
    from system import bpio
    total_count = 0
    found = False
    while True:
        appList = bpio.find_process([
            'regexp:^.*python.*bitdust.py.*?$',
            'bitdustnode.exe',
            'BitDustNode.exe',
            'bpmain.py',
            'bppipe.py',
            'bptester.py',
        ])
        if len(appList) > 0:
            found = True
        for pid in appList:
            lg.out(0, 'trying to stop pid %d' % pid)
            bpio.kill_process(pid)
        if len(appList) == 0:
            if found:
                lg.out(0, 'BitDust stopped\n')
            else:
                lg.out(0, 'BitDust was not started\n')
            return 0
        total_count += 1
        if total_count > 10:
            lg.out(0, 'some BitDust process found, but can not stop it\n')
            return 1
        time.sleep(1)
示例#2
0
 def _try():
     lg.out(0, '_try')
     appList = bpio.find_process([
         'bitdust.exe',
         'bpgui.exe',
         'bppipe.exe',
         'bptester.exe',
         'bitstarter.exe',
         ])
     lg.out(0, 'appList:' + str(appList))
     if len(appList) == 0:
         lg.out(0, 'finished')
         reactor.stop()
         do_uninstall()
         return 0
     total_count += 1
     lg.out(0, '%d' % total_count)
     if total_count > 10:
         lg.out(0, 'not responding')
         ret = kill()
         reactor.stop()
         if ret == 0:
             do_uninstall()
         return ret
     reactor.callLater(1, _try)
示例#3
0
 def kill():
     lg.out(0, 'kill')
     total_count = 0
     found = False
     while True:
         appList = bpio.find_process([
             'bitdust.exe',
             'bpmain.py',
             'bitdust.py',
             'regexp:^/usr/bin/python.*bitdust.*$',
             'bpgui.exe',
             'bpgui.py',
             'bppipe.exe',
             'bppipe.py',
             'bptester.exe',
             'bptester.py',
             'bitstarter.exe',
             ])
         if len(appList) > 0:
             found = True
         for pid in appList:
             lg.out(0, 'trying to stop pid %d' % pid)
             bpio.kill_process(pid)
         if len(appList) == 0:
             if found:
                 lg.out(0, 'BitDust stopped\n')
             else:
                 lg.out(0, 'BitDust was not started\n')
             return 0
         total_count += 1
         if total_count > 10:
             lg.out(0, 'some BitDust process found, but can not stop it\n')
             return 1
         time.sleep(1)            
示例#4
0
def wait_then_kill(x):
    """
    For correct shutdown of the program need to send a URL request to the HTTP
    server:: http://localhost:<random port>/?action=exit.

    After receiving such request the program will call
    ``p2p.init_shutdown.shutdown()`` method and stops. But if the main
    process was blocked it needs to be killed with system "kill"
    procedure. This method will wait for 10 seconds and then call method
    ``kill()``.
    """
    from twisted.internet import reactor  # @UnresolvedImport
    from logs import lg
    from system import bpio
    total_count = 0
    while True:
        appList = bpio.find_process([
            'regexp:^.*python.*bitdust.py.*?$',
            'bitdustnode.exe',
            'BitDustNode.exe',
            'bpmain.py',
            'bppipe.py',
            'bptester.py',
        ])
        if len(appList) == 0:
            lg.out(0, 'DONE')
            reactor.stop()  # @UndefinedVariable
            return 0
        total_count += 1
        if total_count > 10:
            lg.out(0, 'not responding, KILLING ...')
            ret = kill()
            reactor.stop()  # @UndefinedVariable
            return ret
        time.sleep(1)
示例#5
0
def on_tray_icon_command(cmd):
    from main import shutdowner
    from services import driver
    from p2p import network_connector
    lg.out(2, 'on_tray_icon_command %s' % cmd)
    if cmd == 'exit':
        # SendCommandToGUI('exit')
        shutdowner.A('stop', 'exit')

    elif cmd == 'restart':
        # SendCommandToGUI('exit')
        appList = bpio.find_process(['bpgui.', ])
        if len(appList) > 0:
            shutdowner.A('stop', 'restartnshow')  # ('restart', 'show'))
        else:
            shutdowner.A('stop', 'restart')  # ('restart', ''))

    elif cmd == 'reconnect':
        if driver.is_on('service_network'):
            network_connector.A('reconnect')

    elif cmd == 'show':
        show()

    elif cmd == 'hide':
        pass
        # SendCommandToGUI('exit')

    elif cmd == 'toolbar':
        pass
        # SendCommandToGUI('toolbar')

    else:
        lg.warn('wrong command: ' + str(cmd))
def step1(version_digest):
    lg.out(4, 'os_windows_update.step1')
    global _UpdatingInProgress
    global _CurrentVersionDigest
    global _NewVersionNotifyFunc
    global _UpdatingByUser

    _CurrentVersionDigest = str(version_digest).strip()
    local_checksum = bpio.ReadBinaryFile(settings.CheckSumFile()).strip()
    if local_checksum == _CurrentVersionDigest:
        lg.out(6, 'os_windows_update.step1 no need to update, checksums are equal')
        _UpdatingInProgress = False
        if _NewVersionNotifyFunc is not None:
            _NewVersionNotifyFunc(_CurrentVersionDigest)
        return

    appList = bpio.find_process(['bpgui.', ])
    if len(appList) > 0:
        if not _UpdatingByUser:
            lg.out(6, 'os_windows_update.step1 bpgui is running, ask user to update.')
            _UpdatingInProgress = False
            if _NewVersionNotifyFunc is not None:
                _NewVersionNotifyFunc(_CurrentVersionDigest)
            return

    d = download_info()
    d.addCallback(step2, _CurrentVersionDigest)
    d.addErrback(fail)
示例#7
0
def on_tray_icon_command(cmd):
    from main import shutdowner
    from services import driver
    from p2p import network_connector
    lg.out(2, 'on_tray_icon_command %s' % cmd)
    if cmd == 'exit':
        # SendCommandToGUI('exit')
        shutdowner.A('stop', 'exit')

    elif cmd == 'restart':
        # SendCommandToGUI('exit')
        appList = bpio.find_process(['bpgui.', ])
        if len(appList) > 0:
            shutdowner.A('stop', 'restartnshow')  # ('restart', 'show'))
        else:
            shutdowner.A('stop', 'restart')  # ('restart', ''))

    elif cmd == 'reconnect':
        if driver.is_started('service_network'):
            network_connector.A('reconnect')

    elif cmd == 'show':
        show()

    elif cmd == 'hide':
        pass
        # SendCommandToGUI('exit')

    elif cmd == 'toolbar':
        pass
        # SendCommandToGUI('toolbar')

    else:
        lg.warn('wrong command: ' + str(cmd))
示例#8
0
def step1(version_digest):
    lg.out(4, 'os_windows_update.step1')
    global _UpdatingInProgress
    global _CurrentVersionDigest
    global _NewVersionNotifyFunc
    global _UpdatingByUser

    _CurrentVersionDigest = str(version_digest).strip()
    local_checksum = bpio.ReadBinaryFile(settings.CheckSumFile()).strip()
    if local_checksum == _CurrentVersionDigest:
        lg.out(
            6,
            'os_windows_update.step1 no need to update, checksums are equal')
        _UpdatingInProgress = False
        if _NewVersionNotifyFunc is not None:
            _NewVersionNotifyFunc(_CurrentVersionDigest)
        return

    appList = bpio.find_process([
        'bpgui.',
    ])
    if len(appList) > 0:
        if not _UpdatingByUser:
            lg.out(
                6,
                'os_windows_update.step1 bpgui is running, ask user to update.'
            )
            _UpdatingInProgress = False
            if _NewVersionNotifyFunc is not None:
                _NewVersionNotifyFunc(_CurrentVersionDigest)
            return

    d = download_info()
    d.addCallback(step2, _CurrentVersionDigest)
    d.addErrback(fail)
示例#9
0
def kill_child(child_name):
    """
    Search (by "pid") for BitDust child process with name ``child_name`` and
    tries to kill it.
    """
    killed = False
    for pid in bpio.find_process([child_name + '.']):
        bpio.kill_process(pid)
        lg.out(6, 'child_process.kill_child pid %d' % pid)
        killed = True
    return killed
示例#10
0
def wait_then_kill(x):
    """
    For correct shutdown of the program need to send a URL request to the HTTP
    server:: http://localhost:<random port>/?action=exit.

    After receiving such request the program will call
    ``p2p.init_shutdown.shutdown()`` method and stops. But if the main
    process was blocked it needs to be killed with system "kill"
    procedure. This method will wait for 10 seconds and then call method
    ``kill()``.
    """
    import time
    from twisted.internet import reactor
    from logs import lg
    from system import bpio
    total_count = 0
    while True:
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
            'bpgui.exe',
            'bpgui.py',
            'bppipe.exe',
            'bppipe.py',
            'bptester.exe',
            'bptester.py',
            'bitstarter.exe',
        ])
        if len(appList) == 0:
            print_text('DONE')
            reactor.stop()
            return 0
        total_count += 1
        if total_count > 10:
            print_text('not responding, KILLING ...')
            ret = kill()
            reactor.stop()
            return ret
        time.sleep(1)
示例#11
0
def kill():
    """
    Kill all running BitDust processes (except current).
    """
    import time
    from system import bpio
    total_count = 0
    found = False
    while True:
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
            'bpgui.exe',
            'bpgui.py',
            'bppipe.exe',
            'bppipe.py',
            'bptester.exe',
            'bptester.py',
            'bitstarter.exe',
        ])
        if len(appList) > 0:
            found = True
        for pid in appList:
            print_text('trying to stop pid %d' % pid)
            bpio.kill_process(pid)
        if len(appList) == 0:
            if found:
                print_text('BitDust stopped\n')
            else:
                print_text('BitDust was not started\n')
            return 0
        total_count += 1
        if total_count > 10:
            print_text('some BitDust process found, but can not stop it\n')
            return 1
        time.sleep(1)
示例#12
0
def run(opts, args, pars=None, overDict=None): 
    cmd = ''
    if len(args) > 0:
        cmd = args[0].lower()

    from system import bpio
    bpio.init()

    #---start---
    if cmd == '' or cmd == 'start' or cmd == 'go' or cmd == 'run':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
            ])
        if len(appList) > 0:
            print_text('BitDust already started, found another process: %s' % str(appList))
            return 0
        return run_now(opts, args)

    #---detach---
    elif cmd == 'detach':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
            ])
        if len(appList) > 0:
            print_text('main BitDust process already started: %s' % str(appList))
            return 0
        from lib import misc
        print_text('run and detach main BitDust process')
        result = misc.DoRestart(detach=True)
        try:
            result = result.pid
        except:
            pass
        print_text(result)
        return 0

    #---restart---
    elif cmd == 'restart':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
            ])
        if len(appList) == 0:
            return run_now()
        print_text('found main BitDust process: %s, sending "restart" command ... ' % str(appList), '')
        def done(x):
            print_text('DONE\n', '')
            from twisted.internet import reactor
            if reactor.running and not reactor._stopped:
                reactor.stop()
        def failed(x):
            print_text('FAILED, killing previous process and do restart\n', '')
            try:
                kill()
            except:
                print_exception()
            from twisted.internet import reactor
            from lib import misc
            reactor.addSystemEventTrigger('after','shutdown', misc.DoRestart)
            reactor.stop()
        try:
            from twisted.internet import reactor
            call_xmlrpc_method('restart').addCallbacks(done, failed)
            reactor.run()
        except:
            print_exception()
            return 1
        return 0

    #---show---
    elif cmd == 'show' or cmd == 'open':
        appList_bpgui = bpio.find_process([
            'bpgui.exe',
            'bpgui.py',
            ])
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
            ])
        if len(appList_bpgui) > 0:
            if len(appList) == 0:
                for pid in appList_bpgui:
                    bpio.kill_process(pid)
            else:
                print_text('BitDust GUI already opened, found another process: %s' % str(appList))
                return 0
        if len(appList) == 0:
            from lib import misc
            print_text('run and detach main BitDust process')
            result = misc.DoRestart('show', detach=True)
            try:
                result = result.pid
            except:
                pass
            print_text(result)
            return 0
        print_text('found main BitDust process: %s, sending command "show" to start the GUI\n' % str(appList))
        call_xmlrpc_method('show')
        return 0

    #---stop---
    elif cmd == 'stop' or cmd == 'kill' or cmd == 'shutdown':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
            ])
        if len(appList) > 0:
            print_text('found main BitDust process: %s, sending command "exit"' % str(appList))
            try:
                from twisted.internet import reactor
                call_xmlrpc_method('stop').addBoth(wait_then_kill)
                reactor.run()
                return 0
            except:
                print_exception()
                ret = kill()
                return ret
        else:
            print_text('BitDust is not running at the moment')
            return 0

    #---help---
    elif cmd in ['help', 'h', 'hlp', '?']:
        from main import help
        if len(args) >= 2 and args[1].lower() == 'schedule':
            print_text(help.schedule_format())
        elif len(args) >= 2 and args[1].lower() == 'settings':
            # from main import settings
            # settings.uconfig().print_all()
            from main import config
            for k in config.conf().listAllEntries():
                print k, config.conf().getData(k)
        else:
            print_text(help.help())
            print_text(pars.format_option_help())
        return 0

    appList = bpio.find_process([
        'bitdust.exe',
        'bpmain.py',
        'bitdust.py',
        'regexp:^/usr/bin/python.*bitdust.*$',
        ])
    running = len(appList) > 0
    overDict = override_options(opts, args)

    #---set---
#    if cmd == 'set':
#        if len(args) == 1 or args[1].lower() in [ 'help', '?' ]:
#            from main import help
#            print_text(help.settings_help())
#            return 0
#        if not running:
#            cmd_set_directly(opts, args, overDict)
#            return 0
#        return cmd_set_request(opts, args, overDict)
    
    #---backup---
    if cmd in ['backup', 'backups', 'bk']:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_backups(opts, args, overDict)

    #---restore---
    elif cmd in ['restore', 're']:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_restore(opts, args, overDict)

    #---messages---
    elif cmd == 'msg' or cmd == 'message' or cmd == 'messages':
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_message(opts, args, overDict)
    
    #---friends---
    elif cmd == 'friend' or cmd == 'friends' or cmd == 'buddy':
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_friend(opts, args, overDict)

    #---integrate---
    elif cmd == 'integrate':
        return cmd_integrate(opts, args, overDict)

    #---schedule---
    elif cmd in ['schedule', 'shed', 'sched', 'sh']:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_schedule(opts, args, overDict)



    #---suppliers---
#    elif cmd in [ 'suppliers', 'supplier', 'sup', 'supp', 'sp', ]:
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_suppliers(opts, args, overDict)
    
    #---customers---
#    elif cmd in [ 'customers', 'customer', 'cus', 'cust', 'cs', ]:
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_customers(opts, args, overDict)

    #---register---
#    elif cmd == 'register':
#        if running:
#            print_text('BitDust already started.\n')
#            return 0
#        return cmd_register(opts, args, overDict)

    #---recover---
#    elif cmd == 'recover':
#        if running:
#            print_text('BitDust already started.\n')
#            return 0
#        return cmd_recover(opts, args, overDict)

    #---key---
#    elif cmd == 'key':
#        return cmd_key(opts, args, overDict)

    #---stats---
#    elif cmd in [ 'stats', 'st' ]:
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_stats(opts, args, overDict)

    #---version---
    elif cmd in [ 'version', 'v', 'ver' ]:
        from main import settings
        ver = bpio.ReadTextFile(settings.VersionNumberFile()).strip()
        chksum = bpio.ReadTextFile(settings.CheckSumFile()).strip()
        repo, location = misc.ReadRepoLocation()
        print_text('checksum:   %s' % chksum )
        print_text('version:    %s' % ver)
        print_text('repository: %s' % repo)
        print_text('location:   %s' % location)
        return 0

    #---states---
#    elif cmd in [ 'states', 'sta', 'automats', 'auto' ]:
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_states(opts, args, overDict)
    
    #---cache---
#    elif cmd in [ 'cache' ]:
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_cache(opts, args, overDict)

    #---reconnect---
#    elif cmd in [ 'reconnect', ]:
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_reconnect(opts, args, overDict)
        
    #---memory---
#    elif cmd == 'memory':
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_memory(opts, args, overDict)
    
    #---money---
#    elif cmd == 'money':
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_money(opts, args, overDict)
    
#    elif cmd == 'storage':
#        if not running:
#            print_text('BitDust is not running at the moment\n')
#            return 0
#        return cmd_storage(opts, args, overDict)
    
   
#    elif cmd == 'uninstall':
#        return cmd_uninstall(opts, args, overDict)
    
    return 2
示例#13
0
def cmd_uninstall(opts, args, overDict):
    if not bpio.Windows():
        print 'This command can be used only under OS Windows.'
        return 0
    if not bpio.isFrozen():
        print 'You are running BitDust from sources, uninstall command is available only for binary version.'
        return 0
    def do_uninstall():
        lg.out(0, 'command_line.do_uninstall')
        # batfilename = misc.MakeBatFileToUninstall()
        # misc.UpdateRegistryUninstall(True)
        # misc.RunBatFile(batfilename, 'c:/out2.txt')
    def kill():
        lg.out(0, 'kill')
        total_count = 0
        found = False
        while True:
            appList = bpio.find_process([
                'bitdust.exe',
                'bpmain.py',
                'bitdust.py',
                'regexp:^/usr/bin/python.*bitdust.*$',
                'bpgui.exe',
                'bpgui.py',
                'bppipe.exe',
                'bppipe.py',
                'bptester.exe',
                'bptester.py',
                'bitstarter.exe',
                ])
            if len(appList) > 0:
                found = True
            for pid in appList:
                lg.out(0, 'trying to stop pid %d' % pid)
                bpio.kill_process(pid)
            if len(appList) == 0:
                if found:
                    lg.out(0, 'BitDust stopped\n')
                else:
                    lg.out(0, 'BitDust was not started\n')
                return 0
            total_count += 1
            if total_count > 10:
                lg.out(0, 'some BitDust process found, but can not stop it\n')
                return 1
            time.sleep(1)            
    def wait_then_kill(x):
        lg.out(0, 'wait_then_kill')
        total_count = 0
        #while True:
        def _try():
            lg.out(0, '_try')
            appList = bpio.find_process([
                'bitdust.exe',
                'bpgui.exe',
                'bppipe.exe',
                'bptester.exe',
                'bitstarter.exe',
                ])
            lg.out(0, 'appList:' + str(appList))
            if len(appList) == 0:
                lg.out(0, 'finished')
                reactor.stop()
                do_uninstall()
                return 0
            total_count += 1
            lg.out(0, '%d' % total_count)
            if total_count > 10:
                lg.out(0, 'not responding')
                ret = kill()
                reactor.stop()
                if ret == 0:
                    do_uninstall()
                return ret
            reactor.callLater(1, _try)
        _try()
#            time.sleep(1)
    appList = bpio.find_process([
        'bitdust.exe',
        'bpgui.exe',
        'bppipe.exe',
        'bptester.exe',
        'bitstarter.exe',
        ])
    if len(appList) == 0:
        lg.out(0, 'uninstalling BitDust ...   ')
        do_uninstall()
        return 0
    lg.out(0, 'found BitDust processes ...   ')
    try:
        url = webcontrol._PAGE_ROOT+'?action=exit'
        run_url_command(url).addCallback(wait_then_kill)
        #reactor.addSystemEventTrigger('before', 'shutdown', do_uninstall)
        reactor.run()
        return 0
    except:
        lg.exc()
        ret = kill()
        if ret == 0:
            do_uninstall()
        return ret
示例#14
0
def run(opts, args, overDict, pars):
    """
    The entry point, this is called from ``p2p.bpmain`` to process command line arguments.
    """
    print 'Copyright 2014, BitDust. All rights reserved.'
    
    if overDict:
        settings.override_dict(overDict)
    bpio.init()
    settings.init()
    if not opts or opts.debug is None:
        lg.set_debug_level(0)

    appList = bpio.find_process([
        'bitdust.exe',
        'bpmain.py',
        'bitdust.py',
        'regexp:^/usr/bin/python.*bitdust.*$',
        ])
    running = len(appList) > 0
   
    cmd = ''
    if len(args) > 0:
        cmd = args[0].lower()
    
    #---help---
    if cmd in ['help', 'h']:
        from main import help
        if len(args) >= 2 and args[1].lower() == 'schedule':
            print help.schedule_format()
        elif len(args) >= 2 and args[1].lower() == 'settings':
            print config.conf().print_all()
        else:
            print help.help()
            print pars.format_option_help()
        return 0
    
    #---backup---
    elif cmd in ['backup', 'backups', 'bk']:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_backups(opts, args, overDict)

    #---restore---
    elif cmd in ['restore', 're']:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_restore(opts, args, overDict)

    #---schedule---
    elif cmd in ['schedule', 'shed', 'sched', 'sh']:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_schedule(opts, args, overDict)

    #---suppliers---
    elif cmd in [ 'suppliers', 'supplier', 'sup', 'supp', 'sp', ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_suppliers(opts, args, overDict)
    
    #---customers---
    elif cmd in [ 'customers', 'customer', 'cus', 'cust', 'cs', ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_customers(opts, args, overDict)

    #---register---
    elif cmd == 'register':
        if running:
            print 'BitDust already started.\n'
            return 0
        return cmd_register(opts, args, overDict)

    #---recover---
    elif cmd == 'recover':
        if running:
            print 'BitDust already started.\n'
            return 0
        return cmd_recover(opts, args, overDict)

    #---key---
    elif cmd == 'key':
        return cmd_key(opts, args, overDict)

    #---stats---
    elif cmd in [ 'stats', 'st' ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_stats(opts, args, overDict)

    #---version---
    elif cmd in [ 'version', 'v', 'ver' ]:
        ver = bpio.ReadTextFile(settings.VersionNumberFile()).strip()
        chksum = bpio.ReadTextFile(settings.CheckSumFile()).strip()
        repo, location = misc.ReadRepoLocation()
        print 'checksum:   ', chksum 
        print 'version:    ', ver
        print 'repository: ', repo
        print 'location:   ', location
        return 0

    #---states---
    elif cmd in [ 'states', 'sta', 'automats', 'auto' ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_states(opts, args, overDict)
    
    #---cache---
    elif cmd in [ 'cache' ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_cache(opts, args, overDict)

    #---reconnect---
    elif cmd in [ 'reconnect', ]:
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_reconnect(opts, args, overDict)
        
    #---set---
    elif cmd in [ 'set', 'setting', 'settings', 'conf', 'config', 'configs', 'option', 'options', ]:
        if len(args) == 1 or args[1].lower() in [ 'help', '?' ]:
            from main import help
            print help.settings_help()
            return 0
        if not running:
            cmd_set_directly(opts, args, overDict)
            return 0
        return cmd_set_request(opts, args, overDict)
    
    #---memory---
    elif cmd == 'memory':
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_memory(opts, args, overDict)
    
    #---money---
    elif cmd == 'money':
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_money(opts, args, overDict)

    #---storage---
    elif cmd == 'storage':
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_storage(opts, args, overDict)
    
    #---message---
    elif cmd == 'msg' or cmd == 'message' or cmd == 'messages':
        if not running:
            print 'BitDust is not running at the moment\n'
            return 0
        return cmd_message(opts, args, overDict)

    #---integrate---
    elif cmd == 'integrate':
        return cmd_integrate(opts, args, overDict)
    
#    elif cmd == 'uninstall':
#        return cmd_uninstall(opts, args, overDict)
    
    return 2
示例#15
0
def run(opts, args, pars=None, overDict=None, executablePath=None):
    cmd = ''
    if len(args) > 0:
        cmd = args[0].lower()

    from system import bpio
    bpio.init()

    #---start---
    if cmd == '' or cmd == 'start' or cmd == 'go' or cmd == 'run':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
        ])
        if len(appList) > 0:
            print_text('BitDust already started, found another process: %s' % str(appList))
            return 0
        return run_now(opts, args)

    #---detach---
    elif cmd == 'detach':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
        ])
        if len(appList) > 0:
            print_text('main BitDust process already started: %s' % str(appList))
            return 0
        from lib import misc
        print_text('run and detach main BitDust process')
        result = misc.DoRestart(detach=True)
        try:
            result = result.pid
        except:
            pass
        print_text(result)
        return 0

    #---restart---
    elif cmd == 'restart' or cmd == 'reboot':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
        ])
        if len(appList) == 0:
            return run_now(opts, args)
        ui = False
        if cmd == 'restart':
            ui = True
        print_text('found main BitDust process: %s, sending "restart" command' % str(appList))

        def done(x):
            print_text('DONE\n', '')
            from twisted.internet import reactor
            if reactor.running and not reactor._stopped:
                reactor.stop()

        def failed(x):
            print_text('soft restart FAILED, now killing previous process and do restart')
            try:
                kill()
            except:
                print_exception()
            from twisted.internet import reactor
            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
            call_jsonrpc_method('restart', ui).addCallbacks(done, failed)
            reactor.run()
        except:
            print_exception()
            return 1
        return 0

    #---show---
    elif cmd == 'show' or cmd == 'open':
        appList_bpgui = bpio.find_process([
            'bpgui.exe',
            'bpgui.py',
        ])
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
        ])
        if len(appList_bpgui) > 0:
            if len(appList) == 0:
                for pid in appList_bpgui:
                    bpio.kill_process(pid)
            else:
                print_text('BitDust GUI already opened, found another process: %s' % str(appList))
                return 0
        if len(appList) == 0:
            from lib import misc
            print_text('run and detach main BitDust process')
            result = misc.DoRestart('show', detach=True)
            try:
                result = result.pid
            except:
                pass
            print_text(result)
            return 0
        print_text('found main BitDust process: %s, sending command "show" to start the GUI\n' % str(appList))
        call_jsonrpc_method('show')
        return 0

    #---stop---
    elif cmd == 'stop' or cmd == 'kill' or cmd == 'shutdown':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python.*bitdust.*$',
        ])
        if len(appList) > 0:
            print_text('found main BitDust process: %s, sending command "exit" ... ' % str(appList), '')
            try:
                from twisted.internet import reactor
                call_jsonrpc_method('stop').addBoth(wait_then_kill)
                reactor.run()
                return 0
            except:
                print_exception()
                ret = kill()
                return ret
        else:
            print_text('BitDust is not running at the moment')
            return 0

    #---help---
    elif cmd in ['help', 'h', 'hlp', '?']:
        from main import help
        if len(args) >= 2 and args[1].lower() == 'schedule':
            print_text(help.schedule_format())
        elif len(args) >= 2 and args[1].lower() == 'settings':
            # from main import settings
            # settings.uconfig().print_all()
            from main import config
            for k in config.conf().listAllEntries():
                print k, config.conf().getData(k)
        else:
            print_text(help.help())
            print_text(pars.format_option_help())
        return 0

    appList = bpio.find_process([
        'bitdust.exe',
        'bpmain.py',
        'bitdust.py',
        'regexp:^/usr/bin/python.*bitdust.*$',
    ])
    running = len(appList) > 0
    overDict = override_options(opts, args)

    #---identity---
    if cmd in ['identity', 'id', 'idurl', ]:
        return cmd_identity(opts, args, overDict, running)

    #---key---
    elif cmd == 'key':
        return cmd_key(opts, args, overDict, running, executablePath)

    #---ping---
    if cmd == 'ping' or cmd == 'call' or cmd == 'sendid':
        if len(args) < 1:
            return 2
        tpl = jsontemplate.Template(templ.TPL_RAW)
        return call_jsonrpc_method_template_and_stop('ping', tpl, args[1])

    #---set---
    elif cmd in ['set', 'get', 'conf', 'config', 'option', 'setting', ]:
        if len(args) == 1 or args[1].lower() in ['help', '?']:
            from main import help
            print_text(help.settings_help())
            return 0
        if not running:
            return cmd_set(opts, args, overDict)
        return cmd_set_request(opts, args, overDict)

    #---reconnect---
    if cmd in ['reconnect', 'rejoin', 'connect', ]:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_reconnect(opts, args, overDict)

    #---api---
    elif cmd in ['api', 'call', ]:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_api(opts, args, overDict, executablePath)

    #---messages---
    elif cmd in ['msg', 'message', 'messages', 'chat', 'talk', ]:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_message(opts, args, overDict)

    #---suppliers---
    elif cmd in ['suppliers', 'supplier', 'sup', 'supp', 'sp']:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_suppliers(opts, args, overDict)

    #---customers---
    elif cmd in ['customers', 'customer', 'cus', 'cust', 'cu']:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_customers(opts, args, overDict)

    #---storage---
    elif cmd in ['storage', 'space']:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_storage(opts, args, overDict)

    #---automats---
    elif cmd in ['automats', 'aut', 'states', 'machines', ]:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_automats(opts, args, overDict)

    #---services---
    elif cmd in ['services', 'service', 'svc', 'serv', 'srv', ]:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_services(opts, args, overDict)

    #---friends---
    elif cmd == 'friend' or cmd == 'friends' or cmd == 'buddy' or cmd == 'correspondent' or cmd == 'contact' or cmd == 'peer':
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_friend(opts, args, overDict)

    #---backup---
    elif cmd in ['file', 'files', 'fi', 'fs', 'backup', 'backups', 'bk', 'up', 'upload', 'uploads', ]:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_backup(opts, args, overDict, executablePath)

    #---restore---
    elif cmd in ['restore', 'rest', 'download', 'down', ]:
        if not running:
            print_text('BitDust is not running at the moment\n')
            return 0
        return cmd_restore(opts, args, overDict, executablePath)

    #---version---
    elif cmd in ['version', 'v', 'ver']:
        from main import settings
        from lib import misc
        ver = bpio.ReadTextFile(settings.VersionNumberFile()).strip()
        chksum = bpio.ReadTextFile(settings.CheckSumFile()).strip()
        repo, location = misc.ReadRepoLocation()
        print_text('checksum:   %s' % chksum)
        print_text('version:    %s' % ver)
        print_text('repository: %s' % repo)
        print_text('location:   %s' % location)
        return 0

    #---integrate---
    elif cmd == 'integrate' or cmd == 'alias' or cmd == 'shell':
        return cmd_integrate(opts, args, overDict)

    return 2
示例#16
0
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():
        from twisted.internet.defer import setDebugging
        setDebugging(True)

    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')

    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()

    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_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])

        # this is extra protection for Debian release
        # I am not sure how process name can looks on different systems
        # check the process ID from previous start
        # it file exists and we found this PID in the currently running apps - BitDust is working
        # if file not exists we don't want to start if found some other jobs with same name
#        pid = -1
#        try:
#            if bpio.Windows():
#                _data_path = os.path.join(os.environ.get('APPDATA', os.path.join(os.path.expanduser('~'), 'Application Data')), 'BitDust')
#                pid_path = os.path.join(_data_path, 'metadata', 'processid')
#            else:
#                pid_path = os.path.join(appdata, 'metadata', 'processid')
#            if os.path.isfile(pid_path):
#                pid = int(bpio.ReadBinaryFile(pid_path).strip())
#        except:
#            lg.exc()

        if len(appList) > 0:
            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

    #---detach---
    elif cmd == 'detach' or cmd == 'daemon' or cmd == 'background':
        # lg.set_debug_level(20)
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])
        if len(appList) > 0:
            lg.out(0, 'main BitDust process already started: %s\n' % str(appList))
            bpio.shutdown()
            return 0
        from lib import misc
        # from twisted.internet import reactor
        # def _detach():
        #     result = misc.DoRestart(detach=True)
        #     lg.out(0, 'run and detach main BitDust process: %s' % str(result))
        #     reactor.callLater(2, reactor.stop)
        # reactor.addSystemEventTrigger('after','shutdown', misc.DoRestart, detach=True)
        # reactor.callLater(0.01, _detach)
        # reactor.run()
        lg.out(0, 'main BitDust process started in daemon mode\n')
        bpio.shutdown()
        result = misc.DoRestart(detach=True)
        try:
            result = result.pid
        except:
            pass
        return 0

    #---restart---
    elif cmd == 'restart' or cmd == 'reboot':
        appList = bpio.find_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])
        ui = False
        # if cmd == 'restart':
        # ui = True
        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_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])
        if not settings.NewWebGUI():
            appList_bpgui = bpio.find_process([
                'bpgui.exe',
                'bpgui.py',
            ])
            if len(appList_bpgui) > 0:
                if len(appList) == 0:
                    for pid in appList_bpgui:
                        bpio.kill_process(pid)
                else:
                    lg.out(0, 'BitDust GUI already opened, found another process: %s\n' % str(appList))
                    bpio.shutdown()
                    return 0
        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_process([
            'bitdust.exe',
            'bpmain.py',
            'bitdust.py',
            'regexp:^/usr/bin/python\ +/usr/bin/bitdust.*$',
        ])
        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()
    bpio.shutdown()
    return ret
示例#17
0
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