Esempio n. 1
0
def sync(callback_func=None, update_method='rebase'):
    """
    Runs commands and process stdout and stderr to recogneze the result:

        `git fetch --all -v`
        `git rebase origin/master -v`  or  `git reset --hard origin/master`

    """
    src_dir_path = bpio.getExecutableDir()
    expected_src_dir = os.path.join(deploy.default_base_dir_portable(), 'src')
    if bpio.portablePath(src_dir_path) != bpio.portablePath(expected_src_dir):
        if _Debug:
            lg.out(_DebugLevel, 'git_proc.sync SKIP, non standard sources location: %r' % src_dir_path)
        return

    def _reset_done(response, error, retcode, result):
        if callback_func is None:
            return
        callback_func(result)

    def _rebase_done(response, error, retcode, result):
        if callback_func is None:
            return
        if retcode != 0:
            result = 'sync-error'
        else:
            if response.count(b'Changes from') or response.count(b'Fast-forwarded'):
                result = 'code-fetched'
            else:
                result = 'up-to-date'
        callback_func(result)

    def _fetch_done(response, error, retcode):
        if retcode != 0:
            if callback_func:
                callback_func('sync-error')
            return
        result = 'sync-error'
        if response.count(b'Unpacking') or \
            (response.count(b'master') and response.count(b'->')) or \
            response.count(b'Updating') or \
            response.count(b'Receiving') or \
                response.count(b'Counting'):
            result = 'new-code'
        if update_method == 'reset':
            run(['reset', '--hard', 'origin/master', ],
                callback=lambda resp, err, ret: _reset_done(resp, err, ret, result))
        elif update_method == 'rebase':
            run(['rebase', 'origin/master', '-v'],
                callback=lambda resp, err, ret: _rebase_done(resp, err, ret, result))
        else:
            raise Exception('invalid update method: %s' % update_method)

    run(['fetch', '--all', '-v'], callback=_fetch_done)
Esempio n. 2
0
 def listAllEntries(self):
     try:
         from system import bpio
         l = []
         abspth = bpio.portablePath(os.path.abspath(self.getConfigDir()))
         for subpath in bpio.list_dir_recursive(abspth):
             path = bpio.portablePath(subpath)
             l.append(path.replace(abspth, '').strip('/'))
         return l
     except:
         lg.exc()
         return []
Esempio n. 3
0
 def listAllEntries(self):
     try:
         from system import bpio
         l = []
         abspth = bpio.portablePath(os.path.abspath(self.getConfigDir()))
         for subpath in bpio.list_dir_recursive(abspth):
             path = bpio.portablePath(subpath)
             l.append(path.replace(abspth, '').strip('/'))
         return l
     except:
         lg.exc()
         return []
Esempio n. 4
0
def _download(params):
    # localName = params['name']
    backupID = global_id.CanonicalID(params['backupid'])
    destpath = params['dest_path']
    if bpio.Linux() or bpio.Mac():
        destpath = '/' + destpath.lstrip('/')
    restorePath = bpio.portablePath(destpath)
    # overwrite = params['overwrite']
    customerGlobalID, remotePath, version = packetid.SplitBackupID(backupID)
    pathID = packetid.MakeBackupID(customerGlobalID, remotePath)
    if not customerGlobalID:
        customerGlobalID = my_id.getGlobalID()
    if not packetid.IsCanonicalVersion(version):
        return {'result': {"success": False, "error": "path %s is not valid" % backupID}}
    if not remotePath:
        return {'result': {"success": False, "error": "path %s is not valid" % backupID}}
    if not packetid.Valid(remotePath):
        return {'result': {"success": False, "error": "path %s is not valid" % backupID}}
    if backup_control.IsBackupInProcess(backupID):
        return {'result': {"success": True, "error": None}}
    if backup_control.HasTask(pathID):
        return {'result': {"success": True, "error": None}}
    localPath = backup_fs.ToPath(remotePath)
    if localPath == restorePath:
        restorePath = os.path.dirname(restorePath)

    def _itemRestored(backupID, result):
        customerGlobalID, remotePath, _ = packetid.SplitBackupID(backupID)
        backup_fs.ScanID(remotePath, customer_idurl=global_id.GlobalUserToIDURL(customerGlobalID))
        backup_fs.Calculate()

    restore_monitor.Start(backupID, restorePath, callback=_itemRestored)
    return {'result': {"success": True, "error": None}}
Esempio n. 5
0
def saveLocalIdentity():
    """
    Save identity object from memory into local file.

    Do sign the identity than serialize to write to the file.
    """
    global _LocalIdentity
    if not isLocalIdentityReady():
        lg.warn("ERROR local identity not exist!")
        return False
    if not _LocalIdentity.isCorrect():
        lg.warn('local identity is not correct')
        return False
    _LocalIdentity.sign()
    if not _LocalIdentity.Valid():
        lg.err('local identity is not valid')
        return False
    xmlid = _LocalIdentity.serialize(as_text=True)
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    bpio.WriteTextFile(filename, xmlid)
    setTransportOrder(getOrderFromContacts(_LocalIdentity))
    events.send('local-identity-written', data=dict(idurl=_LocalIdentity.getIDURL(), filename=filename))
    if _Debug:
        lg.out(_DebugLevel, "my_id.saveLocalIdentity %d bytes wrote to %s" % (len(xmlid), filename))
    return True
Esempio n. 6
0
def loadLocalIdentity():
    """
    The core method.

    The file [BitDust data dir]/metadata/localidentity keeps the user
    identity in XML format. Do read the local file and set into object
    in memory.
    """
    global _LocalIdentity
    xmlid = ''
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    if os.path.exists(filename):
        xmlid = bpio.ReadTextFile(filename)
        if _Debug:
            lg.out(_DebugLevel, 'my_id.loadLocalIdentity %d bytes read from %s' % (len(xmlid), filename))
    if not xmlid:
        if _Debug:
            lg.out(_DebugLevel, "my_id.loadLocalIdentity SKIPPED, local identity in %s is EMPTY !!!" % filename)
        return False
    lid = identity.identity(xmlsrc=xmlid)
    if not lid.isCorrect():
        if _Debug:
            lg.out(_DebugLevel, "my_id.loadLocalIdentity ERROR loaded identity is not Correct")
        return False
    if not lid.Valid():
        if _Debug:
            lg.out(_DebugLevel, "my_id.loadLocalIdentity ERROR loaded identity is not Valid")
        return False
    setLocalIdentity(lid)
    setTransportOrder(getOrderFromContacts(_LocalIdentity))
    if _Debug:
        lg.out(_DebugLevel, "my_id.loadLocalIdentity my global id is %s" % getGlobalID())
    return True
Esempio n. 7
0
def run(cmdargs, base_dir=None, git_bin=None, env=None, callback=None):
    """
    """
    if _Debug:
        lg.out(_DebugLevel, 'git_proc.run')
    base_dir = base_dir or bpio.getExecutableDir()
    if bpio.Windows():
        cmd = ['git', ] + cmdargs
        if git_bin:
            git_exe = git_bin
        else:
            git_exe = bpio.portablePath(os.path.join(base_dir, '..', 'git', 'bin', 'git.exe'))
        if not os.path.isfile(git_exe):
            if _Debug:
                lg.out(_DebugLevel, '    not found git.exe, try to run from shell')
            try:
                response, error, retcode = execute_in_shell(cmd, base_dir=base_dir)
            except:
                response = ''
                error = ''
                retcode = 1
            if callback:
                callback(response, error, retcode)
            return
        if _Debug:
            lg.out(_DebugLevel, '    found git in %s' % git_exe)
        cmd = [git_exe, ] + cmdargs
    else:
        cmd = [git_bin or 'git', ] + cmdargs
    execute(cmd, callback=callback, base_dir=base_dir, env=env)
Esempio n. 8
0
def _download(params):
    # localName = params['name']
    backupID = params['backupid']
    destpath = params['dest_path']
    if bpio.Linux() or bpio.Mac():
        destpath = '/' + destpath.lstrip('/')
    restorePath = bpio.portablePath(destpath)
    # overwrite = params['overwrite']
    if not packetid.Valid(backupID):
        return {'result': {"success": False, "error": "path %s is not valid" % backupID}}
    pathID, version = packetid.SplitBackupID(backupID)
    if not pathID:
        return {'result': {"success": False, "error": "path %s is not valid" % backupID}}
    if backup_control.IsBackupInProcess(backupID):
        return {'result': {"success": True, "error": None}}
    if backup_control.HasTask(pathID):
        return {'result': {"success": True, "error": None}}
    localPath = backup_fs.ToPath(pathID)
    if localPath == restorePath:
        restorePath = os.path.dirname(restorePath)

    def _itemRestored(backupID, result):
        backup_fs.ScanID(packetid.SplitBackupID(backupID)[0])
        backup_fs.Calculate()
    restore_monitor.Start(backupID, restorePath, _itemRestored)
    return {'result': {"success": True, "error": None}}
Esempio n. 9
0
def loadLocalIdentity():
    """
    The core method.

    The file [BitDust data dir]/metadata/localidentity keeps the user
    identity in XML format. Do read the local file and set into object
    in memory.
    """
    global _LocalIdentity
    global _LocalIDURL
    global _LocalName
    xmlid = ''
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    if os.path.exists(filename):
        xmlid = bpio.ReadTextFile(filename)
        lg.out(6, 'my_id.loadLocalIdentity %d bytes read from\n        %s' % (len(xmlid), filename))
    if xmlid == '':
        lg.out(2, "my_id.loadLocalIdentity SKIPPED, local identity in %s is EMPTY !!!" % filename)
        return
    lid = identity.identity(xmlsrc=xmlid)
    if not lid.isCorrect():
        lg.out(2, "my_id.loadLocalIdentity ERROR loaded identity is not Correct")
        return
    if not lid.Valid():
        lg.out(2, "my_id.loadLocalIdentity ERROR loaded identity is not Valid")
        return
    setLocalIdentity(lid)
#     _LocalIdentity = lid
#     _LocalIDURL = lid.getIDURL()
#     _LocalName = lid.getIDName()
    setTransportOrder(getOrderFromContacts(_LocalIdentity))
    lg.out(6, "my_id.loadLocalIdentity my name is [%s]" % lid.getIDName())
Esempio n. 10
0
def _list_local(params):
    result = []
    path = params['path']
    if bpio.Linux() or bpio.Mac():
        path = '/' + path.lstrip('/')
    path = bpio.portablePath(path)
    only_folders = params['onlyFolders']
    if (path == '' or path == '/') and bpio.Windows():
        for itemname in bpio.listLocalDrivesWindows():
            result.append({
                "name": itemname.rstrip('\\').rstrip('/').lower(),
                "rights": "drwxr-xr-x",
                "size": "",
                "date": "",
                "type": "dir",
                "dirpath": path,
            })
    else:
        if bpio.Windows() and len(path) == 2 and path[1] == ':':
            path += '/'
        apath = path
        for itemname in bpio.list_dir_safe(apath):
            itempath = os.path.join(apath, itemname)
            if only_folders and not os.path.isdir(itempath):
                continue
            result.append({
                "name": itemname,
                "rights": "drwxr-xr-x",
                "size": str(os.path.getsize(itempath)),
                "date": str(os.path.getmtime(itempath)),
                "type": "dir" if os.path.isdir(itempath) else "file",
                "dirpath": apath,
            })
    return {'result': result, }
Esempio n. 11
0
def _list_local(params):
    result = []
    path = params['path']
    if bpio.Linux() or bpio.Mac():
        path = '/' + path.lstrip('/')
    path = bpio.portablePath(path)
    only_folders = params['onlyFolders']
    if (path == '' or path == '/') and bpio.Windows():
        for itemname in bpio.listLocalDrivesWindows():
            result.append({
                "name": itemname.rstrip('\\').rstrip('/').lower(),
                "rights": "drwxr-xr-x",
                "size": "",
                "date": "",
                "type": "dir",
                "dirpath": path,
            })
    else:
        if bpio.Windows() and len(path) == 2 and path[1] == ':':
            path += '/'
        apath = path
        for itemname in bpio.list_dir_safe(apath):
            itempath = os.path.join(apath, itemname)
            if only_folders and not os.path.isdir(itempath):
                continue
            result.append({
                "name": itemname,
                "rights": "drwxr-xr-x",
                "size": str(os.path.getsize(itempath)),
                "date": str(os.path.getmtime(itempath)),
                "type": "dir" if os.path.isdir(itempath) else "file",
                "dirpath": apath,
            })
    return {'result': result, }
Esempio n. 12
0
def execute_in_shell(cmdargs, base_dir=None):
    global _CurrentProcess
    from system import nonblocking
    import subprocess
    if _Debug:
        lg.out(_DebugLevel,
               'git_proc.execute_in_shell: "%s"' % (' '.join(cmdargs)))
    write2log('EXECUTE in shell: %s, base_dir=%s' % (cmdargs, base_dir))
    _CurrentProcess = nonblocking.Popen(
        cmdargs,
        shell=True,
        cwd=bpio.portablePath(base_dir),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )
    result = _CurrentProcess.communicate()
    out_data = result[0]
    err_data = result[1]
    write2log('STDOUT:\n%s\nSTDERR:\n%s\n' % (out_data, err_data))
    returncode = _CurrentProcess.returncode
    if _Debug:
        lg.out(
            _DebugLevel,
            'git_proc.execute_in_shell returned: %s, stdout bytes: %d, stderr bytes: %d'
            % (returncode, len(out_data), len(err_data)))
    return (out_data, err_data, returncode)  # _CurrentProcess
Esempio n. 13
0
def eraseLocalIdentity(do_backup=True):
    if do_backup:
        if os.path.isfile(settings.LocalIdentityFilename()):
            current_identity_xmlsrc = local_fs.ReadBinaryFile(settings.LocalIdentityFilename())
            if current_identity_xmlsrc:
                fd, fname = tempfile.mkstemp(prefix='localidentity_', dir=settings.MetaDataDir())
                os.write(fd, current_identity_xmlsrc)
                os.close(fd)
                lg.info('created backup copy of my local identity in the file : %r' % fname)
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    if not os.path.exists(filename):
        if _Debug:
            lg.out(_DebugLevel, "my_id.eraseLocalIdentity SKIP file %s not exist" % filename)
        return True
    if not os.path.isfile(filename):
        if _Debug:
            lg.out(_DebugLevel, "my_id.eraseLocalIdentity ERROR path %s is not a file" % filename)
        return False
    try:
        os.remove(filename)
    except:
        lg.exc()
        return False
    events.send('local-identity-erased', data=dict())
    if _Debug:
        lg.out(_DebugLevel, "my_id.eraseLocalIdentity file %s was deleted" % filename)
    return True
Esempio n. 14
0
def init(udp_port, db_file_path=None):
    global _MyNode
    if _MyNode is not None:
        if _Debug:
            lg.out(_DebugLevel, 'dht_service.init SKIP, DHTNode already exist')
        return
    if db_file_path is None:
        db_file_path = settings.DHTDBFile()
    dbPath = bpio.portablePath(db_file_path)
    try:
        dataStore = SQLiteExpiredDataStore(dbFile=dbPath)
        # dataStore.setItem('not_exist_key', 'not_exist_value', time.time(), time.time(), None, 60)
        # del dataStore['not_exist_key']
    except:
        lg.warn(
            'failed reading DHT records, removing %s and starting clean DB' %
            dbPath)
        lg.exc()
        os.remove(dbPath)
        dataStore = SQLiteExpiredDataStore(dbFile=dbPath)
    networkProtocol = KademliaProtocolConveyor
    _MyNode = DHTNode(udp_port, dataStore, networkProtocol=networkProtocol)
    if _Debug:
        lg.out(
            _DebugLevel, 'dht_service.init UDP port is %d, DB file path: %s' %
            (udp_port, dbPath))
Esempio n. 15
0
def _config(params):
    result = []
    homepath = bpio.portablePath(os.path.expanduser('~'))
    if bpio.Windows():
        # set "c:" as a starting point when pick files for Windows
        # probably should be MyDocuments folder or something else,
        # but lets take that for now
        homepath = homepath[:2]
    result.append({'key': 'homepath',
                   'value': homepath})
    return {'result': result, }
Esempio n. 16
0
 def identity_recover_v1(self, request):
     data = _request_data(request)
     private_key_source = data.get('private_key_source')
     if not private_key_source:
         private_key_local_file = data.get('private_key_local_file')
         if private_key_local_file:
             from system import bpio
             private_key_source = bpio.ReadTextFile(
                 bpio.portablePath(private_key_local_file))
     return api.identity_recover(private_key_source=private_key_source,
                                 known_idurl=data.get('known_idurl'))
Esempio n. 17
0
def _config(params):
    result = []
    homepath = bpio.portablePath(os.path.expanduser('~'))
    if bpio.Windows():
        # set "c:" as a starting point when pick files for Windows
        # probably should be MyDocuments folder or something else,
        # but lets take that for now
        homepath = homepath[:2]
    result.append({'key': 'homepath',
                   'value': homepath})
    return {'result': result, }
Esempio n. 18
0
def eraseLocalIdentity():
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    if not os.path.exists(filename):
        lg.out(6, "my_id.eraseLocalIdentity SKIP file %s not exist" % filename)
        return True
    if not os.path.isfile(filename):
        lg.out(6, "my_id.eraseLocalIdentity ERROR path %s is not a file" % filename)
        return False
    try:
        os.remove(filename)
    except:
        lg.exc()
        return False
    lg.out(6, "my_id.eraseLocalIdentity file %s was deleted" % filename)
    return True
Esempio n. 19
0
def cmd_key(opts, args, overDict, running, executablePath):
    from main import settings
    from lib import misc
    from system import bpio
    from userid import my_id
    from crypt import key
    settings.init()
    my_id.init()

    if not key.LoadMyKey():
        print_text('private key not exist or is not valid\n')
        return 0
    if not my_id.isLocalIdentityReady():
        print_text('local identity not exist, your key worth nothing\n')
        return 0

    if len(args) == 2:
        if args[1] == 'copy':
            TextToSave = my_id.getLocalID() + "\n" + key.MyPrivateKey()
            misc.setClipboardText(TextToSave)
            del TextToSave
            print_text('now you can "paste" with Ctr+V your private key where you want')
            print_text('WARNING! keep your key in safe place, do not publish it!\n')
            return 0
        elif args[1] == 'print':
            TextToSave = my_id.getLocalID() + "\n" + key.MyPrivateKey()
            print_text('\n' + TextToSave + '\n')
            del TextToSave
            print_text('WARNING! keep your key in safe place, do not publish it!\n')
            return 0
    elif len(args) == 3:
        if args[1] == 'copy' or args[1] == 'save' or args[1] == 'backup':
            from system import bpio
            curpath = os.getcwd()
            os.chdir(executablePath)
            filenameto = bpio.portablePath(args[2])
            os.chdir(curpath)
            TextToSave = my_id.getLocalID() + "\n" + key.MyPrivateKey()
            if not bpio.AtomicWriteFile(filenameto, TextToSave):
                del TextToSave
                print_text('error writing to %s\n' % filenameto)
                return 1
            del TextToSave
            print_text('your private key were copied to file %s' % filenameto)
            print_text('WARNING! keep your key in safe place, do not publish it!\n')
            return 0

    return 2
Esempio n. 20
0
def init(udp_port, db_file_path=None):
    global _MyNode
    if _MyNode is not None:
        if _Debug:
            lg.out(_DebugLevel, "dht_service.init SKIP, already created a DHTNode")
        return
    if _Debug:
        lg.out(_DebugLevel, "dht_service.init UDP port is %d" % udp_port)
    if db_file_path is None:
        db_file_path = settings.DHTDBFile()
    dbPath = bpio.portablePath(db_file_path)
    lg.out(4, "dht_service.init UDP port is %d, DB file path: %s" % (udp_port, dbPath))
    dataStore = SQLiteDataStore(dbFile=dbPath)
    networkProtocol = KademliaProtocolConveyor
    # None, encoding.Bencode(), msgformat.DefaultFormat())
    _MyNode = DHTNode(udp_port, dataStore, networkProtocol=networkProtocol)
Esempio n. 21
0
def saveLocalIdentity():
    """
    Save identity object from memory into local file.

    Do sign the identity than serialize to write to the file.
    """
    global _LocalIdentity
    if not isLocalIdentityReady():
        lg.warn("ERROR local identity not exist!")
        return
    if not _LocalIdentity.isCorrect():
        lg.warn('local identity is not correct')
        return
    _LocalIdentity.sign()
    xmlid = _LocalIdentity.serialize()
    filename = bpio.portablePath(settings.LocalIdentityFilename())
    bpio.WriteFile(filename, xmlid)
    lg.out(6, "my_id.saveLocalIdentity %d bytes wrote to %s" % (len(xmlid), filename))
Esempio n. 22
0
def init(udp_port, db_file_path=None):
    global _MyNode
    if _MyNode is not None:
        if _Debug:
            lg.out(_DebugLevel,
                   'dht_service.init SKIP, already created a DHTNode')
        return
    if _Debug:
        lg.out(_DebugLevel, 'dht_service.init UDP port is %d' % udp_port)
    if db_file_path is None:
        db_file_path = settings.DHTDBFile()
    dbPath = bpio.portablePath(db_file_path)
    lg.out(
        4, 'dht_service.init UDP port is %d, DB file path: %s' %
        (udp_port, dbPath))
    dataStore = SQLiteDataStore(dbFile=dbPath)
    networkProtocol = KademliaProtocolConveyor
    # None, encoding.Bencode(), msgformat.DefaultFormat())
    _MyNode = DHTNode(udp_port, dataStore, networkProtocol=networkProtocol)
Esempio n. 23
0
def init(UI='', options=None, args=None, overDict=None, executablePath=None):
    """
    In the method ``main()`` program firstly checks the command line arguments
    and then calls this method to start the whole process.

    This initialize some low level modules and finally create an
    instance of ``initializer()`` state machine and send it an event
    "run".
    """
    global AppDataDir

    from logs import lg
    lg.out(4, 'bpmain.run UI="%s"' % UI)

    from system import bpio

    #---settings---
    from main import settings
    if overDict:
        settings.override_dict(overDict)
    settings.init(AppDataDir)
    if not options or options.debug is None:
        lg.set_debug_level(settings.getDebugLevel())
    from main import config
    config.conf().addCallback('logs/debug-level',
                              lambda p, value, o, r: lg.set_debug_level(value))

    #---USE_TRAY_ICON---
    if os.path.isfile(settings.LocalIdentityFilename()) and os.path.isfile(settings.KeyFileName()):
        try:
            from system.tray_icon import USE_TRAY_ICON
            if bpio.Mac() or not bpio.isGUIpossible():
                lg.out(4, '    GUI is not possible')
                USE_TRAY_ICON = False
            if USE_TRAY_ICON:
                from twisted.internet import wxreactor
                wxreactor.install()
                lg.out(4, '    wxreactor installed')
        except:
            USE_TRAY_ICON = False
            lg.exc()
    else:
        lg.out(4, '    local identity or key file is not ready')
        USE_TRAY_ICON = False
    lg.out(4, '    USE_TRAY_ICON=' + str(USE_TRAY_ICON))
    if USE_TRAY_ICON:
        from system import tray_icon
        icons_path = bpio.portablePath(os.path.join(bpio.getExecutableDir(), 'icons'))
        lg.out(4, 'bpmain.run call tray_icon.init(%s)' % icons_path)
        tray_icon.init(icons_path)

        def _tray_control_func(cmd):
            if cmd == 'exit':
                from . import shutdowner
                shutdowner.A('stop', 'exit')
        tray_icon.SetControlFunc(_tray_control_func)

    #---OS Windows init---
    if bpio.Windows():
        try:
            from win32event import CreateMutex  # @UnresolvedImport
            mutex = CreateMutex(None, False, "BitDust")
            lg.out(4, 'bpmain.run created a Mutex: %s' % str(mutex))
        except:
            lg.exc()

    #---twisted reactor---
    lg.out(4, 'bpmain.run want to import twisted.internet.reactor')
    try:
        from twisted.internet import reactor  # @UnresolvedImport
    except:
        lg.exc()
        sys.exit('Error initializing reactor in bpmain.py\n')

    #---logfile----
    if lg.logs_enabled() and lg.log_file():
        lg.out(2, 'bpmain.run want to switch log files')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_stop_redirecting()
        lg.close_log_file()
        lg.open_log_file(settings.MainLogFilename())
        # lg.open_log_file(settings.MainLogFilename() + '-' + time.strftime('%y%m%d%H%M%S') + '.log')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_start_redirecting()

    #---memdebug---
#    if settings.uconfig('logs.memdebug-enable') == 'True':
#        try:
#            from logs import memdebug
#            memdebug_port = int(settings.uconfig('logs.memdebug-port'))
#            memdebug.start(memdebug_port)
#            reactor.addSystemEventTrigger('before', 'shutdown', memdebug.stop)
#            lg.out(2, 'bpmain.run memdebug web server started on port %d' % memdebug_port)
#        except:
#            lg.exc()

    #---process ID---
    try:
        pid = os.getpid()
        pid_file_path = os.path.join(settings.MetaDataDir(), 'processid')
        bpio.WriteTextFile(pid_file_path, str(pid))
        lg.out(2, 'bpmain.run wrote process id [%s] in the file %s' % (str(pid), pid_file_path))
    except:
        lg.exc()

#    #---reactor.callLater patch---
#    if lg.is_debug(12):
#        patchReactorCallLater(reactor)
#        monitorDelayedCalls(reactor)

#    #---plugins---
#    from plugins import plug
#    plug.init()
#    reactor.addSystemEventTrigger('before', 'shutdown', plug.shutdown)

    lg.out(2, "    python executable is: %s" % sys.executable)
    lg.out(2, "    python version is:\n%s" % sys.version)
    lg.out(2, "    python sys.path is:\n                %s" % ('\n                '.join(sys.path)))

    lg.out(2, "bpmain.run UI=[%s]" % UI)

    if lg.is_debug(20):
        lg.out(0, '\n' + bpio.osinfofull())

    lg.out(4, 'import automats')

    #---START!---
    from automats import automat
    automat.LifeBegins(lg.when_life_begins())
    automat.OpenLogFile(settings.AutomatsLog())

    from main import events
    events.init()

    from main import initializer
    IA = initializer.A()
    lg.out(4, 'sending event "run" to initializer()')
    reactor.callWhenRunning(IA.automat, 'run', UI)  # @UndefinedVariable
    return IA
Esempio n. 24
0
def init(UI='', options=None, args=None, overDict=None, executablePath=None):
    """
    In the method ``main()`` program firstly checks the command line arguments
    and then calls this method to start the whole process.

    This initialize some low level modules and finally create an
    instance of ``initializer()`` state machine and send it an event
    "run".
    """
    global AppDataDir

    from logs import lg
    lg.out(4, 'bpmain.run UI="%s"' % UI)

    from system import bpio

    #---settings---
    from main import settings
    if overDict:
        settings.override_dict(overDict)
    settings.init(AppDataDir)
    if not options or options.debug is None:
        lg.set_debug_level(settings.getDebugLevel())
    from main import config
    config.conf().addCallback('logs/debug-level',
                              lambda p, value, o, r: lg.set_debug_level(value))

    #---USE_TRAY_ICON---
    if os.path.isfile(settings.LocalIdentityFilename()) and os.path.isfile(settings.KeyFileName()):
        try:
            from system.tray_icon import USE_TRAY_ICON
            if bpio.Mac() or not bpio.isGUIpossible():
                lg.out(4, '    GUI is not possible')
                USE_TRAY_ICON = False
            if USE_TRAY_ICON:
                from twisted.internet import wxreactor
                wxreactor.install()
                lg.out(4, '    wxreactor installed')
        except:
            USE_TRAY_ICON = False
            lg.exc()
    else:
        lg.out(4, '    local identity or key file is not ready')
        USE_TRAY_ICON = False
    lg.out(4, '    USE_TRAY_ICON=' + str(USE_TRAY_ICON))
    if USE_TRAY_ICON:
        from system import tray_icon
        icons_path = bpio.portablePath(os.path.join(bpio.getExecutableDir(), 'icons'))
        lg.out(4, 'bpmain.run call tray_icon.init(%s)' % icons_path)
        tray_icon.init(icons_path)

        def _tray_control_func(cmd):
            if cmd == 'exit':
                import shutdowner
                shutdowner.A('stop', 'exit')
        tray_icon.SetControlFunc(_tray_control_func)

    #---OS Windows init---
    if bpio.Windows():
        try:
            from win32event import CreateMutex
            mutex = CreateMutex(None, False, "BitDust")
            lg.out(4, 'bpmain.run created a Mutex: %s' % str(mutex))
        except:
            lg.exc()

    #---twisted reactor---
    lg.out(4, 'bpmain.run want to import twisted.internet.reactor')
    try:
        from twisted.internet import reactor
    except:
        lg.exc()
        sys.exit('Error initializing reactor in bpmain.py\n')

    #---logfile----
    if lg.logs_enabled() and lg.log_file():
        lg.out(2, 'bpmain.run want to switch log files')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_stop_redirecting()
        lg.close_log_file()
        lg.open_log_file(settings.MainLogFilename() + '-' + time.strftime('%y%m%d%H%M%S') + '.log')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_start_redirecting()

    #---memdebug---
#    if settings.uconfig('logs.memdebug-enable') == 'True':
#        try:
#            from logs import memdebug
#            memdebug_port = int(settings.uconfig('logs.memdebug-port'))
#            memdebug.start(memdebug_port)
#            reactor.addSystemEventTrigger('before', 'shutdown', memdebug.stop)
#            lg.out(2, 'bpmain.run memdebug web server started on port %d' % memdebug_port)
#        except:
#            lg.exc()

    #---process ID---
    try:
        pid = os.getpid()
        pid_file_path = os.path.join(settings.MetaDataDir(), 'processid')
        bpio.WriteFile(pid_file_path, str(pid))
        lg.out(2, 'bpmain.run wrote process id [%s] in the file %s' % (str(pid), pid_file_path))
    except:
        lg.exc()

#    #---reactor.callLater patch---
#    if lg.is_debug(12):
#        patchReactorCallLater(reactor)
#        monitorDelayedCalls(reactor)

#    #---plugins---
#    from plugins import plug
#    plug.init()
#    reactor.addSystemEventTrigger('before', 'shutdown', plug.shutdown)

    lg.out(2, "bpmain.run UI=[%s]" % UI)

    if lg.is_debug(20):
        lg.out(0, '\n' + bpio.osinfofull())

    lg.out(4, 'bpmain.run import automats')

    #---START!---
    from automats import automat
    automat.LifeBegins(lg.when_life_begins())
    automat.OpenLogFile(settings.AutomatsLog())

    import initializer
    I = initializer.A()
    lg.out(4, 'bpmain.run send event "run" to initializer()')
    reactor.callWhenRunning(I.automat, 'run', UI)
    return I