Beispiel #1
0
    def myRun(self):

        if not self.load_keys():
            print "need new keys"
            
            self.get_uuid()
            self.gen_qr_code('qr.png')
            print '[INFO] Please use WeChat to scan the QR code .'

            result = self.wait4login()
            if result != SUCCESS:
                print '[ERROR] Web WeChat login failed. failed code=%s' % (result,)
                return

            if self.login():
                print "skey: " + self.skey
                print "sid: " + self.sid
                print "uin: " + self.uin
                print "pass_ticket: " + self.pass_ticket
                print '[INFO] Web WeChat login succeed .'
            else:
                print '[ERROR] Web WeChat login failed .'
                return


            self.dump_keys()
        else:
            print "loaded old keys"


        if not self.DEBUG:
            ret = daemonize.createDaemon()
            print "start daemon..."

        if self.init():
            print '[INFO] Web WeChat init succeed .'
        else:
            print '[INFO] Web WeChat init failed'
            return

        self.status_notify()
        self.get_contact()
        print '[INFO] Get %d contacts' % len(self.contact_list)
        print '[INFO] Start to process messages .'
        self.proc_msg()
Beispiel #2
0
def main():
    # init app config
    global app
    app['conf'] = ConfigParser.SafeConfigParser()
    app['path'] = {}
    app['path']['app'] = os.path.dirname(os.path.realpath(__file__)) + os.sep

    # add import path
    sys.path.append(app['path']['app'] + 'lib')
    sys.path.append(app['path']['app'] + 'plugin')
    sys.path.append(app['path']['app'] + 'service')

    # add conf path
    import platformDep
    path = os.path.join(platformDep.getNmcontrolDir(), 'conf') + os.sep
    for argv in sys.argv:
        if argv.startswith("--confdir=") or argv.startswith("--main.confdir="):
            path = argv.split("=")[1]
            path = os.path.realpath(path) + os.sep
    app['path']['conf'] = path

    import common
    common.app = app

    import console
    (cWidth, cHeight) = console.getTerminalSize()
    fmt=optparse.IndentedHelpFormatter(indent_increment=4, max_help_position=40, width=cWidth-3, short_first=1 )
    app['parser'] = optparse.OptionParser(formatter=fmt,description='nmcontrol %s' % __version__)

    # debug mode
    app['debug'] = False
    for s in ['--debug=1', '--main.debug=1']:
        while s in sys.argv:
            app['debug'] = True
            sys.argv.remove(s)  # do not disturb client mode option parsing with debug option

    # parse command line options
    (options, app['args']) = app['parser'].parse_args()

    # determine client mode
    app['client'] = False
    if len(app['args']) > 0 and app['args'][0] != 'start':
        app['client'] = True

    # set up output and log
    if app['client']:
        common.logToFile = False
    log = common.get_logger(__name__, clear=True)
    if not app['client']:
        log.info("#######################################################")
    log.debug("DEBUG MODE")

    # init modules
    import re

    # init vars and main plugin
    app['services'] = {}
    app['plugins'] = {}
    import pluginMain
    app['plugins']['main'] = pluginMain.pluginMain('plugin')

    # init service & plugins
    for modType in ['service', 'plugin']:
        modules = os.listdir(os.path.join(app['path']['app'], modType))
        if modType == 'plugin': modules.remove('pluginMain.py')
        for module in modules:
            if re.match("^"+modType+".*.py$", module):
                module = re.sub(r'\.py$', '', module)
                modulename = re.sub(r'^'+modType, '', module).lower()
                try:
                    log.debug("launching", modType, module)
                    importedModule = __import__(module)
                    importedClass = getattr(importedModule, module)
                    app[modType+'s'][importedClass.name] = importedClass(modType)
                    importedClass.app = app
                except Exception as e:
                    log.exception("Exception when loading " + modType, module, ":", e)

    # structure command line options to suit modules
    # Note: There should not be plugins and services with the same name
    for option, value in vars(options).items():
        if value is not None:
            tmp = option.split('.')
            if len(tmp) == 1:
                app['plugins']['main'].conf[tmp[0]] = value
            else:
                module = tmp[0]
                tmp.remove(module)
                if module in app['plugins']:
                    app['plugins'][module].conf['.'.join(tmp)] = value
                if module in app['services']:
                    app['services'][module].conf['.'.join(tmp)] = value

    ###### Act as client : send rpc request ######
    if app['client']:
        error, data = app['plugins']['rpc'].pSend(app['args'][:])
        if error is True or data['error'] is True:
            print "ERROR:", data
        else:
            if data['result']['reply'] in [None, True]:
                print 'ok'
            else:
                print data['result']['reply']
            if data['result']['prints']:
                log.debug("LOG:", data['result']['prints'])
        if app['args'][0] != 'restart':
            return

    # daemon mode
    if os.name == "nt":  # MS Windows
        log.info("Daemon mode not possible on MS Windows.")
    elif int(app['plugins']['main'].conf['daemon']) == 1:
        log.info("Entering background mode")
        import daemonize
        retCode = daemonize.createDaemon()

    ###### Act as server : start plugins ######
    plugins_started = []
    for plugin in app['plugins']:
        if int(app['plugins'][plugin].conf['start']) == 1 and plugin not in ['rpc','main']:
            # exit immediatly when main is stopped, unless in debug mode
            app['plugins'][plugin].daemon=True
            if app['plugins'][plugin].running is False:
                app['plugins'][plugin].start()
                plugins_started.append(app['plugins'][plugin].name)
    log.info("Plugins started :", ', '.join(plugins_started))

    for plugin in app['plugins']:
        if app['plugins'][plugin].__dict__.has_key("criticalStartException") and app['plugins'][plugin].criticalStartException:
            raise Exception(app['plugins'][plugin].criticalStartException)

    #services_started = []
    #for service in app['services']:
    #    if app['services'][service].running:
    #        services_started.append(app['services'][service].name)
    #print "Services started :", ', '.join(services_started)

    # stay there to catch CTRL + C and not exit when in daemon mode
    try:
        app['plugins']['main'].start2()
    except (KeyboardInterrupt, SystemExit):
        log.info('\n! Received keyboard interrupt, quitting threads.\n')

    # stop main program
    app['plugins']['main'].stop()
Beispiel #3
0
	#	shutil.move('cap/capture.pcap', 'cap/'+localtime+'.pcap')

	#	temp = subprocess.Popen("gzip -1 cap/capture.pcap" , shell=True)
		
	#	temp.wait();
		shutil.move('/tmp/cap/capture.pcap', '/tmp/send/' +localtime+'.pcap')
		tcpdump = subprocess.Popen(["tcpdump", "-s", str(CAPSIZE), "-w", "/tmp/cap/capture.pcap"], shell=False)
	#	shutil.move("cap/" +localtime+".pcap.gz", "send/" + localtime+".pcap.gz")
	#	os.remove('cap/capture2compress.pcap')
		
		#subprocess.Popen("mv" + " " + "cap/*.gz" + " " + SENDDIR,shell=True)
		
		pid = str(tcpdump.pid)
		f = open('/tmp/pid', 'w')
		f.write(pid)
		f.close();
		f=open('/tmp/time', 'w')
		f.write("%100.100s"%(str(time.mktime(time.localtime()))))
		f.close()
		
if __name__ == "__main__":

	retCode = daemonize.createDaemon()

	initializecapture()
	while 1:
		capture()
		time.sleep(5)
	sys.exit(retCode)

    s.close()
    sys.exit(0)
except SystemExit as e:
    sys.exit(e)
except:
    pass

# Try to start own VisiCut instance
try:
    creationflags = 0
    close_fds = False
    if os.name == "nt":
        DETACHED_PROCESS = 8  # start as "daemon"
        creationflags = DETACHED_PROCESS
        close_fds = True
    else:
        try:
            import daemonize
            daemonize.createDaemon()
        except:
            sys.stderr.write(
                "Could not daemonize. Sorry, but Inkscape was blocked until VisiCut is closed"
            )
    cmd = [VISICUTBIN] + arguments + [dest_filename]
    Popen(cmd, creationflags=creationflags, close_fds=close_fds)
except:
    sys.stderr.write(
        "Can not start VisiCut (" + str(sys.exc_info()[0]) +
        "). Please start manually or change the VISICUTDIR variable in the Inkscape-Extension script\n"
    )
# TODO (complicated, probably WONTFIX): cleanup temporary directories -- this is really difficult because we need to make sure that visicut no longer needs the file, even for reloading!
Beispiel #5
0
#call(["inkscape","-z",filename+".svg","-T","--export-pdf="+filename+".clean.pdf"])
#call(["inkscape","-z",filename+".clean.pdf","--export-plain-svg="+filename+".clean.svg"])
#call(["inkscape","-z",filename+".clean.svg","--verb=EditSelectAllInAllLayers","--verb=SelectionUnGroup","--verb=FileSave","--verb=FileClose"])

# Try to connect to running VisiCut instance
try:
  import socket
  s=socket.socket()
  s.connect(("localhost", SINGLEINSTANCEPORT))
  s.send(filename+".svg\n")
  s.close()
  sys.exit(0)
except SystemExit, e:
    sys.exit(e)
except:
  pass
# Try to start own VisiCut instance
try:
  arguments=["--singleinstanceport", str(SINGLEINSTANCEPORT)]
  if which(VISICUTBIN) == None:
    sys.stderr.write("Error: Can't find VisiCut at '"+VISICUTBIN+"'. Please start VisiCut manually, add '"+VISICUTBIN+"' to the PATH Variable or change the VISICUTBIN variable in the Inkscape Extension.\n")
  else:
    try:
      from subprocess import Popen    
      import daemonize
      daemonize.createDaemon()
    except:
      sys.stderr.write("Could not daemonize. Sorry, but Inkscape was blocked until VisiCut is closed")
    Popen([VISICUTBIN]+arguments+[filename+".svg"])
except:
  sys.stderr.write("Can not start VisiCut ("+str(sys.exc_info()[0])+"). Please start manually or change the VISICUTBIN variable in the Inkscape-Extension script\n")
Beispiel #6
0
def main():
    # init app config
    global app
    app['conf'] = ConfigParser.SafeConfigParser()
    app['path'] = {}
    app['path']['app'] = os.path.dirname(os.path.realpath(__file__)) + os.sep

    # add import path
    sys.path.append(app['path']['app'] + 'lib')
    sys.path.append(app['path']['app'] + 'plugin')
    sys.path.append(app['path']['app'] + 'service')

    # add conf path
    import platformDep
    app['path']['conf'] = os.path.join(platformDep.getNmcontrolDir(),
                                       'conf') + os.sep

    import common
    common.app = app

    import console
    (cWidth, cHeight) = console.getTerminalSize()
    fmt=optparse.IndentedHelpFormatter(indent_increment=4, max_help_position=40, width=cWidth-3, short_first=1 )
    app['parser'] = optparse.OptionParser(formatter=fmt,description='nmcontrol %s' % __version__)
    app['debug'] = False

    # debug mode
    for argv in sys.argv:
        if argv in ['--debug=1','--main.debug=1']:
            app['debug'] = True

    # init modules
    import re
    import dircache

    # init vars and main plugin
    app['services'] = {}
    app['plugins'] = {}
    import pluginMain
    app['plugins']['main'] = pluginMain.pluginMain('plugin')

    # init service & plugins
    for modType in ['service', 'plugin']:
        modules = dircache.listdir(modType)
        if modType == 'plugin': modules.remove('pluginMain.py')
        for module in modules:
            if re.match("^"+modType+".*.py$", module):
                module = re.sub(r'\.py$', '', module)
                modulename = re.sub(r'^'+modType, '', module).lower()
                try:
                    importedModule = __import__(module)
                    importedClass = getattr(importedModule, module)
                    app[modType+'s'][importedClass.name] = importedClass(modType)
                    importedClass.app = app
                except Exception as e:
                    print "Exception when loading "+modType, module, ":", e

    # parse command line options
    (options, app['args']) = app['parser'].parse_args()
    if app['debug']: print "Cmdline args:", app['args']
    if app['debug']: print "Cmdline options:", options
    for option, value in vars(options).items():
        if value is not None:
            tmp = option.split('.')
            if len(tmp) == 1:
                app['plugins']['main'].conf[tmp[0]] = value
            else:
                module = tmp[0]
                tmp.remove(module)
                if module in app['plugins']:
                    app['plugins'][module].conf['.'.join(tmp)] = value
                elif module in app['services']:
                    app['services'][module].conf['.'.join(tmp)] = value

    ###### Act as client : send rpc request ######
    if len(app['args']) > 0 and app['args'][0] != 'start':
        error, data = app['plugins']['rpc'].pSend(app['args'][:])
        if error is True or data['error'] is True:
            print "ERROR:", data
        else:
            if data['result']['reply'] in [None, True]:
                print 'ok'
            else:
                print data['result']['reply']
            if app['debug'] and data['result']['prints']: print "LOG:", data['result']['prints']
        if app['args'][0] != 'restart':
            return

    # daemon mode
    if os.name == "nt":  # MS Windows
        print "Daemon mode not possible on MS Windows."
    elif int(app['plugins']['main'].conf['daemon']) == 1:
        print "Entering background mode"
        import daemonize
        retCode = daemonize.createDaemon()

    ###### Act as server : start plugins ######
    plugins_started = []
    for plugin in app['plugins']:
        if int(app['plugins'][plugin].conf['start']) == 1 and plugin not in ['rpc','main']:
            # exit immediatly when main is stopped, unless in debug mode
            app['plugins'][plugin].daemon=True
            if app['plugins'][plugin].running is False:
                app['plugins'][plugin].start()
                plugins_started.append(app['plugins'][plugin].name)
    print "Plugins started :", ', '.join(plugins_started)

    #services_started = []
    #for service in app['services']:
    #    if app['services'][service].running:
    #        services_started.append(app['services'][service].name)
    #print "Services started :", ', '.join(services_started)

    # stay there to catch CTRL + C and not exit when in daemon mode
    try:
        app['plugins']['main'].start2()
    except (KeyboardInterrupt, SystemExit):
        print '\n! Received keyboard interrupt, quitting threads.\n'

    # stop main program
    app['plugins']['main'].stop()
#New service found, we'll add it when it is resolved.
def new_service( interface, protocol, name, stype, domain, flags):

    if flags & avahi.LOOKUP_RESULT_LOCAL:
        pass

    log("Adding service "+" ".join([name,stype,domain]))
    server.ResolveService(interface, protocol, name, stype,
            domain, avahi.PROTO_UNSPEC, dbus.UInt32(0),
            reply_handler=service_resolved, error_handler=print_error)


if __name__ == "__main__":
   #Change directory to /tmp/ and user to nobody, as we don't need any extra privileges
   os.chdir("/tmp/")
   retCode = createDaemon()

   log("Daemonized with code "+str(retCode)+" setting up avahi")
   log("Dropping uid to nobody:nobody")
   os.setgid(getpwnam('nobody')[3])
   os.setuid(getpwnam('nobody')[2])
   DBusGMainLoop( set_as_default=True )
   bus = dbus.SystemBus()
   
   log("Opening DB")
   initdb()

   server = dbus.Interface(
               bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER ),
               avahi.DBUS_INTERFACE_SERVER )
   log("Advertisement setup done")
Beispiel #8
0
def main():
    # init app config
    global app
    app['conf'] = ConfigParser.SafeConfigParser()
    app['path'] = {}
    app['path']['app'] = os.path.dirname(os.path.realpath(__file__)) + os.sep
    app['path']['conf'] = app['path']['app'] + os.sep + 'conf' + os.sep

    # add import path
    sys.path.append(app['path']['app'] + 'lib')
    sys.path.append(app['path']['app'] + 'plugin')
    sys.path.append(app['path']['app'] + 'service')

    import common
    common.app = app

    import console
    (cWidth, cHeight) = console.getTerminalSize()
    fmt = optparse.IndentedHelpFormatter(indent_increment=4,
                                         max_help_position=40,
                                         width=cWidth - 3,
                                         short_first=1)
    app['parser'] = optparse.OptionParser(formatter=fmt,
                                          description='nmcontrol %s' %
                                          __version__)
    app['debug'] = False

    # debug mode
    for argv in sys.argv:
        if argv in ['--debug=1', '--main.debug=1']:
            app['debug'] = True

    # init modules
    import re
    import dircache

    # init vars and main plugin
    app['services'] = {}
    app['plugins'] = {}
    import pluginMain
    app['plugins']['main'] = pluginMain.pluginMain('plugin')

    # init service & plugins
    for modType in ['service', 'plugin']:
        modules = dircache.listdir(modType)
        if modType == 'plugin': modules.remove('pluginMain.py')
        for module in modules:
            if re.match("^" + modType + ".*.py$", module):
                module = re.sub(r'\.py$', '', module)
                modulename = re.sub(r'^' + modType, '', module).lower()
                try:
                    importedModule = __import__(module)
                    importedClass = getattr(importedModule, module)
                    app[modType +
                        's'][importedClass.name] = importedClass(modType)
                    importedClass.app = app
                except Exception as e:
                    print "Exception when loading " + modType, module, ":", e

    # parse command line options
    (options, app['args']) = app['parser'].parse_args()
    if app['debug']: print "Cmdline args:", app['args']
    if app['debug']: print "Cmdline options:", options
    for option, value in vars(options).items():
        if value is not None:
            tmp = option.split('.')
            if len(tmp) == 1:
                app['plugins']['main'].conf[tmp[0]] = value
            else:
                module = tmp[0]
                tmp.remove(module)
                if module in app['plugins']:
                    app['plugins'][module].conf['.'.join(tmp)] = value
                elif module in app['services']:
                    app['services'][module].conf['.'.join(tmp)] = value

    ###### Act as client : send rpc request ######
    if len(app['args']) > 0 and app['args'][0] != 'start':
        error, data = app['plugins']['rpc'].pSend(app['args'][:])
        if error is True or data['error'] is True:
            print "ERROR:", data
        else:
            if data['result']['reply'] in [None, True]:
                print 'ok'
            else:
                print data['result']['reply']
            if app['debug'] and data['result']['prints']:
                print "LOG:", data['result']['prints']
        if app['args'][0] != 'restart':
            return

    # daemon mode
    if int(app['plugins']['main'].conf['daemon']) == 1:
        print "Entering background mode"
        import daemonize
        retCode = daemonize.createDaemon()

    ###### Act as server : start plugins ######
    plugins_started = []
    for plugin in app['plugins']:
        if int(app['plugins'][plugin].conf['start']) == 1 and plugin not in [
                'rpc', 'main'
        ]:
            # exit immediatly when main is stopped, unless in debug mode
            app['plugins'][plugin].daemon = True
            if app['plugins'][plugin].running is False:
                app['plugins'][plugin].start()
                plugins_started.append(app['plugins'][plugin].name)
    print "Plugins started :", ', '.join(plugins_started)

    #services_started = []
    #for service in app['services']:
    #	if app['services'][service].running:
    #		services_started.append(app['services'][service].name)
    #print "Services started :", ', '.join(services_started)

    # stay there to catch CTRL + C and not exit when in daemon mode
    try:
        app['plugins']['main'].start2()
    except (KeyboardInterrupt, SystemExit):
        print '\n! Received keyboard interrupt, quitting threads.\n'

    # stop main program
    app['plugins']['main'].stop()
Beispiel #9
0
        old_res = None
    if old_res is not None and old_res != OndiskDb.DAEMON_RUNNING:
        p = old_res
        print "\n".join(p).strip()
    else:
        if not options.blocking:
            orig_sha = hashlib.sha1(open(args[0], 'r').read()).hexdigest()
            dir = os.getcwd()
            # Give vim something to know we're running in the background
            print "%s:1:1:n:Generating results" % args[0]
            if old_res == 'running':
                sys.exit(0)
            db.saveDb(args[0], orig_sha, OndiskDb.DAEMON_RUNNING)
            sys.stdout.flush()
            import traceback
            createDaemon()
            # Change back to original directory so arc works
            os.chdir(dir)
        try:
            if len(args) == 0:
                arcres = runarc(None)
            else:
                arcres = runarc(args[0])

            p = getArcResults(arcres, options.make_compatable)
            if not options.blocking:
                db.saveDb(args[0], orig_sha, p)
            else:
                print "\n".join(p).strip()
        except:
            # Could be running in a daemon.  Put debug info in a file
Beispiel #10
0
def main():
    # init app config
    global app
    app['conf'] = ConfigParser.SafeConfigParser()
    app['path'] = {}
    app['path']['app'] = os.path.dirname(os.path.realpath(__file__)) + os.sep

    # add import path
    sys.path.append(app['path']['app'] + 'lib')
    sys.path.append(app['path']['app'] + 'plugin')
    sys.path.append(app['path']['app'] + 'service')

    # add conf path
    import platformDep
    path = os.path.join(platformDep.getNmcontrolDir(), 'conf') + os.sep
    for argv in sys.argv:
        if argv.startswith("--confdir=") or argv.startswith("--main.confdir="):
            path = argv.split("=")[1]
            path = os.path.realpath(path) + os.sep
    app['path']['conf'] = path

    import common
    common.app = app

    import console
    (cWidth, cHeight) = console.getTerminalSize()
    fmt = optparse.IndentedHelpFormatter(indent_increment=4,
                                         max_help_position=40,
                                         width=cWidth - 3,
                                         short_first=1)
    app['parser'] = optparse.OptionParser(formatter=fmt,
                                          description='nmcontrol %s' %
                                          __version__)

    # debug mode
    app['debug'] = False
    for s in ['--debug=1', '--main.debug=1']:
        while s in sys.argv:
            app['debug'] = True
            sys.argv.remove(
                s
            )  # do not disturb client mode option parsing with debug option

    # parse command line options
    (options, app['args']) = app['parser'].parse_args()

    # determine client mode
    app['client'] = False
    if len(app['args']) > 0 and app['args'][0] != 'start':
        app['client'] = True

    # set up output and log
    if app['client']:
        common.logToFile = False
    log = common.get_logger(__name__, clear=True)
    if not app['client']:
        log.info("#######################################################")
    log.debug("DEBUG MODE")

    # init modules
    import re

    # init vars and main plugin
    app['services'] = {}
    app['plugins'] = {}
    import pluginMain
    app['plugins']['main'] = pluginMain.pluginMain('plugin')

    # init service & plugins
    for modType in ['service', 'plugin']:
        modules = os.listdir(os.path.join(app['path']['app'], modType))
        if modType == 'plugin': modules.remove('pluginMain.py')
        for module in modules:
            if re.match("^" + modType + ".*.py$", module):
                module = re.sub(r'\.py$', '', module)
                modulename = re.sub(r'^' + modType, '', module).lower()
                try:
                    log.debug("launching", modType, module)
                    importedModule = __import__(module)
                    importedClass = getattr(importedModule, module)
                    app[modType +
                        's'][importedClass.name] = importedClass(modType)
                    importedClass.app = app
                except Exception as e:
                    log.exception("Exception when loading " + modType, module,
                                  ":", e)

    # structure command line options to suit modules
    # Note: There should not be plugins and services with the same name
    for option, value in vars(options).items():
        if value is not None:
            tmp = option.split('.')
            if len(tmp) == 1:
                app['plugins']['main'].conf[tmp[0]] = value
            else:
                module = tmp[0]
                tmp.remove(module)
                if module in app['plugins']:
                    app['plugins'][module].conf['.'.join(tmp)] = value
                if module in app['services']:
                    app['services'][module].conf['.'.join(tmp)] = value

    ###### Act as client : send rpc request ######
    if app['client']:
        error, data = app['plugins']['rpc'].pSend(app['args'][:])
        if error is True or data['error'] is True:
            print "ERROR:", data
        else:
            if data['result']['reply'] in [None, True]:
                print 'ok'
            else:
                print data['result']['reply']
            if data['result']['prints']:
                log.debug("LOG:", data['result']['prints'])
        if app['args'][0] != 'restart':
            return

    # daemon mode
    if os.name == "nt":  # MS Windows
        log.info("Daemon mode not possible on MS Windows.")
    elif int(app['plugins']['main'].conf['daemon']) == 1:
        log.info("Entering background mode")
        import daemonize
        retCode = daemonize.createDaemon()

    ###### Act as server : start plugins ######
    plugins_started = []
    for plugin in app['plugins']:
        if int(app['plugins'][plugin].conf['start']) == 1 and plugin not in [
                'rpc', 'main'
        ]:
            # exit immediatly when main is stopped, unless in debug mode
            app['plugins'][plugin].daemon = True
            if app['plugins'][plugin].running is False:
                app['plugins'][plugin].start()
                plugins_started.append(app['plugins'][plugin].name)
    log.info("Plugins started :", ', '.join(plugins_started))

    for plugin in app['plugins']:
        if app['plugins'][plugin].__dict__.has_key(
                "criticalStartException"
        ) and app['plugins'][plugin].criticalStartException:
            raise Exception(app['plugins'][plugin].criticalStartException)

    #services_started = []
    #for service in app['services']:
    #    if app['services'][service].running:
    #        services_started.append(app['services'][service].name)
    #print "Services started :", ', '.join(services_started)

    # stay there to catch CTRL + C and not exit when in daemon mode
    try:
        app['plugins']['main'].start2()
    except (KeyboardInterrupt, SystemExit):
        log.info('\n! Received keyboard interrupt, quitting threads.\n')

    # stop main program
    app['plugins']['main'].stop()
    cli.run()


if __name__ == '__main__':
    
    #BASE_URL = 'http://localhost:8000'
    #STORE_DIR = os.getcwd()  # "." loses its meaning as soon as we deamonize
    
    BASE_URL = 'http://www.speed.dcc.ufmg.br/slashcrawling'
    STORE_DIR = '/home/ufmg_socnets/client/article_data/'

    # Dettach the current proceess from the terminal and became 
    # a daemon
    print "Becoming a daemon"
    res = createDaemon()
    # We closed all stdio and redirected them for /dev/null
    # Just in case we need them back, let's reconfigure stdout and stderr
    reconfigStdout(STORE_DIR + "/daemon.log")
    log = sys.stdout # we closed the old file descriptor, get the new one.
    print "Became a daemon"
    
    try:
        main(BASE_URL, STORE_DIR)
    except urllib2.HTTPError, e:
        log_urllib2_exception(e)
        raise
    except:
        log_backtrace()
        raise
 
Beispiel #12
0
    old_res = None
  if old_res is not None and old_res != OndiskDb.DAEMON_RUNNING:
    p = old_res
    print "\n".join(p).strip()
  else:
    if not options.blocking:
      orig_sha = hashlib.sha1(open(args[0], 'r').read()).hexdigest()
      dir = os.getcwd()
      # Give vim something to know we're running in the background
      print "%s:1:1:n:Generating results" % args[0]
      if old_res == 'running':
        sys.exit(0)
      db.saveDb(args[0], orig_sha, OndiskDb.DAEMON_RUNNING)
      sys.stdout.flush()
      import traceback
      createDaemon()
      # Change back to original directory so arc works
      os.chdir(dir)
    try:
        if len(args) == 0:
          arcres = runarc(None)
        else:
          arcres = runarc(args[0])

        p = getArcResults(arcres, options.make_compatable)
        if not options.blocking:
          db.saveDb(args[0], orig_sha, p)
        else:
          print "\n".join(p).strip()
    except:
        # Could be running in a daemon.  Put debug info in a file