Ejemplo n.º 1
0
 def masterapp(self):
     """
     """
     config = json.load(open(self.configpath, 'r'))
     GlobalObject().json_config = config
     mastercnf = config.get('master')
     rootport = mastercnf.get('rootport')
     webport = mastercnf.get('webport')
     masterlog = mastercnf.get('log')
     self.root = PBRoot()
     rootservice = services.Service("rootservice")
     self.root.addServiceChannel(rootservice)
     self.webroot = vhost.NameVirtualHost()
     self.webroot.addHost('0.0.0.0', './')
     GlobalObject().root = self.root
     GlobalObject().webroot = self.webroot
     if masterlog:
         log.addObserver(loogoo(masterlog))  #日志处理
     log.startLogging(sys.stdout)
     import firefly.master.webapp
     import firefly.master.rootapp
     reactor.listenTCP(webport,
                       DelaySite(self.webroot),
                       interface='127.0.0.1')
     reactor.listenTCP(rootport, BilateralFactory(self.root))
Ejemplo n.º 2
0
 def create_master(self):
     """
     创建Master服务
     :return:
     """
     config = Config().config
     GlobalObject().json_config = config
     mastercnf = config.get('master')
     rootport = mastercnf.get('rootport')
     webport = mastercnf.get('webport')
     masterlog = mastercnf.get('log')
     self.root = PBRoot()
     rootservice = services.Service("rootservice")
     self.root.addServiceChannel(rootservice)
     self.web = vhost.NameVirtualHost()
     self.web.addHost('0.0.0.0', './')
     GlobalObject().root = self.root
     GlobalObject().webroot = self.web
     import webapp
     import rootapp
     internet.TCPServer(webport,
                        DelaySite(self.web)).setServiceParent(self.service)
     internet.TCPServer(rootport, BilateralFactory(
         self.root)).setServiceParent(self.service)
     self.process.setServiceParent(self.service)
Ejemplo n.º 3
0
def loadModule():
    root = vhost.NameVirtualHost()
    #在浏览器地址栏输入http://localhost:2012/opera?username=xx&opera_str=xxx  (username是要操作的账号  opera_str是要操作的脚本)
    root.putChild('opera', OperaPlayer())
    root.putChild('dayrecored', DayRecored())  #datarecorded获取每日的记录
    root.putChild('statistics', Statistics())  #statistics获取单服总数据
    reactor.listenTCP(2012, Site(root))
Ejemplo n.º 4
0
def initWeb():
        webroot = vhost.NameVirtualHost()
        webroot.addHost('0.0.0.0', './')

        webroot.putChild(stop.__name__, stop())
        webroot.putChild(reloadmodule.__name__, reloadmodule())
        webroot.putChild(chenee.__name__, chenee())

        return  webroot
Ejemplo n.º 5
0
 def makeService(self, options):
     application = wsgi_hello.application
     pool = threadpool.ThreadPool(minthreads=1, maxthreads=100)
     reactor.callWhenRunning(pool.start)
     reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
     dynamic = wsgi.WSGIResource(reactor, pool, application)
     files = static.File('static')
     root = vhost.NameVirtualHost()
     root.addHost(b'app.example.org', dynamic)
     root.addHost(b'static.example.org', files)
     site = server.Site(root)
     return strports.service(options['port'], site)
Ejemplo n.º 6
0
    def masterapp(self):
        """
        """
        config = json.load(open(self.configpath, "r"))
        GlobalObject().json_config = config
        mastercnf = config.get("master")
        rootport = mastercnf.get("rootport")
        webport = mastercnf.get("webport")
        masterlog = mastercnf.get("log")
        self.root = PBRoot()
        rootservice = services.Service("rootservice")
        self.root.addServiceChannel(rootservice)
        self.webroot = vhost.NameVirtualHost()
        self.webroot.addHost("0.0.0.0", "./")
        GlobalObject().root = self.root
        GlobalObject().webroot = self.webroot
        if masterlog:
            log.addObserver(loogoo(masterlog))  # 日志处理
        log.startLogging(sys.stdout)
        from . import webapp
        from . import rootapp

        reactor.listenTCP(webport, DelaySite(self.webroot))
        reactor.listenTCP(rootport, BilateralFactory(self.root))
Ejemplo n.º 7
0
    def config(self,
               config,
               servername=None,
               dbconfig=None,
               memconfig=None,
               masterconf=None):
        '''配置服务器
        '''
        GlobalObject().json_config = config
        netport = config.get('netport')  #客户端连接
        webport = config.get('webport')  #http连接
        rootport = config.get('rootport')  #root节点配置
        self.remoteportlist = config.get('remoteport', [])  #remote节点配置列表
        if not servername:
            servername = config.get('name')  #服务器名称
        logpath = config.get('log')  #日志
        hasdb = config.get('db')  #数据库连接
        hasmem = config.get('mem')  #memcached连接
        app = config.get('app')  #入口模块名称
        cpuid = config.get('cpu')  #绑定cpu
        mreload = config.get('reload')  #重新加载模块名称
        self.servername = servername
        if masterconf:
            masterport = masterconf.get('rootport')
            masterhost = masterconf.get('roothost')
            self.master_remote = RemoteObject(servername, "master")
            addr = ('localhost',
                    masterport) if not masterhost else (masterhost, masterport)
            self.master_remote.connect(addr)
            GlobalObject().masterremote = self.master_remote

        if netport:
            self.netfactory = LiberateFactory()
            netservice = services.CommandService("netservice")
            self.netfactory.addServiceChannel(netservice)
            reactor.listenTCP(netport, self.netfactory)

        if webport:
            self.webroot = vhost.NameVirtualHost()
            GlobalObject().webroot = self.webroot
            reactor.listenTCP(webport, DelaySite(self.webroot))

        if rootport:
            self.root = PBRoot()
            rootservice = services.Service("rootservice")
            self.root.addServiceChannel(rootservice)
            reactor.listenTCP(rootport, BilateralFactory(self.root))

        for cnf in self.remoteportlist:
            rname = cnf.get('rootname')
            self.remote[rname] = RemoteObject(self.servername, rname)

        if hasdb and dbconfig:
            log.msg(str(dbconfig))
            dbpool.initPool(**dbconfig)

        if hasmem and memconfig:
            urls = memconfig.get('urls')
            hostname = str(memconfig.get('hostname'))
            mclient.connect(urls, hostname)

        if logpath:
            log.addObserver(loogoo(logpath))  #日志处理
        log.startLogging(sys.stdout)

        if cpuid:
            affinity.set_process_affinity_mask(os.getpid(), cpuid)
        GlobalObject().config(netfactory=self.netfactory,
                              root=self.root,
                              remote=self.remote)
        if app:
            __import__(app)
        if mreload:
            _path_list = mreload.split(".")
            GlobalObject().reloadmodule = __import__(mreload,
                                                     fromlist=_path_list[:1])
        GlobalObject().remote_connect = self.remote_connect
        import admin
Ejemplo n.º 8
0
class PhishingWebServer():
    def __init__(self, config):
        self.config = config
        self.logpath = os.getcwd() + "/" + self.config[
            "domain_name"] + "_" + self.config["phishing_domain"] + "/"

        #ensure log path exists
        if not os.path.exists(self.logpath):
            os.makedirs(self.logpath)
        if not os.path.exists(self.logpath + "logs/"):
            os.makedirs(self.logpath + "/logs")

        # set up database connection
        self.db = MyDB(sqlite_file=self.logpath)

        self.websites = {}
        self.phishingsites = {}
        self.MINPORT = int(self.config["vhost_port_min"])
        self.MAXPORT = int(self.config["vhost_port_max"])

    def getTemplates(self):
        templates = []
        db_static_templates = self.db.getWebTemplates(ttype="static")
        db_dynamic_templates = self.db.getWebTemplates(ttype="dynamic")
        if (db_static_templates or db_dynamic_templates):
            for template in db_static_templates:
                parts = template.split("[-]")
                template_file = parts[0] + "/CONFIG"
                if Utils.is_readable(template_file) and os.path.isfile(
                        template_file):
                    templates.append(parts[0])
                    print "STATIC = [%s]" % (parts[0])
            for template in db_dynamic_templates:
                parts = template.split("[-]")
                template_file = parts[0] + "/CONFIG"
                if Utils.is_readable(template_file) and os.path.isfile(
                        template_file):
                    templates.append(parts[0])
                    print "DYNAMIC = [%s]" % (parts[0])
        else:
            for f in os.listdir(self.config["web_template_path"]):
                template_file = os.path.join(self.config["web_template_path"],
                                             f) + "/CONFIG"
                if Utils.is_readable(template_file) and os.path.isfile(
                        template_file):
                    templates.append(
                        os.path.join(self.config["web_template_path"], f))
                    print "FIXED = [%s]" % (os.path.join(
                        self.config["web_template_path"], f))
        return templates

    def loadSites(self):

        templates = self.getTemplates()
        print

        # loop over each web template
        for f in templates:
            template_file = f + "/CONFIG"
            if Utils.is_readable(template_file) and os.path.isfile(
                    template_file):
                print "Found the following web sites: [%s]" % template_file
                # read in the VHOST, LOGFILE, and REDIRECTURL
                VHOST = ""
                LOGFILE = ""
                REDIRECTURL = ""
                #PATH = self.config["web_template_path"] + f + "/"
                PATH = f + "/"
                with open(template_file, "r") as myfile:
                    for line in myfile.readlines():
                        match = re.search("VHOST=", line)
                        if match:
                            VHOST = line.replace('"', "")
                            VHOST = VHOST.split("=")
                            VHOST = VHOST[1].lower().strip()
                        match2 = re.search("LOGFILE=", line)
                        if match2:
                            LOGFILE = line.replace('"', "")
                            LOGFILE = LOGFILE.split("=")
                            LOGFILE = LOGFILE[1].strip()
                        match3 = re.search("REDIRECTURL=", line)
                        if match3:
                            REDIRECTURL = line.replace('"', "")
                            REDIRECTURL = REDIRECTURL.replace(r'\n', "\n")
                            REDIRECTURL = REDIRECTURL.split("=")
                            REDIRECTURL = REDIRECTURL[1].strip()
                self.websites[VHOST] = {
                    'path': PATH,
                    'port': 8000,
                    'logfile': LOGFILE,
                    'redirecturl': REDIRECTURL
                }

    def timedLogFormatter(timestamp, request):
        """
        A custom request formatter.  This is whats used when each request line is formatted.

        :param timestamp:
        :param request: A twisted.web.server.Request instance
        """
        #referrer = _escape(request.getHeader(b"referer") or b"-")
        agent = _escape(request.getHeader(b"user-agent") or b"-")
        duration = round(time.time() - request.started, 4)
        line = (u'"%(ip)s" %(duration)ss "%(method)s %(uri)s %(protocol)s" '
                u'%(code)d %(length)s "%(agent)s"' %
                dict(ip=_escape(request.getClientIP() or b"-"),
                     duration=duration,
                     method=_escape(request.method),
                     uri=_escape(request.uri),
                     protocol=_escape(request.clientproto),
                     code=request.code,
                     length=request.sentLength or u"-",
                     agent=agent))
        return line

    def start(self):
        self.loadSites()

        if self.config["ip"] == "0.0.0.0":
            self.config["ip"] = Utils.getIP()

        #define phishing sites
        for key in self.websites:
            self.phishingsites[key] = PhishingSite(
                self.config, key, self.websites[key]['path'], self.logpath,
                "logs/" + self.websites[key]['logfile'], self.db,
                self.websites[key]['redirecturl']).getResource()

        site_length = 0
        for key in self.phishingsites:
            if (len(key) > site_length):
                site_length = len(key)

        # if we are doing port based
        print
        for key in self.phishingsites:
            for port in range(self.MINPORT, self.MAXPORT):
                try:
                    site = Site(self.phishingsites[key],
                                logPath=self.logpath + "logs/" +
                                self.websites[key]['logfile'] + ".access")
                    #                    site.logRequest = True
                    reactor.listenTCP(port, site)
                    print "Started website [%s] on [http://%s:%s]" % (
                        ('{:<%i}' %
                         (site_length)).format(key), self.config["ip"], port)
                    self.websites[key]['port'] = port
                    break
                except twisted.internet.error.CannotListenError, ex:
                    continue

        # if we are doing virtual hosts
        if (self.config["enable_host_based_vhosts"] == "1"):
            print

            root = vhost.NameVirtualHost()
            site_length += len("." + self.config["phishing_domain"])
            # add each port based vhost to the nam based vhost
            for key in self.phishingsites:
                root.addHost(
                    key + "." + self.config["phishing_domain"],
                    proxy.ReverseProxyResource('localhost',
                                               self.websites[key]['port'], ''))
                print "Created VHOST [%s] -> [https://%s:%s]" % (
                    ('{:<%i}' %
                     (site_length)).format(key + "." +
                                           self.config["phishing_domain"]),
                    self.config["ip"], str(self.websites[key]['port']))
                print "Created VHOST [%s] -> [http://%s:%s]" % (
                    ('{:<%i}' %
                     (site_length)).format(key + "." +
                                           self.config["phishing_domain"]),
                    self.config["ip"], str(self.websites[key]['port']))
            # add a mapping for the base IP address to map to one of the sites
            if (self.phishingsites):
                root.addHost(
                    self.config["ip"],
                    proxy.ReverseProxyResource(
                        'localhost',
                        int(self.websites[self.phishingsites.keys()[0]]
                            ['port']), ''))
                try:
                    site = Site(root,
                                logPath=self.logpath + "logs/root.log.access")

                    # ADD SSL CERT
                    sslContext = ssl.DefaultOpenSSLContextFactory(
                        self.config["cert_path"] + 'privkey.pem',
                        self.config["cert_path"] + 'fullchain.pem',
                    )
                    reactor.listenSSL(int(self.config["default_web_ssl_port"]),
                                      site,
                                      contextFactory=sslContext)
                    reactor.listenTCP(int(self.config["default_web_port"]),
                                      site)
                except twisted.internet.error.CannotListenError, ex:
                    print "ERROR: Could not start web service listener on port [" + int(
                        self.config["default_web_ssl_port"]) + "]!"
                    print "ERROR: Could not start web service listener on port [80]!"
                    print ex
                    print "ERROR: Host Based Virtual Hosting will not function!"
            else:
                print "ERROR: Could not start web service listener on port [" + int(
                    self.config["default_web_ssl_port"]) + "]!"
                print "ERROR: Could not start web service listener on port [80]!"
                print "ERROR: Host Based Virtual Hosting will not function!"
Ejemplo n.º 9
0
Archivo: web.py Proyecto: webvul/SPF
    def start(self):
        self.loadSites()

        if self.config["ip"] == "0.0.0.0":
            self.config["ip"] = Utils.getIP()

        #define phishing sites
        for key in self.websites:
            self.phishingsites[key] = PhishingSite(
                self.config, key, self.websites[key]['path'], self.logpath,
                "logs/" + self.websites[key]['logfile'], self.db,
                self.websites[key]['redirecturl']).getResource()

        site_length = 0
        for key in self.phishingsites:
            if (len(key) > site_length):
                site_length = len(key)

        # if we are doing port based
        print()
        for key in self.phishingsites:
            for port in range(self.MINPORT, self.MAXPORT):
                try:
                    site = Site(self.phishingsites[key],
                                logPath=self.logpath + "logs/" +
                                self.websites[key]['logfile'] + ".access")
                    #                    site.logRequest = True
                    reactor.listenTCP(port, site)
                    print(
                        "Started website [%s] on [http://%s:%s]" %
                        (('{:<%i}' %
                          (site_length)).format(key), self.config["ip"], port))
                    self.websites[key]['port'] = port
                    break
                except twisted.internet.error.CannotListenError as ex:
                    continue

        # if we are doing virtual hosts
        if (self.config["enable_host_based_vhosts"] == "1"):
            print()

            # GENERATING SSL CERTS ARE CURRENTLY BROKEN
            # TODO: Fix this
            # generate new certificates
            #            domains = ""
            #            cert_path = "/etc/letsencrypt/live/"
            #            first = True
            #            for key in self.phishingsites:
            #                domains += "-d " + key + "." + self.config["phishing_domain"] + " "
            #                if first:
            #                    cert_path += key + "." + self.config["phishing_domain"] + "/"
            #                    first = False
            #
            #            cmd = self.config["certbot_path"] + " certonly --register-unsafely-without-email --non-interactive --agree-tos --standalone --force-renewal " + domains
            #
            #            env = os.environ
            #            print "Generating SSL CERT"
            #            proc = subprocess.Popen(cmd, executable='/bin/bash', env=env, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
            #            result = proc.communicate()[0]
            #            m = re.search(r'.* (\/etc\/letsencrypt\/live\/[^\/]+\/).*fullchain.pem.*', result)
            #            print result
            #
            #            cert_path = m.group(1)

            root = vhost.NameVirtualHost()
            site_length += len("." + self.config["phishing_domain"])
            # add each port based vhost to the nam based vhost
            for key in self.phishingsites:
                root.addHost(
                    key + "." + self.config["phishing_domain"],
                    proxy.ReverseProxyResource('localhost',
                                               self.websites[key]['port'], ''))
                #                print "Created VHOST [%s] -> [https://%s:%s]" % (('{:<%i}' % (site_length)).format(key + "." + self.config["phishing_domain"]), self.config["ip"], str(self.websites[key]['port']))
                print("Created VHOST [%s] -> [http://%s:%s]" %
                      (('{:<%i}' %
                        (site_length)).format(key + "." +
                                              self.config["phishing_domain"]),
                       self.config["ip"], str(self.websites[key]['port'])))
            # add a mapping for the base IP address to map to one of the sites
            if (self.phishingsites):
                root.addHost(
                    self.config["ip"],
                    proxy.ReverseProxyResource(
                        'localhost',
                        int(self.websites[list(
                            self.phishingsites.keys())[0]]['port']), ''))
                try:
                    site = Site(root,
                                logPath=self.logpath + "logs/root.log.access")

                    #                    # ADD SSL CERT
                    #                    sslContext = ssl.DefaultOpenSSLContextFactory(
                    #                        cert_path + 'privkey.pem',
                    #                        cert_path + 'fullchain.pem',
                    #                    )
                    #                    reactor.listenSSL(int(self.config["default_web_ssl_port"]), site, contextFactory=sslContext)
                    reactor.listenTCP(int(self.config["default_web_port"]),
                                      site)
                except twisted.internet.error.CannotListenError as ex:
                    #                    print "ERROR: Could not start web service listener on port [" + int(self.config["default_web_ssl_port"]) + "]!"
                    print(
                        "ERROR: Could not start web service listener on port [80]!"
                    )
                    print(ex)
                    print(
                        "ERROR: Host Based Virtual Hosting will not function!")
            else:
                #                print "ERROR: Could not start web service listener on port [" + int(self.config["default_web_ssl_port"]) + "]!"
                print(
                    "ERROR: Could not start web service listener on port [80]!"
                )
                print("ERROR: Host Based Virtual Hosting will not function!")

        print()
        print("Websites loaded and launched.")
        sys.stdout.flush()
        reactor.run()
Ejemplo n.º 10
0
    def set_config(self):
        """
        初始化节点服务配置
        :return:
        """
        config = Config().config
        ser_cfg = config.get("servers", {}).get(self.servername)
        if not ser_cfg:
            raise ValueError
        mem_cfg = config.get("cache")
        master_cfg = config.get("master")
        db_cfg = config.get("db")

        GlobalObject().json_config = ser_cfg
        netport = ser_cfg.get('netport')  # 客户端连接
        webport = ser_cfg.get('webport')  # http连接
        rootport = ser_cfg.get('rootport')  # root节点配置
        wsport = ser_cfg.get("wsport")  # WebSocket端口
        self.remoteportlist = ser_cfg.get('remoteport', [])  # remote节点配置列表
        logpath = ser_cfg.get('log')  # 日志
        hasdb = ser_cfg.get('db')  # 数据库连接
        hasmem = ser_cfg.get('mem')  # memcached连接
        app = ser_cfg.get('app')  # 入口模块名称
        cpuid = ser_cfg.get('cpu')  # 绑定cpu
        mreload = ser_cfg.get('reload')  # 重新加载模块名称

        if master_cfg:
            masterport = master_cfg.get('rootport')
            masterhost = master_cfg.get('roothost')
            self.master_remote = RemoteObject(self.servername)
            addr = ('localhost',
                    masterport) if not masterhost else (masterhost, masterport)
            self.master_remote.connect(addr)
            GlobalObject().masterremote = self.master_remote

        if netport:
            self.netfactory = LiberateFactory()
            netservice = services.CommandService("netservice")
            self.netfactory.addServiceChannel(netservice)
            reactor.listenTCP(netport, self.netfactory)

        if webport:
            self.webroot = vhost.NameVirtualHost()
            GlobalObject().webroot = self.webroot
            reactor.listenTCP(webport, DelaySite(self.webroot))

        if rootport:
            self.root = PBRoot()
            rootservice = services.Service("rootservice")
            self.root.addServiceChannel(rootservice)
            reactor.listenTCP(rootport, BilateralFactory(self.root))

        if wsport:
            self.ws = WsFactory(wsport)
            wsservice = services.CommandService("wsservice")
            self.ws.addServiceChannel(wsservice)
            reactor.listenTCP(wsport, self.ws)

        for cnf in self.remoteportlist:
            rname = cnf.get('rootname')
            self.remote[rname] = RemoteObject(self.servername)

        if hasdb and db_cfg:
            log.msg(str(db_cfg))
            dbpool.initPool(**db_cfg)

        if hasmem and mem_cfg:
            urls = mem_cfg.get('urls')
            hostname = str(mem_cfg.get('hostname'))
            mclient.connect(urls, hostname)

        if logpath:
            log.addObserver(loogoo(logpath))  #日志处理
        log.startLogging(sys.stdout)

        if cpuid:
            affinity.set_process_affinity_mask(os.getpid(), cpuid)

        GlobalObject().config(netfactory=self.netfactory,
                              root=self.root,
                              remote=self.remote)
        GlobalObject().server = self

        if app:
            __import__(app)
        if mreload:
            _path_list = mreload.split(".")
            GlobalObject().reloadmodule = __import__(mreload,
                                                     fromlist=_path_list[:1])
        GlobalObject().remote_connect = self.remote_connect
        import admin
Ejemplo n.º 11
0
    def handle(self, *args, **options):

        # setup
        running_processes = []
        main_server_port = 8001
        mirror_server_port = 8002
        main_server_address = 'http://users.perma.dev:%s' % main_server_port
        mirror_server_address = 'http://perma.dev:%s' % mirror_server_port
        temp_dir = tempdir.TempDir()

        try:
            print "Creating mirror database ..."
            main_database = settings.DATABASES['default']['NAME']
            mirror_database = main_database+"_mirror"
            mysql_credentials = [
                "-u"+settings.DATABASES['default']['USER'],
                "-p" + settings.DATABASES['default']['PASSWORD'],
            ]
            empty_tables = ['perma_linkuser','perma_link','perma_asset']
            mysqldump_command = "mysqldump %(user)s %(password)s %%(options)s %(main_database)s %%(tables)s | mysql %(user)s %(password)s %(mirror_database)s" % {
                'user':mysql_credentials[0], 'password':mysql_credentials[1], 'main_database':main_database, 'mirror_database':mirror_database,
            }
            subprocess.call(["mysql"]+mysql_credentials+[main_database, "-e", "DROP DATABASE IF EXISTS %s;" % mirror_database])
            subprocess.call(["mysql"]+mysql_credentials+[main_database, "-e", "CREATE DATABASE %s CHARACTER SET utf8;" % mirror_database])
            subprocess.call(mysqldump_command % {
                'options':" ".join(["--ignore-table=%s.%s" % (main_database, table) for table in empty_tables]),
                'tables':''
            }, shell=True)
            subprocess.call(mysqldump_command % {
                'options': '-d',
                'tables': " ".join(empty_tables),
            }, shell=True)

            print "Launching main server ..."
            main_server_env = dict(
                DJANGO__MIRRORS__0__address=mirror_server_address,
                DJANGO__MIRRORING_ENABLED='True',
                DJANGO__CELERY_DEFAULT_QUEUE='runmirror_main_queue',
            )
            running_processes.append(subprocess.Popen(['python', 'manage.py', 'runserver', str(main_server_port)],
                                             env=dict(os.environ, **main_server_env)))
            running_processes.append(subprocess.Popen(
                ['celery', '-A', 'perma', 'worker', '--loglevel=info', '-Q', 'runmirror_main_queue', '--hostname=runmirror_main_queue'],
                env=dict(os.environ, **main_server_env)))

            print "Launching mirror server ..."
            mirror_server_env = dict(
                DJANGO__CELERY_DEFAULT_QUEUE='runmirror_mirror_queue',
                DJANGO__MIRRORING_ENABLED='True',
                DJANGO__DATABASES__default__NAME=mirror_database,
                DJANGO__MIRROR_SERVER='True',
                DJANGO__UPSTREAM_SERVER__address=main_server_address,
                #DJANGO__RUN_TASKS_ASYNC='False',
                DJANGO__MEDIA_ROOT=temp_dir.name,
                DJANGO__CDX_SERVER_URL=mirror_server_address+'/cdx',
            )
            running_processes.append(subprocess.Popen(['python', 'manage.py', 'runserver', str(mirror_server_port)],
                                             env=dict(os.environ, **mirror_server_env)))
            running_processes.append(subprocess.Popen(
                ['celery', '-A', 'perma', 'worker', '--loglevel=info', '-Q', 'runmirror_mirror_queue', '--hostname=runmirror_mirror_queue'],
                env=dict(os.environ, **mirror_server_env)))

            print "Syncing contents ..."
            running_processes.append(subprocess.Popen(['python', 'manage.py', 'shell'],
                            env=dict(os.environ, **mirror_server_env)))

            print "Launching reverse proxy ..."
            root = vhost.NameVirtualHost()
            root.addHost('users.perma.dev', ForwardedReverseProxyResource('127.0.0.1', main_server_port, ''))
            root.addHost('perma.dev', ForwardedReverseProxyResource('127.0.0.1', mirror_server_port, ''))
            site = server.Site(root)
            reactor.listenTCP(8000, site)
            reactor.run()

        finally:
            # make sure all our subprocesses are killed on exit
            for process in running_processes:
                process.terminate()

            # remove temp files
            temp_dir.dissolve()
Ejemplo n.º 12
0

# If the code is completely asynchronous,
# you can use the dummy_threading module
# to avoid RLock overhead.
import dummy_threading
dummy_threading = dummy_threading
amfast.mutex_cls = dummy_threading.RLock

# Setup ChannelSet
channel_set = TwistedChannelSet(notify_connections=True)
rpc_channel = TwistedChannel('rpc')
channel_set.mapChannel(rpc_channel)


def pushMessage(topic, msg):
    channel_set.publishObject(msg, topic)


from ServiceFunctions import *
setup_channel_set(channel_set)

root = vhost.NameVirtualHost()
#root.addHost("192.168.1.17", static.File("E:\\melee\\code\\client\\bin-debug"))
root.putChild('services', rpc_channel)
#root.putChild('images', static.File("E:\\melee\\program\\server\\melee\\public\\image"))
#root.putChild('data', static.File("E:\\melee\\program\\server\\melee\\public\\data"))

static = static
MeleeSiteFactory = Site
Ejemplo n.º 13
0
    def config(self, config, servername=None, dbconfig=None, memconfig=None, masterconf=None):
        """配置服务器
        """
        GlobalObject().json_config = config
        netport = config.get("netport")  # 客户端连接
        webport = config.get("webport")  # http连接
        rootport = config.get("rootport")  # root节点配置
        self.remoteportlist = config.get("remoteport", [])  # remote节点配置列表
        if not servername:
            servername = config.get("name")  # 服务器名称
        logpath = config.get("log")  # 日志
        hasdb = config.get("db")  # 数据库连接
        hasmem = config.get("mem")  # memcached连接
        app = config.get("app")  # 入口模块名称
        cpuid = config.get("cpu")  # 绑定cpu
        mreload = config.get("reload")  # 重新加载模块名称
        self.servername = servername
        if masterconf:
            masterport = masterconf.get("rootport")
            masterhost = masterconf.get("roothost")
            self.master_remote = RemoteObject(servername, "master")
            addr = ("localhost", masterport) if not masterhost else (masterhost, masterport)
            self.master_remote.connect(addr)
            GlobalObject().masterremote = self.master_remote

        if netport:
            self.netfactory = LiberateFactory()
            netservice = services.CommandService("netservice")
            self.netfactory.addServiceChannel(netservice)
            reactor.listenTCP(netport, self.netfactory)

        if webport:
            self.webroot = vhost.NameVirtualHost()
            GlobalObject().webroot = self.webroot
            reactor.listenTCP(webport, DelaySite(self.webroot))

        if rootport:
            self.root = PBRoot()
            rootservice = services.Service("rootservice")
            self.root.addServiceChannel(rootservice)
            reactor.listenTCP(rootport, BilateralFactory(self.root))

        for cnf in self.remoteportlist:
            rname = cnf.get("rootname")
            self.remote[rname] = RemoteObject(self.servername, rname)

        if hasdb and dbconfig:
            log.msg(str(dbconfig))
            dbpool.initPool(**dbconfig)

        if logpath:
            log.addObserver(loogoo(logpath))  # 日志处理
        log.startLogging(sys.stdout)
        GlobalObject().config(netfactory=self.netfactory, root=self.root, remote=self.remote)
        if app:
            __import__(app)
        if mreload:
            _path_list = mreload.split(".")
            GlobalObject().reloadmodule = __import__(mreload, fromlist=_path_list[:1])
        GlobalObject().remote_connect = self.remote_connect
        from . import admin
Ejemplo n.º 14
0
Note: You need to edit your hosts file for this example
to work. Need to add the following entry:

    127.0.0.1   example.com

Then visit http://example.com/ with a web browser and compare the results to
visiting http://localhost/.
"""

from twisted.application import internet, service
from twisted.web import script, server, static, vhost

default = static.Data(b"", "text/html")
# Setting up vhost resource.
default.putChild(b"vhost", vhost.VHostMonsterResource())
resource = vhost.NameVirtualHost()
resource.default = default
# Here we use /var/www/html/ as our root diretory for the web server, you can
# change it to whatever directory you want.
root = static.File("/var/www/html/")
root.processors = {".rpy": script.ResourceScript}
# addHost binds domain name example.com to our root resource.
resource.addHost("example.com", root)

# Setup Twisted Application.
site = server.Site(resource)
application = service.Application("vhost")
sc = service.IServiceCollection(application)
# Only the processes owned by the root user can listen @ port 80, change the
# port number here if you don't want to run it as root.
i = internet.TCPServer(80, site)
Ejemplo n.º 15
0
def loadModule():
    root = vhost.NameVirtualHost()
    root.putChild('opera', OperaGamer())
    root.putChild('dayrecord', DayRecord())
    root.putChild('statistics', Statistics())
    reactor.listenTCP(2014, Site(root))
Ejemplo n.º 16
0
def CreateWebServer(sHost, iPort):
	oWebNode = vhost.NameVirtualHost()
	oWebNode.addHost(sHost, vhost.VHostMonsterResource())
	reactor.listenTCP(iPort, CDelaySite(oWebNode))
	return oWebNode