Example #1
0
    def __init__ (self, MAX_IMAGES=None, debug=0, args=[], optlist=[]):
        ChallengeBase.__init__(self, debug)

        self.message ="""
    usage: %s [-h] [-v] [-d] FQDN ip-add
        -h - usage help 
        -v - verbose / debug output 
        -d - if a domain exists it will be deleted first 

        FQDN - Fully Qualified Domain Name; exaple www.wikipedia.org
        ip-add - ip address
    """ % (PROGRAM_NAME)

        self.optlist = optlist
        self.args = args
        
        self.opt_delete_domain = False

        if "-d" in map(lambda x: x[0], optlist) :
            self.opt_delete_domain = True

        try:
            self.domain_record = self.args[0]
            self.domain_name =  ".".join( self.domain_record.split('.')[1:] )
            self.domain = None

            self.ip_str = self.args[1]

        except Exception, e:
            log("missing params")
            self.usage()
            sys.exit(-1)
def run_check():
    # Important 'True' last!
    check = octoprint_api_req("plugin/softwareupdate/check", None, False, None, False, False, True)
    has_updates = False
    available_updates = []

    if check is not None:
        if "information" in check:
            for plugin in check["information"]:
                if "updateAvailable" in check["information"][plugin]:
                    if check["information"][plugin]["updateAvailable"]:
                        has_updates = True
                        release_notes = check["information"][plugin]["releaseNotes"]
                        new_version = check["information"][plugin]["information"]["remote"]["name"]

                        available_updates.append({
                            "plugin": plugin,
                            "version": new_version,
                            "release_notes": release_notes
                        })

    if has_updates:
        # Tell server!
        log("OctoPrint or plugin(s) has an update available!")
        website_ping_update("&updates_available=" + url_quote(json.dumps(available_updates)))
Example #3
0
    def run(self):
        debug("run start")
        ChallengeBase.run(self)
        
        if self.check() is False:
            self.usage()
            sys.exit(-1)

        log("Creating new DNS zone %s" % self.domain_name)
        self.domain=self.dns.create(name=self.domain_name, emailAddress="*****@*****.**", ttl=300, comment="challenge9 domain")

        log("Creating cloud server ...(please wait the build can take a while)")
        self.server=self.cs.servers.create(name=self.fqdn_name, flavor=self.flavor_id, image=self.image_id)

        wait = WaitingForTask(self.check_cs_build, self.server)
        if wait.wait_for_tasks() == False: 
            log("Cloud server build failed, deleting created objects")
            self.server.delete()
            self.domain.delete()
            sys.exit(-1)

        # get all public IPs
        net = [ i["addr"] for i in self.server.addresses["public"] ] 
        self.net = utils.get_ipv4net(net)

        cname_rec = {"type": "A",
                    "name": self.fqdn_name,
                    "data": self.net,
                    "ttl": 300,
                    "comment": "challenge9 rec"}

        self.recs = self.domain.add_record(cname_rec)

        log("DNS zone %s has been udpated and a new A record created" % (self.domain_name))
        log("rec A: %s -> %s" % (self.fqdn_name, self.net))
Example #4
0
def execCompile(session_path, src_path, lang):
    Base.log('[TDMaker]编译程序 (JUDGE_COMPILING)')
    # 获取编译程序临时文件名
    if str(lang) == 'java':
        # 将提交的代码重命名为Main.java
        scname = os.path.join(session_path, "Main.java")
        # 编译
        ccmd = Config.SOURCE_CODE_COMPILE_CMD.get(lang)
        # session_path: Java Lib位置,src_path 源代码位置
        exitcode, output = commands.getstatusoutput(ccmd %
                                                    (session_path, scname))
    else:
        output_exec = os.path.join(session_path, "m")
        # 根据评测语言获取编译命令
        ccmd = Config.SOURCE_CODE_COMPILE_CMD.get(lang)
        # 运行编译并截取编译器返回的数据
        # session_path
        exitcode, output = commands.getstatusoutput(ccmd %
                                                    (src_path, output_exec))

    # 判断是否正确编译
    if exitcode != 0:
        print output
        return False, output
    return True, None
Example #5
0
    def retrieved_draw(self, gameId, token, drawCount):
        url = self.sle.url_retrieved_draw(gameId)

        headers = {
            'accept':
            'application/json, text/plain, */*',
            'accept-language':
            'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'authorization':
            token,
            'origin':
            'https://mx2.stgdevops.site',
            'referer':
            'https://mx2.stgdevops.site/',
            'sec-fetch-dest':
            'empty',
            'sec-fetch-mode':
            'cors',
            'sec-fetch-site':
            'same-site',
            'user-agent':
            'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 '
            '(KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        }
        params = {'drawcount': drawCount}
        r = self.s.get(url, headers=headers, params=params)
        log(f"Retrieved draw: {r.json()}")

        return r.json()
Example #6
0
    def create_users(self):
        debug("create_users start")
        password = "******"

        for user in self.db_users:
            self.db_instance.create_user(user, password, self.dbs)
            log("Created user %s pass %s in db %s" % (user, password, self.dbs))
Example #7
0
def get_judge_queue_item():

    conn = Base.dbManager.getConn()
    try:
        cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        result = cursor.execute(
            'SELECT * FROM `problem_judgequeue` WHERE `queue_status` = 0 OR `queue_status` = -1 ORDER BY `queue_status` DESC, `id` ASC LIMIT 1'
        )
        if result > 0:
            res = cursor.fetchone()
            id = res.get('id')
            sid = res.get('judge_status_id', 0)
            queue_status = res.get('queue_status', 0)
            if queue_status == -1:
                Base.log("[JudgeService]****重判队列****")
            cursor.execute(
                'UPDATE `problem_judgequeue` SET `queue_status` = 1 WHERE `id` = %s',
                (str(id), ))
            conn.commit()
            cursor.execute(
                'UPDATE `problem_judgestatus` SET `flag` = -1 WHERE `id` = %s',
                (str(sid), ))
            conn.commit()
            cursor.close()
            conn.close()
            return id, sid
        else:
            cursor.close()
            conn.close()
            return None, ''
    except BaseException, ex:
        conn.rollback()
        conn.close()
        return None, str(ex)
Example #8
0
def join(nick):
    """Actions to perform on user join"""
    rank = v.getrank(nick)    
    if not v.listvar(nick) and config.get('auto-add'):
        v.makevarfile(nick)
        
    c.raw("WHOIS " + nick)
    ACC_CHECKED = False
    
    if config.get('join-message'):
        c.msg(f.LIGHTBLUE + "Welcome to the Rapid IRC, " + f.PURPLE + nick + f.LIGHTBLUE + ".", nick)
    
    if rank == 0 and config.get('auto-kick'):
        c.kick(nick, "NotWhitelisted")
        
    elif rank >= 3:
        if config.get('auto-op'):
            c.mode(["+o", nick])
            c.msg("You have been opped by Oracle", nick)
        else:
            c.msg("Oracle auto-op is disabled. Identify with NickServ to receive op.", nick)
            
    else:
        c.mode(["+v", nick])
       
    if config.get('check-mail'):
        if not m.check(nick):
            c.msg("You have no new mail.", nick)
        else:
            c.msg("You have mail! Use '?mail check' to see.", nick)
            
    log(nick + " joined. Rank: " + str(rank), m_type='JOIN', colour=Fore.MAGENTA)
Example #9
0
def execCompile(session_path, src_path, lang):
    Base.log('[JudgeService]编译程序 (JUDGE_COMPILING)')
    # 获取编译程序临时文件名
    if str(lang) == 'java':
        # 将提交的代码重命名为Main.java
        scname = os.path.join(session_path, "Main.java")
        shutil.copy(src_path, scname)
        src_path = scname
        # 编译
        ccmd = Config.SOURCE_CODE_COMPILE_CMD.get(lang)
        exitcode, output = commands.getstatusoutput(ccmd %
                                                    (session_path, src_path))
    else:
        output_exec = os.path.join(session_path, "m")
        # 根据评测语言获取编译命令
        ccmd = Config.SOURCE_CODE_COMPILE_CMD.get(lang)
        # 运行编译并截取编译器返回的数据
        exitcode, output = commands.getstatusoutput(ccmd %
                                                    (src_path, output_exec))

    # 判断是否正确编译
    if exitcode != 0:
        print output
        return False, output
    return True, None
Example #10
0
    def profile(self, username='******'):
        url = self.sle.url_profile()

        _, get_token = self.sle_login(username)
        headers = {
            'accept':
            'application/json, text/plain, */*',
            'accept-language':
            'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'authorization':
            get_token['token'],
            'origin':
            'https://mx2.stgdevops.site',
            'referer':
            'https://mx2.stgdevops.site/',
            'sec-fetch-dest':
            'empty',
            'sec-fetch-mode':
            'cors',
            'sec-fetch-site':
            'same-site',
            'user-agent':
            'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 '
            '(KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        }

        r = self.s.get(url, headers=headers)
        log(f"Status code: {r.status_code}\nProfile{r.json()}")

        return r.status_code, r.json()
Example #11
0
    def active_and_previous_period(self, gameId):

        url = self.sle.url_active_and_previous_period(gameId)

        r = self.s.get(url)

        log(f"Active and previous period: {r.json()}")
        return r.json()
Example #12
0
 def __init__(self):
     self.questions = self.load_trivia()
     self.current = ""
     self.trivia_time = LoopTimeThread(config.get('trivia-interval'), self)
     self.trivia_time.start()
     self.f = f.WHITE + "[" + f.PURPLE + "Trivia" + f.WHITE + "] "
     self.disabled = False
     log("Trivia initialized.", m_type="STARTUP", colour=Fore.CYAN)
Example #13
0
    def show(self):
        debug("show start")

        dom = self.dns.find(name=self.domain_name)

        log("domain name: %s created at %s" % (dom.name, dom.created) )
        for r in dom.list_records() : 
            log("record %3s %s -> %s" % (r.type, r.name, r.data) )
Example #14
0
def _send_irc(raw_msg):
    try:
        s.send(raw_msg)
        log(raw_msg, m_type="RAWMESSAGE", colour=Fore.GREEN, lg='send', l_type=2)
        return True
    except Exception:
        traceback.print_exc()
    return False
Example #15
0
 def __init__(self):
     self.questions = self.load_trivia()
     self.current = ""
     self.trivia_time = LoopTimeThread(config.get('trivia-interval'), self)
     self.trivia_time.start()
     self.f = f.WHITE + "[" + f.PURPLE + "Trivia" + f.WHITE + "] "
     self.disabled = False
     log("Trivia initialized.", m_type="STARTUP", colour=Fore.CYAN)
Example #16
0
def execJudge(session_path, config, pid, sid, testdatas):

    # 这是用来判断TLE计数的,因为判题机核心是按每次每个测试数据来给时间,但我是按总计来给时间的
    timeuseTotal = 0
    # 最大内存使用
    memuseMax = 0
    # 最大时间限制
    TIMELIMIT = config.get('time_limit', 10000)
    results = {}
    outdatas = {}

    testdatas.sort(key=lambda obj: obj.get('order'))

    for td in testdatas:
        # 取得测试数据UUID
        tdid = td.get('handle', None)
        tname = td.get('name', None)
        # 测试数据错误System Error
        if tdid is None:
            return results, 8, 0, 0, ''
        # 测试数据是否有效
        if td.get('available', True) is False:
            continue
        Base.log('[JudgeService]运行测试数据:%s[%s]  (TEST_DATA_VIEW)' %
                 (str(tdid), str(tname)))
        inFile = os.path.join(Config.PROBLEM_TESTDATA_DIR,
                              "%s/%s.in" % (str(pid), str(tdid)))
        outFile = os.path.join(Config.PROBLEM_TESTDATA_DIR,
                               "%s/%s.out" % (str(pid), str(tdid)))
        # 测试数据文件是否存在
        if os.path.exists(inFile) and os.path.exists(outFile):
            # 执行评测
            (crst, outdata) = execRunOnce(session_path, tdid, config, inFile,
                                          outFile)
            # 保存评测结果
            results[tdid] = crst
            # 保存运行输出
            outdatas[tdid] = outdata
            # 统计时间
            timeuseTotal += int(crst.get('timeused', 0))
            # 获取最大内存使用
            mem = crst.get('memoryused', 0)
            if mem > memuseMax:
                memuseMax = mem
            # 如果任意测试数据出错,则终止评测,返回当前评测结果
            if crst.get('result') != 0:
                return results, crst.get(
                    'result'), timeuseTotal, memuseMax, outdatas
            # 超时终止评测,返回评测结果
            if timeuseTotal > TIMELIMIT:
                return results, 2, timeuseTotal, memuseMax, outdatas  # TLE
        else:
            # 测试数据文件不存在,SE
            return None, 8, 0, 0, ''

    # 评测全部通过
    return results, 0, timeuseTotal, memuseMax, outdatas
Example #17
0
    def check(self):
        debug("check start")

        try:
            self.clb.find(name=self.lb_name) 
            log("found lb %s, please remove it before reruning the script" % self.lb_name )
            ret = False
        except exc.NotFound, e:
            ret = True
Example #18
0
 def check(self):
     debug("check start")
     ret = True
 
     try:
         self.image=self.cs.images.find(id=self.image_id)
     except exc.NotFound, e:
         log("The image id is incorrect")
         ret=False
Example #19
0
    def check_network_objects(self):
        debug("check_network_objects start")

        for net in self.cnw.list() :
            if net.name == self.network_name :
                log("Deleted existing network obj %s" % self.network_name)
                net.delete()

        return True
Example #20
0
def restart(nick):
    log("Restart command issued by " + nick + ".", m_type="RESTART", colour=Fore.YELLOW, reset=False)
    say("\00307\x02Restarting!\00307\x02")
    _send_irc("QUIT\r\n")

    args = sys.argv[:]
    args.insert(0, sys.executable)
    if sys.platform == 'win32':
        args = ['"%s"' % arg for arg in args]
    os.execv(sys.executable, args)
Example #21
0
    def handle(self, nick, val):
        if val > config.get("kick"):
            connect.kick(nick, "Spamming")
            connect.say(f.YELLOW + "User " + f.RED + nick + f.YELLOW + " was kicked for spamming.")
            log("User: "******" was kicked for spamming", m_type="SPAMHANDLR", reset=False)
            # ACTION_LOG.info(Fore.RED + 'KCK' + Fore.RESET + ' User: '******' was kicked for spamming')
            del self.FLOOD[nick]

        elif val > config.get("warn"):
            connect.msg(f.YELLOW + "Please slow down with your messages, or else you'll be kicked.", nick)
Example #22
0
    def show(self):
        debug("show start")

        lb_properties = [ "name", "status", "created", "virtual_ips", "port", "protocol", "algorithm", "nodeCount" ]
        
        for prop in lb_properties : 
            log("lb %s : %s " % (prop, getattr(self.lb, prop)) )

        for n in self.nodes:
            log("Node: %s" % n.to_dict() )
Example #23
0
    def upload_dir(self, path):
        debug("upload_dir start")

        try:
            cont = self.cf.get_container(self.container)
            log("container %s exists, all newly uploaded files will overwrite existing cloud files" %
                self.container)

        except exc.NoSuchContainer, e:
            log("container %s don't exists, create a new one ..." % (self.container,) )
            cont = self.cf.create_container(self.container)
Example #24
0
 def run(self):
     debug("run start")
     ChallengeBase.run(self)
     
     if self.check(args) is False:
         self.usage()
         sys.exit(-1)
     
     log("Uploading directory %s to container %s" % (self.path, self.container))
     self.upload_dir(self.path) 
     self.wait_for_upload()
Example #25
0
    def check_ssh_pub_key(self):
        debug("check_ssh_pub_key start")
        ret = True

        if self.ssh_public_key_name == None:
            try:
                self.ssh_public_key_name = "%s/.ssh/id_rsa.pub" % os.environ["HOME"]
            except Exception, e:
                ret=False
                log("Please specify a path to ssh public key")
                sys.exit(-1)
Example #26
0
    def enable_cdn(self, container_name):
        debug("enable_cdn start")
        ret=True

        container = self.get_container(container_name)
        if container.cdn_enabled == False:
            container.make_public(ttl=1200)
        else:
            log("container %s is alrady CDN enabled")
            ret = False
        
        return ret
Example #27
0
    def run(self):
        debug("run start")
        ChallengeBase.run(self)
        
        if self.check() is False:
            self.usage()
            sys.exit(-1)

        log("Creating container %s and uploading small %s file." %  (self.container_name, self.index_name) )
        self.set_container()
        self.set_dns()
        self.show()
Example #28
0
    def wait_for_lb_change(self):
        debug("wait_for_lb_change start")

        wait = WaitingForTask(self.check_lb, [self.lb_name], sleep_time=5, max_timeout=1)
        if wait.wait_for_tasks() == False: 
            log("Aborting as the build of lb is taking too long; all created objects will be deleted")
            
            for s in self.servers :
                s.delete()
            self.lb.delete()

            sys.exit(-1)
Example #29
0
    def show(self):
        debug("show start")

        log("-" * 70)
        log("vip name %s and ip %s" % (self.lb_name, self.vip_address) )
        
        for i in xrange(0, self.cs_count) :
            name= "%s-%d" % (self.server_prefix, i)
            log("cloud server %s added to pool as %s" % (name, self.nodes[i].address) )

        log("Error page is stored in container %s under name %s" % (self.container_name, self.error_page_name) )
        log("to check if the config works try to: curl -v http://%s" % self.vip_address)
Example #30
0
    def check_blocks(self) :
        debug("check_storage start")
        ret = True

        for i in xrange(0, self.cs_count) :
            name="%s-%d" % (self.storage_name, i)
            try:
                storage=self.cbs.find(name=name)
                storage.delete()
                log("Deleted existing block storage image  %s" % name )
            except Exception, e:
                debug("There is not block storage with name %s" % name )
Example #31
0
    def check_cloud_servers(self):
        debug("check_cloud_servers start")
        ret = True

        for i in xrange(0, self.cs_count) :
            name= "%s-%d" % (self.server_prefix, i)
            try:
                c=self.cs.servers.find(name=name)
                c.delete()
                log("Deleted existing cloud server %s" % name )
            except Exception, e:
                debug("There is not cs with name %s" % name )
Example #32
0
    def check_existing_lb(self):
        debug("check_existing_lb start")
        ret = True

        try:
            lb=self.clb.find(name=self.lb_name) 
            if self.opt_delete :
                lb.delete()
            else :
                log("found lb %s, please remove it before reruning the script" % self.lb_name )
                ret = False
        except exc.NotFound, e:
            pass
Example #33
0
    def little_game_play(
        self,
        token=None,
        choice="TAIL" or 'HEAD',
        gameId="SC" or "RPS" or "HL",
        platform="Desktop",
        roomId=1271981426123892,
    ):

        url = self.sle.url_little_game_play()

        headers = {
            'accept':
            'application/json, text/plain, */*',
            'accept-language':
            'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'authorization':
            token,
            'content-length':
            '78',
            'content-type':
            'application/json',
            'origin':
            'https://mx2.stgdevops.site',
            'referer':
            'https://mx2.stgdevops.site/',
            'sec-fetch-dest':
            'empty',
            'sec-fetch-mode':
            'cors',
            'sec-fetch-site':
            'same-site',
            'user-agent':
            'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko)'
            ' Chrome/86.0.4240.198 Mobile Safari/537.36',
            'x-vendor-id':
            'MX2',
        }

        data = {
            'choice': choice,
            'gameId': gameId,
            'platform': platform,
            'roomId': roomId,
        }

        r = self.s.post(url, headers=headers, json=data)
        log(f"\nLittle game's play:\n{r.json()}")

        return r.json()
Example #34
0
def work():
    try:
        global lastActiveTime
        lastActiveTime = -1
        # 1. 从数据库队列获取新的评测请求
        queue_id = get_judge_queue_item()
        if queue_id is not None:
            # 2. 读取评测状态的详情
            judge_options = Base.api(Config.TDmakerAPI_GET_JUDGE_LIST_ITEM %
                                     str(queue_id))
            if judge_options is False:
                Base.log('[TDMaker]获取评测状态信息失败。(LOAD_STATUS_INFO_ERROR)',
                         logging.ERROR)

            lastActiveTime = int(time.time())
            lang = str(judge_options.get('lang', ''))
            Base.log('[TDMaker]获取队列成功,ID:%s,评测语言:%s(JUDGEMENT_LOAD_QUEUE)' %
                     (str(queue_id), lang))
            # 3.执行评测
            rel = Function.main(judge_options)
            # 4.报告评测结果
            apirel = Base.api(
                Config.TDmakerAPI_JUDGE_RESULT_RECEICER % str(queue_id),
                {'result': json.dumps(rel)})
            if apirel is not False:
                Base.log('[TDMaker]评测成功结束。(JUDGE_FINISHED)')

    except BaseException, ex:
        Base.log(
            '[TDMaker]评测机业务逻辑发生错误(WORK_RUNTIME_ERROR)\n[问题描述:%s]' % str(ex),
            logging.ERROR)
        return
Example #35
0
    def show(self):
        debug("show start")

        log("Static site details: (make sure you point your DNS to Rackspace Cloud DNS servers):")
        log("ping %s" % self.rec_CNAME)
        log("curl -v http://%s/%s" % (self.rec_CNAME, self.index_name) )
        log("curl -v http://%s" % (self.rec_CNAME_data) )
Example #36
0
    def create_record(self, domain_name, ip_str) :
        debug("create_record start")

        # Substitute your actual domain name and IP addresses here
        a_rec = {"type": "A",
                "name": self.domain_record,
                "data": ip_str,
                "ttl": 6000
                }

        log("Adding records to our domain ...")
        recs = self.domain.add_records([a_rec])

        return True
Example #37
0
    def cancel_bet(
        self,
        token=None,
        drawIdString='202012160932',
        drawid='2020121600932',
        gameid='NYSSC1F',
        txnid='1282027396351040',
    ):
        url = self.sle.url_cancel_bet()

        headers = {
            'accept':
            'application/json, text/plain, */*',
            'accept-language':
            'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'authorization':
            token,
            'content-length':
            '100',
            'content-type':
            'application/json',
            'origin':
            'https://mx2.stgdevops.site',
            'referer':
            'https://mx2.stgdevops.site/',
            'sec-fetch-dest':
            'empty',
            'sec-fetch-mode':
            'cors',
            'sec-fetch-site':
            'same-site',
            'user-agent':
            'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 '
            '(KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
            'x-vendor-id':
            'MX2',
        }

        data = [{
            'drawIdString': drawIdString,
            'drawid': drawid,
            'gameid': gameid,
            'txnid': txnid,
        }]

        r = self.s.put(url, headers=headers, json=data)
        log(f"Cancel bet:{r.json()}\nStatus code: {r.status_code}")

        return r.status_code, r.json()
Example #38
0
    def check(self):
        debug("check start")
        ret = True

        if self.check_domain_name(self.domain_name) == False: 
            log("Invalid domain name string")
            ret = False
        
        if self.check_ip(self.ip_str) == False:
            log("Invalid ip address")
            ret = False
        else :
            self.ip_str = self.convert_ip(self.ip_str)
            
        return ret
Example #39
0
    def check_cert(self):
        debug("check_cert start")
        ret = True

        if self.cert_use_default : 
            return True

        try:
            f = open(self.cert_key_name)
            self.cert_key = f.read()
            f.close()
        except Exception, e:
            log("Can't read or the private key file has incorrect data %s" % self.cert_key_name)
            log(e)
            ret = False
Example #40
0
    def check(self):
        debug("check start")
        ret = True

        if self.container_name in self.cf.list_containers() :
            self.container = self.cf.get_container(self.container_name)
        else :
            log("Can't find container name %s under your cloud account %s" % (self.container_name, self.account_name))
            return False

        debug("found container %s, objects %s, bytes %s" % (self.container.name, 
            self.container.object_count, 
            self.container.total_bytes))
        
        return ret
Example #41
0
    def transaction_record(
        self,
        token=None,
        start='1607270400000',
        end='1607443199999',
        types='LITTLE_GAME_DRAW_RETURN_BET,'
        'LITTLE_GAME_TIMEOUT_RETURN_BET,'
        'LITTLE_GAME_CLOSE_RETURN_BET',
        offset='0',
    ):

        url = self.sle.url_transaction_record()

        headers = {
            'accept':
            'application/json, text/plain, */*',
            'accept-language':
            'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'authorization':
            token,
            'origin':
            'https://mx2.stgdevops.site',
            'referer':
            'https://mx2.stgdevops.site/',
            'sec-fetch-dest':
            'empty',
            'sec-fetch-mode':
            'cors',
            'sec-fetch-site':
            'same-site',
            'user-agent':
            'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 ABuild/MRA58N) AppleWebKit/537.36 '
            '(KHTML, like Gecko) Chrome/86.0.4240.198 Mobile Safari/537.36',
            'x-vendor-id':
            'MX2',
        }

        params = {
            'start': start,
            'end': end,
            'types': types,
            'offset': offset,
        }

        r = self.s.get(url, headers=headers, params=params)
        log(f"\rSle transaction record: {r.json()}")

        return r.json()
Example #42
0
    def handle(self, nick, val):
        if val > config.get('kick'):
            connect.kick(nick, "Spamming")
            connect.say(f.YELLOW + 'User ' + f.RED + nick + f.YELLOW +
                        ' was kicked for spamming.')
            log('User: '******' was kicked for spamming',
                m_type='SPAMHANDLR',
                reset=False)
            #ACTION_LOG.info(Fore.RED + 'KCK' + Fore.RESET + ' User: '******' was kicked for spamming')
            del self.FLOOD[nick]

        elif val > config.get('warn'):
            connect.msg(
                f.YELLOW +
                'Please slow down with your messages, or else you\'ll be kicked.',
                nick)
Example #43
0
    def delete_db_instance(self, db_instance_name):
        debug("delete_db_instance start")

        try:
            db = self.cdb.find(name=db_instance_name)

            if self.opt_delete_instance:
                log("Found existing db instance %s, deleting it ..." % db_instance_name)
                db.delete()
                time.sleep(5)  # ugly hack
            else:
                log("db instace exists; remove it or provide other instance name, canceling ...")
                return False

        except exc.NotFound, e:
            debug("no instace %s found" % db_instance_name)
Example #44
0
    def set_dns(self):
        debug("set_dns start")

        log("Creating DNS domain %s and setting CNAME records" % self.domain_name)

        self.rec_CNAME = self.container_name + "." + self.domain_name
        self.rec_CNAME_data = self.container.cdn_uri.partition("//")[2]

        domain=self.dns.create(name=self.domain_name, emailAddress="*****@*****.**", ttl=300, comment="challenge8 domain")
        cname_rec = {"type": "CNAME",
                    "name": self.rec_CNAME,
                    "data":  self.rec_CNAME_data,
                    "ttl": 300,
                    "comment": "cloud files CDN enabled container"}
        self.recs = domain.add_record(cname_rec)
        self.domain = domain
Example #45
0
def start():    
    try:
        global s
        s = socket.socket()
        s.connect((config.get('host'), config.get('port')))
        _send_irc("NICK "
                + config.get('nick')
                + "\r\n")
        _send_irc("USER "
                + config.get('ident') + " " + config.get('host')
                + " bla :" + config.get('realname')
                + "\r\n")
        return s
    except Exception:
        traceback.print_exc()
        log("Could not connect to server.", m_type="WARNING", colour=Fore.RED, reset=False)
        return False
Example #46
0
def exe_apply():
        cwd = get_realpath()
        lgpath = "%s/%s" % (cwd,'../logs/matrix')
        lg = log(lgpath)
        aly_res = apply_vmres(lg)
        while True:
                aly_res.do_apply()
                time.sleep(1)
Example #47
0
def submit_apply():
        cwd = get_realpath()
        lgpath = "%s/%s" % (cwd,'../logs/matrix')
        lg = log(lgpath)
        aly_res = apply_vmres(lg)
        while True:
                aly_res.do_instance_create()
                time.sleep(1)
Example #48
0
def create_vm():
        cwd = get_realpath()
        lgpath = "%s/%s" % (cwd,'../logs/matrix')
        lg = log(lgpath)
        aly_res = apply_vmres(lg)
        while True:
                aly_res.do_query_create_status()   #这个动作比较耗时
                time.sleep(2)
Example #49
0
def vm_opt_query():
        cwd = get_realpath()
        lgpath = "%s/%s" % (cwd,'../logs/matrix')
        lg = log(lgpath)
        opt_vm = opt_vmres(lg)
        while True:
                opt_vm.do_vm_instance_opt_status_query()
                time.sleep(1)
Example #50
0
def main(judge_option):
    problem_id = judge_option.get('problem_id')
    status_id = judge_option.get('status_id')
    session_id = uuidstr()  # 评测Session
    session_path = os.path.join(Config.TEMP_PROGRAM_STORAGE, session_id)
    if not os.path.isdir(session_path):
        os.mkdir(session_path)
    # 编译代码
    source_code = "%s/%s" % (Config.USER_UPLOADCODE_DIR,
                             judge_option.get('code_path'))
    flag, msg = execCompile(session_path, source_code,
                            judge_option.get('lang'))
    if not flag:
        Base.log('[JudgeService]编译错误!(COMPILE_ERROR)', logging.ERROR)
        return {"exitcode": 7, 'ce_info': msg}  # Compile Error
    # 读取测试数据列表
    test_data = judge_option.get('test_data', None)
    if (test_data is None) or (isinstance(test_data, dict)):
        Base.log(
            '[JudgeService]载入测试数据配置信息错误!(问题ID:%s)(LOAD_TEST_DATA_FAILED)' %
            str(problem_id), logging.ERROR)
        return {"exitcode": 8}  # System Error
    # 执行评测
    (result, exitcode, timeuse, memuse,
     outdatas) = execJudge(session_path, judge_option, problem_id, status_id,
                           test_data)

    try:
        if str(judge_option.get('lang')) == 'java':
            os.remove(os.path.join(session_path, "Main.class"))
            os.remove(os.path.join(session_path, "Main.java"))
        else:
            os.remove(os.path.join(session_path, "m"))
    except:
        pass

    # 返回评测结果
    return {
        'outdatas': outdatas,
        "result": result,
        "exitcode": exitcode,
        'timeused': timeuse,
        'memused': memuse,
        'session_id': session_id
    }
Example #51
0
    def get_launch_token(self, username='******'):

        url = self.sle.url_get_launch_token()

        _, get_token = self.sle_login(username)

        headers = {
            'Host':
            'mx2-api.stgdevops.site',
            'Connection':
            'keep-alive',
            'Content-Length':
            '33',
            'Accept':
            'application/json, text/plain, */*',
            'Authorization':
            get_token['token'],
            'User-Agent':
            'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 '
            '(KHTML, like Gecko) Chrome/86.0.4240.193 Mobile Safari/537.36',
            'Content-Type':
            'application/json',
            'Origin':
            'https://mx2.stgdevops.site',
            'Sec-Fetch-Site':
            'same-site',
            'Sec-Fetch-Mode':
            'cors',
            'Sec-Fetch-Dest':
            'empty',
            'Referer':
            'https://mx2.stgdevops.site/',
            'Accept-Language':
            'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        }

        data = {"lang": "zh-CN", "platformtype": 1}

        r = self.s.put(url, headers=headers, json=data)
        log(f"Get game's launch token:\n{r.json()}")
        time.sleep(1)

        return r.status_code, r.json()
Example #52
0
    def decrement(self):
        try:
            keys = self.FLOOD.keys()
            for nick in keys:
                self.FLOOD[nick] -= 1
                if self.FLOOD[nick] == 0:
                    del self.FLOOD[nick]

            say = False
            for nick, val in self.FLOOD.iteritems():
                log(nick + ': ' + str(val), m_type='SPAMHANDLR')
                #ACTION_LOG.info(Style.BRIGHT + Fore.BLUE + 'SPAMHDLR ' + Fore.RESET + nick + ': ' + str(val))
                say = True
            if say:
                log('Decremented FLOOD dict', m_type='SPAMHANDLR')
                #ACTION_LOG.info(Style.BRIGHT + Fore.BLUE + 'SPAMHDLR ' + Fore.RESET + ' Decremented FLOOD dict')

        except:
            traceback.print_exc()
Example #53
0
def main2():
        cwd = get_realpath()
        lgpath = "%s/%s" % (cwd,'../logs/matrix')
        lg = log(lgpath)
        aly_res = apply_vmres(lg)
        while True:
                aly_res.do_instance_create()
#                 time.sleep(1)
                aly_res.do_query_create_status()
#                 time.sleep(1)
                aly_res.do_apply()
                time.sleep(1)
Example #54
0
def vm_opt_total():
        '''
        提交vm操作请求以及vm操作结果查询
        '''
        cwd = get_realpath()
        lgpath = "%s/%s" % (cwd,'../logs/matrix')
        lg = log(lgpath)
        opt_vm = opt_vmres(lg)
        while True:
                opt_vm.do_vm_instance_opt()
                opt_vm.do_vm_instance_opt_status_query()
                time.sleep(1)
Example #55
0
def execRunOnce(session_path, handel, config, td_in_path):
    my_out_filename = "%s.outdata" % handel
    # 获取程序运行结果输出文件的绝对路径
    tMP_PATH = os.path.join(session_path, my_out_filename)
    # 只读打开测试数据输入样例文件
    fin = open(td_in_path)
    # 清理遗留文件
    if os.path.exists(tMP_PATH):
        os.remove(tMP_PATH)
    # 只写打开运行结果文件
    ftemp = open(tMP_PATH, 'w+')
    # 创建评测配置信息
    # java -classpath <session_path> Main
    if str(config.get('lang')) == 'java':
        args = [
            'java', '-client', '-Dfile.encoding=utf-8', '-classpath',
            session_path, "Main"
        ]

    else:
        args = [os.path.join(session_path, "m")]
    time_limit = config.get('time_limit', 1000)
    memory_limit = config.get('memory_limit', 32768)
    runcfg = {
        'args': args,  # 运行程序文件
        'fd_in': fin.fileno(),
        'fd_out': ftemp.fileno(),
        'timelimit': time_limit,
        'memorylimit': memory_limit
    }
    Base.log('[TDMaker]运行源程序!(JUDGE_PROCESS_START)')
    # 执行Lorun模块,运行程序
    rst = lorun.run(runcfg)
    Base.log('[TDMaker]程序运行结束!(JUDGE_PROCESS_FINISHED)')
    # 释放文件
    fin.close()
    ftemp.close()

    # 返回运行结果
    return rst
Example #56
0
def main(judge_option):
    problem_id = judge_option.get('problem_id')
    session_id = uuidstr()  # 评测Session
    session_path = os.path.join(Config.TEMP_PROGRAM_STORAGE, session_id)
    if not os.path.isdir(session_path):
        os.mkdir(session_path)

    # 将示例代码写入文件
    try:
        source_code = "%s/%s" % (session_path, judge_option.get('code_path'))
        source_code_fp = open(source_code, "w+")
        source_code_fp.write(judge_option.get('demo_code').encode("utf-8"))
        source_code_fp.close()
    except:
        Base.log('[TDMaker]代码写入错误!(WRITE_CODE_ERROR)', logging.ERROR)
        return {"exitcode": 8}  # Compile Error

    # 编译代码
    flag, msg = execCompile(session_path, source_code,
                            judge_option.get('lang'))
    if not flag:
        Base.log('[TDMaker]编译错误!(COMPILE_ERROR)', logging.ERROR)
        return {"exitcode": 7, 'ce_info': msg}  # Compile Error
    # 读取测试数据列表
    test_data = judge_option.get('test_data', None)
    if (test_data is None) or (isinstance(test_data, dict)):
        Base.log(
            '[TDMaker]载入测试数据配置信息错误!(问题ID:%s)(LOAD_TEST_DATA_FAILED)' %
            str(problem_id), logging.ERROR)
        return {"exitcode": 8}  # System Error
    # 执行评测
    (exitcode, timeuse, memuse) = execJudge(session_path, judge_option,
                                            problem_id, test_data)

    try:
        if str(judge_option.get('lang')) == 'java':
            os.remove(os.path.join(session_path, "Main.class"))
            os.remove(os.path.join(session_path, "Main.java"))
        else:
            os.remove(os.path.join(session_path, "m"))
    except:
        pass

    # 返回评测结果
    return {
        "exitcode": exitcode,
        'timeused': timeuse,
        'memused': memuse,
        'session_id': session_id
    }
Example #57
0
def main(socket):
    """Main loop, everything happens through this loop
    Data received from s is placed in the readbuffer,
    which is then split into lines that are iterated
    over as incoming messages.
    
    Returning false will close Oracle, and true will
    reload oracle.py
    """   
    readbuffer = ""
    
    global RELOAD
    global EXIT
    RELOAD = EXIT = False
    
    if config.get('trivia'):
        global trivia
        trivia = games.Trivia()
        
    if config.get('command-line'):
        global commandline
        commandline = input.CommandLine()
        
    if config.get('random-points'):
        global randompoints
        randompoints = games.RandomPoints()
        
    
    while True:
        try:
            # get messages from the server
            readbuffer = readbuffer + socket.recv(1024)
        except Exception:
            # this only happens when the server throttles the connection
            log("Cannot connect, throttled by server.", m_type="WARNING", colour=Fore.RED, reset=False)
            log("Will try again in 20 seconds...", m_type="WARNING", colour=Fore.RED, reset=False)
            time.sleep(20)
            # reloads the bot, rather than exit
            return True
            
        temp = string.split(readbuffer, "\n")
        readbuffer = temp.pop()

        for line in temp:
            line = string.split(string.rstrip(line))
            message = " ".join(line)
                 
            # reply to every periodic PING event
            if(line[0] == "PING"): 
                c.ping(line[1])
                
            # join the channel
            elif(line[1] == "376" and line[2] == config.get('ident')): 
                c.join()
                
            # identify with nickserv after being prompted
            elif("NickServ!" in line[0] and line[4] == "nickname"):
                c.identify()
                log("Identified with NickServ", m_type="NICKSERV", colour=Fore.GREEN)
                #ACTION_LOG.info(Style.BRIGHT + Fore.CYAN + "IDENTIFY " + Fore.WHITE + "Identified")
                
            # return of NAMES list
            elif(line[1] == "353"): 
                nicks = "".join(message.split(":")[2].replace("@","").replace("+","").replace("Oracle ",""))
                global ATTENTION
                if ATTENTION:
                    c.say(nicks)
                    ATTENTION = False
                users = nicks.replace(config.get('server-bots')[0],"").replace(config.get('server-bots')[1],"")
                if config.get('random-points'):
                    randompoints.add_users(users)
                
            # realise that Orace just joined, say welcome
            elif("JOIN" in line) and ("Oracle" in message):
                # if welcome-message == false
                if not config.get('welcome-message'):
                    pass
                else:
                    c.say(format.replace(config.get('welcome-message')))
                
            # throw nick to join() after they join
            elif ("JOIN" in line or ":JOIN" in line) and not ("Oracle" in message):
                join(line[0].split(":",1)[1].split("!",1)[0])
            
            # possible 'line(s)'
            # ':[email protected]', 'PRIVMSG', '#rapid', ': [message]'
            # ':[email protected]', 'PRIVMSG', 'Oracle', ': [message]'
            # ':nova.esper.net', 'NOTICE', '*' ':***', 'foo', 'is', 'bar'
            # 'PING', ':nova.esper.net'
            # ':[email protected]', 'MODE', '#rapid', '+o', 'Oracle'
            # ':nova.esper.net', '001', 'Oracle', '[thing]'
            
            if (len(line) > 2):     
                # grab nick from first string in line
                # grab message from fourth string onwards
                try:
                    nick = line[0].replace(":","").split("!",1)[0]
                    msg = " ".join(line[3:]).replace(":","",1)
                except:
                    nick = "null"
                    break
					
                id = None
                if nick.endswith('.esper.net'):
                    id = "ESPERNET"
                elif nick.lower() == ('nickserv'):
                    id = "NICKSERV"
                elif nick.lower() == ('chanserv'):
                    id = "CHANSERV"
                
                if id is not None:
                    log(msg, m_type=id, colour=Fore.GREEN, lg='receive')
                    #RECEIVE_LOG.info(Style.BRIGHT + Fore.GREEN + id + " " + Fore.RESET + msg)
                elif nick.lower() is not 'oracle':
                    log("<" + nick + "> " + msg, m_type="MESSAGE", colour=Fore.MAGENTA, lg='receive')
                    #RECEIVE_LOG.info(Style.BRIGHT + Fore.MAGENTA + "MESSAGE " + Fore.RESET + " <" + nick + "> " + msg)
            else:
                # the message is bad
                break
                
            # reply from WHOIS
            if "is logged in as" in msg and ".esper.net" in nick:
                confirm_account(msg.split(" ",2)[1])
                
            # reset variable that tells connect if it is a
            # message from a server bot
            if c.getactive():
                c.set_inactive()
            
            # throw msg and nick to spamhandler
            if config.get('spam-handler'):
                global spam
                if spam == None:
                    spam = spamhandler.Handler()
                sh = True
                for bot in config.get('server-bots'):
                    if nick == bot:
                        sh = False
                if nick == config.get('nick'):
                    sh = False
                elif nick.lower() == 'nickserv' or nick.lower() == 'chanserv':
                    sh = False
                if sh:
                    spam.increment(nick, msg) 
                
            # ignore list doesn't work properly, but meh
            if not nick in IGNORE_LIST or nick == 'Toofifty':
                # check if the nick is one of the RapidIRC bots
                # change nick and msg accordingly
                for bot in config.get('server-bots'):
                    if nick == bot:
                        try:
                            if msg.startswith("<"):
                                nick, msg = msg.split("<",1)[1].split("> ",1)
                                c.set_active(bot)
                                
                            elif msg.split(" ")[1] == "whispers":
                                nick, msg = msg.split(" whispers ", 1)
                                c.set_active(bot)
                                
                            elif msg.startswith("Online Players:"):
                                users = msg.replace("Online Players:", "")
                                if not users == "":
                                    randompoints.add_users(users)
                        except IndexError:
                            pass
                                    
                # handle sudo commands
                if msg.startswith(str(config.get('sudo-char'))) and v.getrank(nick) >= 4:
                    msg = msg.replace(config.get('sudo-char'),"")
                    nick, msg = msg.split(" ",1)

                # identify commands from msg
                for char in config.get('command-chars'):
                    if msg.startswith(char):
                        # make sure to only get rid of one '?'
                        msg = msg.split(char, 1)[1]
                        process_cmd(nick, msg)

                # throw msg to translator
                if config.get('translate'):
                    if translate.requires_translate(msg):
                        ACTION_LOG.info("TRN Translating...")
                        c.say("I think you mean: " + translate.translate_result(msg))

                # throw msg and nick to gags
                if config.get('say-responses'):
                    gags.get_response(nick, msg)
      
                # check and handle youtube links
                if config.get('youtube-links'):
                    if(msg.startswith("http://www.youtube.com/")):
                        try:
                            author, title = youtube.processlink(msg)
                            c.say(f.BOLD + f.RED + "YouTube Video" + f.BOLD + f.WHITE + " - " + title + " by " + author)
                        except:
                            c.say(f.BOLD + f.RED + "Youtube video failed" + f.BOLD + f.WHITE + " - 404 Not Found")
            
            # tell run.py to reload or exit
            if RELOAD:
                return True
            if EXIT:
                return False