def gm_get_camp_treasure(self, camp_id):
        ''' GM获取阵容中的宝物详情
        '''
        yield self._load()
        dict_data = [{}, {}]

        if not self.__camp_position.has_key(camp_id):
            defer.returnValue(dict_data)
        positions = self.__camp_position[camp_id]

        # 6-兵书, 7-战马
        for _pos in range(6, 8):
            if not positions.has_key(_pos):
                continue

            user_treasure_id = positions[_pos]
            attrib = yield self.get(user_treasure_id)
            if not attrib:
                log.error('Can not find user treasure. user_treasure_id: {0}.'.
                          format(user_treasure_id))
                continue
            dict_data[_pos - 6] = {
                'user_item_id': user_treasure_id,
                'item_type': attrib.item_type,
                'item_id': attrib.item_id,
                'level': attrib.level,
                'refine_level': attrib.refine_level
            }

        defer.returnValue(dict_data)
Exemple #2
0
def validateAction(_context):
    '''Check to make sure we have not updated the initrd esx.conf after we
    copied it to the installed system, where it might have also been modified.
    '''
    
    if _computeEsxConfChecksum() != INITRD_ESX_CONF_CHECKSUM:
        log.error("initrd esx.conf has changed after copying to the chroot!")
Exemple #3
0
 def delete_table_data(self, attrib_id):
     if self.__gsattribs.has_key( attrib_id ):
         gsattrib = self.__gsattribs[attrib_id]
         gsattrib.delete()
         del self.__gsattribs[attrib_id]
     else:
         log.error('Can not find delete data. uid: {0}.'.format( attrib_id ))
    def equip_reborn(self, user_equip_id):
        ''' 
        @summary: 装备重生 
            (1) 已穿戴 或 未洗炼的装备 不能重生
            (2) 返还该装备洗炼消耗的洗炼石和强化消耗的金币
            (3) 洗练消耗的金币和钻石不返还
            (4) 每返还10个洗炼石,则重生价格为1钻石
        '''
        equip = yield self.user.bag_equip_mgr.get( user_equip_id )
        if not equip:
            log.error('Can not find user equip.')
            defer.returnValue( UNKNOWN_EQUIP_ERROR )

        # 已穿戴 或 洗炼属性为[]的不可重生
        #log.error('camp_id: {0}, refine_attribute: {1}.'.format( equip.camp_id, loads(equip.refine_attribute) ))
        if (equip.camp_id > 0) or not loads(equip.refine_attribute):
            log.error('Equip reborn error. cid: {0}, ueid: {1}, camp_id: {2}, refine_attribute: {3}.'.format( self.cid, user_equip_id, equip.camp_id, loads(equip.refine_attribute) ))
            defer.returnValue( EQUIP_REBORN_ERROR )

        # 装备的conf
        equip_conf = get_item_by_itemid( equip.item_id )
        if not equip_conf:
            log.error('Can not find conf. item id: {0}.'.format( equip.item_id ))
            defer.returnValue( UNKNOWN_ITEM_ERROR )

        # 计算钻石消耗
        if (equip.refine_cost % 10) > 0:
            need_credits = equip.refine_cost / 10 + 1
        else:
            need_credits = equip.refine_cost / 10

        # 玩家钻石不足
        if need_credits > self.user.base_att.credits:
            log.error('Need credits: {0}, now have: {1}.'.format( need_credits, self.user.base_att.credits ))
            defer.returnValue( CHAR_CREDIT_NOT_ENOUGH )

        items_return = []
        # 返还金币、洗炼石
        #self.user.base_att.golds += equip.strengthen_cost
        self.user.get_golds( equip.strengthen_cost, WAY_EQUIP_REBORN )
        try:
            res_err, res_value = yield self.user.bag_item_mgr.new(ITEM_REFINE_STONE, equip.refine_cost)
            if not res_err:
                items_return = res_value
        except Exception as e:
            log.error('ERROR: {0}.'.format( e ))
            log.exception()
        # 扣钻石, 数据清零
        #self.user.base_att.credits -= need_credits
        if need_credits:
            yield self.user.consume_credits( need_credits, WAY_EQUIP_REBORN )
        self.user.bag_equip_mgr.reborn( user_equip_id )
 
        if equip.strengthen_cost > 0:
            items_return.append( [0, ITEM_TYPE_MONEY, ITEM_MONEY_GOLDS, equip.strengthen_cost] )

        # 强化、精炼属性清零
        equip.level, equip.strengthen_cost, equip.refine_cost, equip.refine_attribute = 0, 0, 0, dumps([])

        defer.returnValue( (self.user.base_att.credits, items_return) )
    def POST(self):
        '''
        Method: post
        '''   
        try:                  
            try:
                data = web.data()
                build_info = utils.json_load_to_str(data)
                log.debug("build info: %s" % build_info)           
            except Exception, e:
                log.error(e)
                raise UnableParsePostDataError
            
            # update status 
            dbopts = SQLAdaptor()
#            commit_id = dbopts.SetBuildStatus(build_info)            
            
            # if all results are failures, send email to commitor
            #
            
            phase_id, failure_list, commit_id = dbopts.CheckBuildFailures(build_info)
            
            if failure_list:
                if not opts.SendEmailToCommitor(build_info, commit_id):
                    dbopts.SetCommitStatus(commit_id, 10)
                else:
                    dbopts.SetCommitStatus(commit_id, 4)
            elif (not failure_list) and (phase_id == 3):
            
                dbopts.SetCommitStatus(commit_id, 1)
            else:
                dbopts.SetCommitStatus(commit_id, 3)
                 
            return HTTPAdaptor.format_response("ok", "003", "Update status based on CI")
    def GetTestSummary(self, jobs):
        '''Query from test result database'''
        log.debug("Get test summary")
        try:

            conn = self._init_connection(config.database_test_result)
            cursor = conn.cursor()
            test_num = 0
            failures = 0
            tests = [] 
            for job in jobs:                
                cursor.execute(SQL_SELECT_TEST_NUM, (job[0], job[1]))
                for row in cursor:
                    tests.append(row[0])
                    
#                test_num = tests.__len__() 
                for test in tests:
                    cursor.execute(SQL_SELECT_TEST_RESULT_ID, (job[0], job[1], test))
                    for row in cursor:
                        test_num += 1
                        if row[0] == 2:
                            failures += 1
     
        except Exception, e:
            log.error("Get test summary failed")
            log.error(e)
Exemple #7
0
    def raster(self, filename, client):
        """Takes a filename and converts it to a raster image
        reportlab can process"""

        if not os.path.exists(filename):
            log.error("Missing image file: %s",filename)
            return missing

        try:
            # First try to rasterize using the suggested backend
            backend = self.get_backend(filename, client)[1]
            return backend.raster(filename, client)
        except:
            pass

        # Last resort: try everything

        if sys.platform[0:4] == 'java':
            try:
                from javax.imageio import ImageIO
                from java.io import File

                iis = ImageIO.createImageInputStream(File(filename))
                readers = ImageIO.getImageReaders(iis)
                if readers.hasNext():
                    reader = readers.next()
                    reader.setInput(iis, True)
                    metadata = reader.getImageMetadata(0)
                    # this means imageio can read it
                    return filename
                else:
                    log.warning("Java's ImageIO cannot read the file [%s]", filename)
            except Exception, error:
                log.warning("Could not use Java's ImageIO to read the file [%s]: %s", filename, str(error))
Exemple #8
0
async def test(session, user_id):
    try:
        tweets_replies = await session.get_profile_tweets_raw(user_id)
        tweet_ids = session.get_ordered_tweet_ids(tweets_replies)
        replied_ids = []
        for tid in tweet_ids:
            if tweets_replies["globalObjects"]["tweets"][tid][
                    "reply_count"] > 0 and tweets_replies["globalObjects"][
                        "tweets"][tid]["user_id_str"] == user_id:
                replied_ids.append(tid)

        for tid in replied_ids:
            tweet = await session.tweet_raw(tid)
            for reply_id, reply_obj in tweet["globalObjects"]["tweets"].items(
            ):
                if reply_id == tid or reply_obj.get(
                        "in_reply_to_status_id_str", None) != tid:
                    continue
                reply_tweet = await session.tweet_raw(reply_id)
                if reply_id not in reply_tweet["globalObjects"]["tweets"]:
                    continue
                obj = {"tweet": tid, "reply": reply_id}
                if tid in reply_tweet["globalObjects"]["tweets"]:
                    obj["ban"] = False
                else:
                    obj["ban"] = True
                return obj
    except:
        log.error('Unexpected Exception:')
        log.error(traceback.format_exc())
        return {"error": "EUNKNOWN"}
Exemple #9
0
 def joinClient(self, client, channel):
     """Joins a PyLink client to a channel."""
     # InspIRCd doesn't distinguish between burst joins and regular joins,
     # so what we're actually doing here is sending FJOIN from the server,
     # on behalf of the clients that are joining.
     channel = utils.toLower(self.irc, channel)
     server = utils.isInternalClient(self.irc, client)
     if not server:
         log.error(
             '(%s) Error trying to join client %r to %r (no such pseudoclient exists)',
             self.irc.name, client, channel)
         raise LookupError('No such PyLink PseudoClient exists.')
     # Strip out list-modes, they shouldn't be ever sent in FJOIN.
     modes = [
         m for m in self.irc.channels[channel].modes
         if m[0] not in self.irc.cmodes['*A']
     ]
     self._send(
         server, "FJOIN {channel} {ts} {modes} :,{uid}".format(
             ts=self.irc.channels[channel].ts,
             uid=client,
             channel=channel,
             modes=utils.joinModes(modes)))
     self.irc.channels[channel].users.add(client)
     self.irc.users[client].channels.add(channel)
 def gather_elements(self, client, node, style):
     # Based on the graphviz extension
     global graphviz_warn
     try:
         # Is vectorpdf enabled?
         if hasattr(VectorPdf, 'load_xobj'):
             # Yes, we have vectorpdf
             fname, outfn = sphinx.ext.graphviz.render_dot(
                 node['builder'], node['code'], node['options'], 'pdf')
         else:
             # Use bitmap
             if not graphviz_warn:
                 log.warning(
                     'Using graphviz with PNG output. You get much better results if you enable the vectorpdf extension.'
                 )
                 graphviz_warn = True
             fname, outfn = sphinx.ext.graphviz.render_dot(
                 node['builder'], node['code'], node['options'], 'png')
         if outfn:
             client.to_unlink.append(outfn)
             client.to_unlink.append(outfn + '.map')
         else:
             # Something went very wrong with graphviz, and
             # sphinx should have given an error already
             return []
     except sphinx.ext.graphviz.GraphvizError, exc:
         log.error('dot code %r: ' % node['code'] + str(exc))
         return [Paragraph(node['code'], client.styles['code'])]
    def __init__(self, filename=None):
        super(CustomDriversWindow, self).__init__()
        global _currentMediaKey

        self.start = self.askCustomDrivers
        self.substep = self.start  # initial TextRunner substep

        # cumulativeDriversDict uses package name (currently RPM name) as key,
        # and have as value tuples of:
        #  (driverName, version, description, driverBinList, pciTable,
        #   removeList)
        self.cumulativeDriversDict = {}  # drivers to install
        _currentMediaKey = 'install'

        if not filename:
            filename = os.path.join(os.path.dirname(__file__), os.path.pardir,
                                    "drivereula.txt")

        self.textlines = ['']

        try:
            rawtext = open(filename).read()
        except Exception, msg:
            log.error(msg)
            log.error("Couldn't load driver eula")
Exemple #12
0
    def broadcast(self):
        _len = self.msgs.qsize()
        if _len > 0:
            _count = min(_len, CHAR_MSG_BROADCAST_MAX_LEN)

            i = 0
            _msgs = []
            while i < _count:
                i += 1
                try:
                    _msgs.append(self.msgs.get_nowait())
                except Queue.Empty:
                    break
                except Exception as e:
                    log.error("Broadcast error. e: %s." % (e))
            cids_in_room, cids_notice = g_UserMgr.getAllianceCids(
                self.alliance_id)
            #log.info('For Test. cids_in_room: {0}, cids_notice: {1}.'.format( cids_in_room, cids_notice ))
            if cids_in_room and _msgs:
                gw_broadcast(self.broadcast_protocol, _msgs, cids_in_room)
            if cids_notice and _msgs:
                g_UserMgr.updateNotifyFlag(cids_notice)
                gw_broadcast('new_chat_message', [self.channel], cids_notice)

        reactor.callLater(CHAT_BROADCAST_INTERVAL, self.broadcast)
Exemple #13
0
    def get_website(self, url=None):
        log.info('get_website %s' % url)
        main_handle = self.webdriver.current_window_handle
        try:
            if url:
                self.webdriver.get(url)
            else:
                self.webdriver.get(self.url)

        except TimeoutException:
            log.error('[get_website] TimeoutException')

        # Sleep after get returns
        time.sleep(DEFAULT_SLEEP)

        # Close modal dialog if exists
        try:
            WebDriverWait(self.webdriver, .5).until(EC.alert_is_present())
            alert = self.webdriver.switch_to_alert()
            alert.dismiss()
            time.sleep(1)
        except TimeoutException:
            pass

        windows = self.webdriver.window_handles
        if len(windows) > 1:
            for window in windows:
                if window != main_handle:
                    self.webdriver.switch_to_window(window)
                    self.webdriver.close()
            self.webdriver.switch_to_window(main_handle)

        if config['browser_params']['bot_mitigation']:
            self.bot_mitigation()
    def reset_climbing(self):
        '''
        @summary: 重置天外天数据。当前塔层归1, 挑战次数置满, 更新last_time, 扣重置次数
        '''
        self.system_daily_reset()
        # 正在扫荡, 不能重置
        if self.climbing.start_datetime > 0:
            log.error('In climbing could not reset.')
            defer.returnValue(IN_CLIMBING_ONGOING)
        if self.climbing.cur_layer == 1:
            log.error('Tower layer 1 could not reset.')
            defer.returnValue(IN_CLIMBING_MIN_LAYER)
        climbing_data = self.get_vip_conf_of_climbing()
        if (climbing_data[1] + self.climbing.buyed_reset < 1):
            log.warn(
                'User no reset count. cid: {0}, had_free_reset: {1}, buyed_reset: {2}.'
                .format(self.cid, self.climbing.free_reset,
                        self.climbing.buyed_reset))
            res_err = yield self.buy_count(1)
            if isinstance(res_err, int):
                defer.returnValue(res_err)
            climbing_data = self.get_vip_conf_of_climbing()

        self.climbing.cur_layer = 1
        if self.climbing.buyed_reset > 0:
            self.climbing.buyed_reset -= 1
        elif climbing_data[1] > 0:
            self.climbing.free_reset += 1
            climbing_data[1] -= 1

        self.climbing.free_fight = 0
        self.climbing.last_datetime = datetime.now()

        defer.returnValue( (self.climbing.cur_layer, self.climbing.max_layer, climbing_data[3]+self.climbing.buyed_fight, \
                climbing_data[1]+self.climbing.buyed_reset, climbing_data[2], self.climbing.start_datetime, self.user.credits) )
def fellowsoul_combine(p, req):
    res_err = UNKNOWN_ERROR

    cid, [user_fellow_id] = req

    user = g_UserMgr.getUser(cid)
    if not user:
        log.error('Can not find user. cid: {0}.'.format( cid ))
        defer.returnValue( res_err )

    res_err, fellow_id = yield user.bag_fellowsoul_mgr.combine( user_fellow_id )
    if not res_err:
        try:
            # args: fellow_id, is_major, camp_id, on_troop
            res_err, attrib = yield user.fellow_mgr.create_table_data( fellow_id, 0, 0, 0 )
        except Exception as e:
            log.warn('Create fellow fail! e:', e)
            defer.returnValue(res_err)
        #errorno, value = yield user.fellow_mgr.addNewFellow( fellow_id )
        if not res_err:
            _conf = get_fellow_by_fid(fellow_id)
            if _conf:
                q = _conf.get('Quality', 0)
                if q>= 2:
                    user.achievement_mgr.update_achievement_status(29, 1)
                if q>= 3:
                    user.achievement_mgr.update_achievement_status(30, 1)
                if q>= 4:
                    user.achievement_mgr.update_achievement_status(31, 1)
            defer.returnValue( [attrib.attrib_id, attrib.fellow_id] )

    defer.returnValue( res_err )
def TriggerJobs(jobs):
    is_triggered = False
    for job_name, job_content in jobs.iteritems():
        urlprefix = config.ciserver["urlprefix"]
        urlsuffix = config.ciserver["urlsuffix"]
        auth = [job_content["author"], job_content["token"]]
        log.debug("auth: %s token: %s" %
                  (job_content["author"], job_content["token"]))
        if not urlprefix:
            raise IncorrectCIServerPrefixError
        elif not urlsuffix:
            raise IncorrectCIServerSuffixError
        else:
            job_url = "".join([urlprefix, job_name, urlsuffix])
            log.debug("Job url: %s" % job_url)
            body = utils.format_body_for_ci(job_content)
            code = HTTPAdaptor.get_url(job_url, auth=auth, body=body)
            if not code == 200:
                dbopts = SQLAdaptor()
                dbopts.SetBuildToInvalid(job_name, job_content)
                log.error("Code: %s" % code)
            else:
                is_triggered = True
                log.info(
                    "trigger request sent for job '%s'. code returned is %s" %
                    (job_name, code))
    if not is_triggered:
        raise NoJobTriggeredError
Exemple #17
0
def randcard(p, req):
    '''
    @summary: In client, card_type=1 ~ 3
    '''
    res_err = UNKNOWN_ERROR

    cid, (card_type, rand_times) = req
    user = g_UserMgr.getUser(cid)
    if not user:
        log.error('Can not find user. cid: {0}.'.format( cid ))
        defer.returnValue( res_err )

    # 背包容量判断 (去掉容量判断)
    #cur_capacity = yield user.fellow_mgr.cur_capacity()
    #if cur_capacity >= user.base_att.fellow_capacity:
    #    log.error('cid: {0}, max fellow capacity: {1}, cur_capacity: {2}.'.format( cid, user.base_att.fellow_capacity, cur_capacity ))
    #    defer.returnValue( FELLOW_CAPACITY_NOT_ENOUGH )

    if rand_times <= 0:
        defer.returnValue( REQUEST_LIMIT_ERROR )

    randcard_mgr = GSRandCardMgr( user )
    res_err = yield randcard_mgr.randcard( card_type, rand_times )

    defer.returnValue( res_err )
Exemple #18
0
    def limit_fellow_info(self):
        ''' 限时神将基本信息 '''
        _status, _data = yield self.status()
        if _status < 0:
            defer.returnValue(LIMIT_FELLOW_NO_ERROR)

        _all_lvl_conf = get_limit_fellow_level()
        if not _all_lvl_conf:
            log.error('Can not find limit fellow shrine level update conf.')
            defer.returnValue(NOT_FOUND_CONF)
        _all_lvls = _all_lvl_conf.keys()
        _max_level = max(_all_lvls)
        if _data[1] >= _max_level:
            _shrine_level = _max_level
        else:
            _shrine_level = _data[1] + 1
        _shrine_conf = _all_lvl_conf[_shrine_level]
        _need_count = _shrine_conf['RandCount'] - _data[2] if _shrine_conf[
            'RandCount'] > _data[2] else 0
        _need_time = self.left_free_timestamp(_data[3], LIMIT_FELLOW_FREE_TIME)

        _rank, _score = yield self.get_name_info(self.user.nick_name)
        _ranklist = yield self.ranklist()

        defer.returnValue((_data[0], _rank, _score, _need_time, _need_count,
                           _ranklist, LIMIT_FELLOW_RAND_COST))
 def InsertJobInfo(self, job_info):
     log.debug("Insert job info into database")        
     try:
         curtime = datetime.utcnow()
         conn = self._init_connection()
         cursor = conn.cursor()            
         cursor.execute("SET AUTOCOMMIT = 0")
         for jobname, jobcontent in job_info.iteritems():
             cursor.execute(SQL_SELECT_JOB_ID, (jobname, ))
             for row in cursor:
                 job_id = row[0]
             tnx = jobcontent["transaction"]
             if tnx:
                 cursor.execute(SQL_SELECT_COMMIT_ID_BY_TRANSACTION, (tnx, ))
             else:
                 cursor.execute(SQL_SELECT_COMMIT_ID_BY_REVISION, (jobcontent["revision"], ))
             for row in cursor:
                 commit_id = row[0]
             cursor.execute(SQL_INSERT_BUILD_INFO, (job_id, commit_id, curtime))
             
         conn.commit()
         
     except Exception, e:
         log.error('Insert job info into database failed')
         log.error(e)
         conn.rollback()
Exemple #20
0
def download_file(url, base_path, filename = '', call_func = ''):
    file_path = base_path + filename
    directory = os.path.dirname(file_path)
    mkdir(directory)

    if url:
        try:
            log.debug('''
                         正在下载 %s
                         存储路径 %s
                      '''
                         %(url, file_path))

            request.urlretrieve(url, file_path)

            log.debug('''
                         下载完毕 %s
                         文件路径 %s
                      '''
                         %(url, file_path)
                     )

            call_func and call_func()
            return 1
        except Exception as e:
            log.error(e)
            return 0
    else:
        return 0
Exemple #21
0
def _deploy(squadron_dir, new_dir, last_dir, commit_info,
        this_run_sum, last_run_sum, last_commit, dont_rollback,
        resources, force):
    log.info("Applying changes")
    log.debug("Changes: %s", commit_info)
    commit.commit(commit_info)

    paths_changed, new_paths = _get_hash_diff(last_run_sum, this_run_sum, force)

    log.debug("Paths changed: %s", paths_changed)
    log.debug("New paths: %s", new_paths)

    _run_actions(squadron_dir, new_dir, commit_info, resources, paths_changed,
            new_paths)

    # Now test
    try:
        _run_tests(squadron_dir, commit_info)
    except TestException:
        # Roll back
        if last_commit and not dont_rollback:
            log.error("Rolling back to %s because tests failed", last_commit)
            # Flip around the paths changed and new_paths
            _deploy(squadron_dir, last_dir, None, last_commit, last_run_sum,
                    {}, None, dont_rollback, resources, False)
        raise
Exemple #22
0
 def run_func(*args, **kw):
     callfunc = ''
     try:
         callfunc = func(*args, **kw)
     except Exception as e:
         log.error(module_name + ": " + func.__name__ + " - " + str(e))
     return callfunc
Exemple #23
0
def load_all_handlers(root, module):
    _imported = []

    for f in listdir(root + module):
        if f.startswith('.') or f.startswith('_'):
            continue

        _subfix = ''
        if f.find('.pyc') > 0:
            _subfix = '.pyc'
        elif f.find('.pyo') > 0:
            _subfix = '.pyo'
        elif f.find('.py') > 0:
            _subfix = '.py'
        else:
            continue

        fname, _ = f.rsplit(_subfix, 1)
        if fname and fname not in _imported:
            _handlers_name = '%s.%s' % (module, fname)
            try:
                __import__(_handlers_name)
            except Exception, e:
                log.error('[ load_all_handlers ]Error when load handler:', root, f, _handlers_name, 'Detail:', str(e))
                traceback.print_exc()
                raise e
                break
            _imported.append(fname)
Exemple #24
0
def get_html_by_urllib(url, code = 'utf-8'):
    html = None
    if not url.endswith('.exe') and not url.endswith('.EXE'):
        page = None
        is_timeout = False
        try:
            def timeout_handler(response):
                is_timeout = True
                if response:
                    response.close()

            page = request.urlopen(quote(url,safe='/:?=&'), timeout = TIME_OUT)
            # 设置定时器 防止在read时卡死
            t = Timer(TIMER_TIME, timeout_handler, [page])
            t.start()
            html = page.read().decode(code,'ignore')
            t.cancel()

        except Exception as e:
            log.error(e)
        finally:
            # page and page.close()
            if page and not is_timeout:
                page.close()

    return html and len(html) < 1024 * 1024 and html or None
Exemple #25
0
    def onekey_receive_reward(self, user):
        res = CONSTELLATION_REWARD_RECEIVED

        self.synced = False

        items_return = []
        for idx, reward in enumerate(self.rewards):
            if reward[3]:
                continue

            if self.score >= Constellation.stars_need( idx ):
                _add_func = ITEM_MODELs.get(reward[0], None)

                if _add_func:
                    res_err, res_value = yield _add_func( user, ItemID = reward[1], ItemNum = reward[2], AddType=WAY_CONSTELLATION_AWARD, CapacityFlag=False )
                    if not res_err:
                        for _v in res_value:
                            items_return = total_new_items(_v, items_return)
                    reward = list(reward)
                    reward[3] = 1
                    self.rewards[idx] = reward
                    res = NO_ERROR
                else:
                    log.error('[ Constellation.receve_reward ]no such item type: {0}.', reward[0])
            else:
                log.warn('user too few score. cid:{0}, score:{1}, idx:{2}, stars need:{3}.'.format( user.cid, self.score, idx, Constellation.stars_need(idx)) )
                break

        defer.returnValue( (res, self.rewards, items_return) )
 def __init__(self, filename, width=None, height=None, kind='direct',
                                  mask=None, lazy=True, srcinfo=None):
     Flowable.__init__(self)
     ext = os.path.splitext(filename)[-1]
     self._kind = kind
     # Prefer svg2rlg for SVG, as it works better
     if LazyImports.svg2rlg:
         self._mode = 'svg2rlg'
         self.doc = LazyImports.svg2rlg.svg2rlg(filename)
         self.imageWidth = width
         self.imageHeight = height
         x1, y1, x2, y2 = self.doc.getBounds()
         # Actually, svg2rlg's getBounds seems broken.
         self._w, self._h = x2, y2
         if not self.imageWidth:
             self.imageWidth = self._w
         if not self.imageHeight:
             self.imageHeight = self._h
     else:
         self._mode = None
         log.error("SVG support not enabled,"
             " please install svg2rlg.")
     self.__ratio = float(self.imageWidth)/self.imageHeight
     if kind in ['direct','absolute']:
         self.drawWidth = width or self.imageWidth
         self.drawHeight = height or self.imageHeight
     elif kind in ['bound','proportional']:
         factor = min(float(width)/self.imageWidth,float(height)/self.imageHeight)
         self.drawWidth = self.imageWidth*factor
         self.drawHeight = self.imageHeight*factor
def get_plunder_info(p, req):
    '''
    @summary: 获取夺宝基本信息
    '''
    res_err = UNKNOWN_ERROR

    cid, (plunder_type, ) = req

    user = g_UserMgr.getUser(cid)
    if not user:
        log.error('Can not find user. cid: {0}.'.format( cid ))
        defer.returnValue( res_err )

    shard_type = 0
    if plunder_type == 1: #战马
        shard_type = ITEM_TYPE_HORSESHARD
    elif plunder_type == 2: #兵书
        shard_type = ITEM_TYPE_BOOKWARSHARD
    else:
        log.error('[ get_plunder_info ]cid:{0}, Unknown plunder type: {1}.'.format( cid, plunder_type ))
        defer.returnValue( res_err )

    value_list = yield user.bag_treasureshard_mgr.value_list_by_type(shard_type)
    avoid_time = yield AvoidWarMgr.remain_avoid_war_time(cid)
    defer.returnValue( (avoid_time, value_list) )
Exemple #28
0
 def sendPullResponse(self, request, txpk):
     """"Send a PULL_RESP message to a gateway.
     
     The PULL_RESP message transports its payload, a JSON object,
     from the LoRa network server to the LoRa gateway. The length
     of a PULL_RESP message shall not exceed 1000 octets.
     
     Args:
         request (GatewayMessage): The decoded Pull Request
         txpk (Txpk): The txpk to be transported
     """
     # Create a new PULL_RESP message. We must send to the
     # gateway's PULL_DATA port.
     host = request.remote[0]
     gateway = self.configuredGateway(host)
     if gateway == None:
         log.error("Pull Reponse - no known gateway for {host}", host=host)
         return
     if gateway.port == None:
         log.error("Pull Reponse - no known port for gateway {host}",
                   host=host)
         return
     remote = (host, gateway.port)
     m = GatewayMessage(version=request.version,
                        token=request.token,
                        identifier=PULL_RESP,
                        gatewayEUI=gateway.eui,
                        remote=remote,
                        ptype='txpk',
                        txpk=txpk)
     log.info("Sending PULL_RESP message to %s:%d" % remote)
     self._sendMessage(m)
Exemple #29
0
    def get_camp_equip(self, camp_id):
        '''
        @summary: 获取camp_id的position_id对应的equip
        '''
        yield self._load()
        _camp_equip = [[], [], [], []]

        if not self.__camp_position.has_key(camp_id):
            defer.returnValue( _camp_equip )

        positions = self.__camp_position[camp_id]

        # 2-头盔 3-武器, 4-项链, 5-护甲
        for _pos in range(2, 6):
            if not positions.has_key(_pos):
                continue
            user_equip_id = positions[_pos]

            attrib  = yield self.get( user_equip_id )
            if not attrib:
                log.error('Can not find user equip. user_equip_id: {0}.'.format( user_equip_id ))
                positions[_pos] = 0
                continue
            _camp_equip[_pos-2] = [user_equip_id, attrib.item_id, attrib.level, loads(attrib.refine_attribute)]

        defer.returnValue( _camp_equip )
Exemple #30
0
    def _handleDependencies(self, deplist):
        '''Handle any unresolved dependencies returned by the
        TransactionSet.check() method.
        '''
        stillUnresolved = []
        for (unsatisfiedPkg, reqNameVer, _needsFlag, suggestedPkg, _sense) \
                in deplist:
            if reqNameVer[1]:
                reqString = "%s-%s" % reqNameVer
            else:
                reqString = reqNameVer[0]
            msg = "Package %s-%s-%s requires %s" % \
                  (unsatisfiedPkg + (reqString,))
            log.info(msg)
            if userchoices.getResolveDeps() and suggestedPkg:
                package = suggestedPkg[0]
                log.info("  resolving dependency with %s" %
                         package.fullSrcPath)
                self.ts.addInstall(package.header, (package, ), 'u')
                self.totalSize += (package.header[rpm.RPMTAG_SIZE] / SIZE_MB)
            elif userchoices.getIgnoreDeps():
                log.info("  ignoring dependency")
            else:
                log.error("unable to resolve dependency -- %s" % msg)
                stillUnresolved.append(msg)

        return stillUnresolved
Exemple #31
0
 def run(self):        
     self.server.addMsgHandler("default", self.default_handler)
     while True:
         try:
             self.server.handle_request()
         except Exception as e:
             log.error(log.exc(e))
Exemple #32
0
 def checkForProblems(self):
     # XXX Do more than just logging here.
     problems = self.ts.problems()
     if problems:
         log.error('RPM transaction set problems:')
         for prob in problems:
             log.error(' %s' % prob)
Exemple #33
0
def forward_to_local(request, uid):
    full_path = content.fullpath(uid)

    if full_path is None:
        log.error('requested uid({}) is invalid'.format(uid))
        raise Http404
    return static.serve(request, path=full_path, document_root='/')
Exemple #34
0
def process_text_block(fp_in, fp, job: bool) -> None:
    add_final_nl = False
    if job == OBEYLINES:
        add_final_nl = True
    music.output_music(fp)
    buffer.buffer_eob(fp)
    common.cfmt.textfont.set_font(fp, False)
    common.words_of_text = ""
    for i in range(100):
        ln = fp_in.read()
        if ln == '':
            log.error("EOF reached scanning text block")
        common.linenum += 1
        log.warning(f"{common.linenum:3d}  {ln} \n")
        if ln.startswith('%%'):
            del ln[0:1]

        if ln == "endtext":
            break

        if job != SKIP:
            if not ln:
                subs.write_text_block(fp, job)
                common.words_of_text = ''
            else:
                subs.add_to_text_block(ln, add_final_nl)
    if job != SKIP:
        subs.write_text_block(fp, job)
Exemple #35
0
    def loginUser(self, char_data, flag=False):
        '''
        @param: char_data=[id, account, nick_name, ...]
        @param: flag-离线登陆的标志位
        '''
        from manager.gscharacter import GSCharacter
        char_data = dict(zip(GSCharacter._fields, char_data))

        cid  = char_data['id']
        user = self.getUser(cid, flag)

        if user:
            log.error('user had exists already. cid {0}.'.format(cid))
            return user

        user = GSCharacter(cid)

        self.__dic_uid_user[cid] = user
        user.load( char_data, flag )
        # 离线登陆的标志位
        if flag: 
            user.offline_num += 1

        log.debug('load user data. cid: {0}'.format( cid ))
        return user
Exemple #36
0
 def congrats(self):
     "Get IP address, Show congratulatory message."
     cosNICs = userchoices.getCosNICs()
     warn = ''
     if not cosNICs:
         log.error("No COS network adapter found")
         warn = warnText
     elif 'ip' not in cosNICs[0]:
         log.error("COS network adapter missing IP address")
         warn = warnText
     elif not cosNICs[0]['ip']:
         # COS NIC detected, using DHCP
         pass
     else:
         # COS NIC configured using static IP
         self.ipaddr = cosNICs[0]['ip']
     ui = {
         'title': title,
         'body': congratsText % {
             'ipaddr': self.ipaddr,
             'warn': warn
         },
         'menu': {
             '1': self.stepForward,
         }
     }
     self.setSubstepEnv(ui)
 def InsertCommitInfo(self, commit_info):
     log.debug("Insert commit info into database")        
     try:
         curtime = datetime.utcnow()
         conn = self._init_connection()
         cursor = conn.cursor()            
         cursor.execute("SET AUTOCOMMIT = 0")
         cursor.execute(SQL_INSERT_COMMIT_INFO, (commit_info["author"], 
                                                 commit_info["transaction"],
                                                 commit_info["revision"],
                                                 commit_info["uuid"], 
                                                 commit_info["comments"], 
                                                 7,
                                                 curtime))
         commit_id = cursor.lastrowid
         for change in commit_info["changes"]:
             cursor.execute(SQL_INSERT_CHANGESET_INFO, (
                                                        commit_id,
                                                        change["type"],
                                                        change["filename"] if change.has_key("filename") else "",
                                                        change["fileurl"] if change.has_key("fileurl") else "",
                                                        change["diffname"] if change.has_key("diffname") else "",
                                                        change["diffpath"] if change.has_key("diffpath") else "",
                                                        curtime))
                                                        
                 
         conn.commit()
         
     except Exception, e:
         log.error('commit info into database failed')
         log.error(e)
         conn.rollback()
Exemple #38
0
    def handle_error(self, e):
        log.error(e)
        if isinstance(e, HTTPException):
            message = e.description
            if hasattr(e, "data") and "message" in e.data:
                message = e.data["message"]
            if e.code == 400:
                return self.make_response(bad_request(message), 200)
            if e.code == 401:
                return self.make_response(unauthorized(message), 200)
            if e.code == 403:
                return self.make_response(forbidden(message), 200)
            if e.code == 404:
                return self.make_response(not_found(message), 200)
            if e.code == 409:
                return self.make_response(conflict(message), 200)
            if e.code == 412:
                return self.make_response(precondition_failed(message), 200)
            if e.code == 415:
                return self.make_response(unsupported_mediatype(message), 200)
            if e.code == 500:
                return self.make_response(internal_server_error(message), 200)

        # if exception cannot be handled, return error 500
        return self.make_response(internal_server_error(e.message), 200)
Exemple #39
0
 def congrats(self):
     "Get IP address, Show congratulatory message."
     cosNICs = userchoices.getCosNICs()
     warn = ''
     if not cosNICs:
         log.error("No COS network adapter found")
         warn = warnText
     elif 'ip' not in cosNICs[0]:
         log.error("COS network adapter missing IP address")
         warn = warnText
     elif not cosNICs[0]['ip']:
         # COS NIC detected, using DHCP
         pass
     else:
         # COS NIC configured using static IP
         self.ipaddr = cosNICs[0]['ip']
     ui = {
         'title': title,
         'body': congratsText % {
             'ipaddr': self.ipaddr,
             'warn': warn },
         'menu': {
             '1': self.stepForward,
         }
     }
     self.setSubstepEnv(ui)
    def __init__(self, realVnic=None, ipConfig=None, portGroupName=None):
        '''VirtualNic shouldn't need to be constructed outside the
        networking_base module. If you're calling this from outside,
        you're probably doing something wrong
        '''
        log.debug('Creating a Virtual NIC')

        self.driverName = 'VMware Virtual NIC'
        self.humanReadableName = self.driverName
    
        # sanity-check the arguments
        if realVnic and ipConfig:
            log.error('VirtualNicFacade constructed with a real Vnic,'
                      ' ignoring the specified ipConfig')
        elif not (realVnic or ipConfig):
            raise Exception('VirtualNicFacade constructed without a real Vnic'
                            ' but the needed ipConfig argument was missing')
        elif ipConfig and not portGroupName:
            msg = ('VirtualNicFacade constructed with an ipConfig, but'
                   ' the needed port group name was ommitted.')
            log.error(msg)
            raise ValueError(msg)

        # create the Virtual NIC Facade
        if realVnic:
            self.__vNic = realVnic
        else:
            self.createVnic(ipConfig, portGroupName) # creates self.__vNic
    def reset_climbing(self):
        '''
        @summary: 重置天外天数据。当前塔层归1, 挑战次数置满, 更新last_time, 扣重置次数
        '''
        self.system_daily_reset()
        # 正在扫荡, 不能重置
        if self.climbing.start_datetime > 0:
            log.error('In climbing could not reset.')
            defer.returnValue( IN_CLIMBING_ONGOING )
        if self.climbing.cur_layer == 1:
            log.error('Tower layer 1 could not reset.')
            defer.returnValue( IN_CLIMBING_MIN_LAYER )
        climbing_data = self.get_vip_conf_of_climbing()
        if (climbing_data[1] + self.climbing.buyed_reset < 1):
            log.warn('User no reset count. cid: {0}, had_free_reset: {1}, buyed_reset: {2}.'.format( self.cid, self.climbing.free_reset, self.climbing.buyed_reset ))
            res_err = yield self.buy_count(1)
            if isinstance(res_err, int):
                defer.returnValue( res_err )
            climbing_data = self.get_vip_conf_of_climbing()

        self.climbing.cur_layer = 1
        if self.climbing.buyed_reset > 0:
            self.climbing.buyed_reset -= 1
        elif climbing_data[1] > 0:
            self.climbing.free_reset += 1
            climbing_data[1] -= 1

        self.climbing.free_fight    = 0
        self.climbing.last_datetime = datetime.now()
 
        defer.returnValue( (self.climbing.cur_layer, self.climbing.max_layer, climbing_data[3]+self.climbing.buyed_fight, \
                climbing_data[1]+self.climbing.buyed_reset, climbing_data[2], self.climbing.start_datetime, self.user.credits) )
 def delete_table_data(self, attrib_id):
     if self.__gsattribs.has_key(attrib_id):
         gsattrib = self.__gsattribs[attrib_id]
         gsattrib.delete()
         del self.__gsattribs[attrib_id]
     else:
         log.error('Can not find delete data. uid: {0}.'.format(attrib_id))
Exemple #43
0
def world_ranklist(p, req):
    if hasattr(p, "uid"):
        log.debug('uid:{0}'.format(p.uid))
        uid = p.uid
    else: # used to test
        log.error('client has not found uid.')
        defer.returnValue((CONNECTION_LOSE, None))

    user = g_UserMgr.getUserByUid(uid)
    if not user:
        defer.returnValue((CONNECTION_LOSE, None))

    data = list()
    other_data = list()
    weight_data = yield redis.zrange(SET_RANK_PVP_WEIGHT, 0, 10, True)
    for _rank, (_uid, _weight) in enumerate(weight_data):
        _machine_code = yield redis.hget(HASH_UID_MACHINE_CODE, _uid)
        other_data.append((_rank+1, _uid, _machine_code, _weight))

    self_rank = yield redis.zrank(SET_RANK_PVP_WEIGHT, uid)
    self_rank = 0 if self_rank is None else int(self_rank) + 1
    self_machine_code = yield redis.hget(HASH_UID_MACHINE_CODE, uid)
    self_weight = yield redis.zscore(SET_RANK_PVP_WEIGHT, uid)
    self_weight = 0 if self_weight is None else abs(self_weight)

    data = (other_data, (self_rank, uid, self_machine_code, self_weight))
    defer.returnValue((NO_ERROR, data))
    def use(self, item_id, item_num):
        '''
        @summary: 先使用数量少的, 接着使用已满叠加数的分魂
        '''
        # used item attrib
        used_attribs = []
        total_num, item_attribs = yield self.get_fellowsouls(item_id)
        if item_num > total_num:
            log.error('Item id: {0}, need num: {1}, cur num: {2}.'.format(
                item_id, item_num, total_num))
            defer.returnValue([CHAR_ITEM_NOT_ENOUGH, used_attribs])

        for attrib in item_attribs:
            if attrib.item_num < item_num:
                item_num -= attrib.item_num
                attrib.item_num = 0
            else:
                attrib.item_num -= item_num
                item_num = 0
            # save used item attrib
            used_attribs.append(attrib)

            if attrib.item_num == 0:
                self.delete_table_data(attrib.attrib_id)

            if 0 == item_num:
                break

        defer.returnValue((NO_ERROR, used_attribs))
Exemple #45
0
    def __init__(self, host=None, user=None, password=None, database=None, max_idle_time=7*3600):
        self.host = config['mysql']['host'] if host is None else host
        self.database = config['mysql']['database'] if database is None else database
        self.max_idle_time = max_idle_time

        args = dict(conv=CONVERSIONS, use_unicode=True, charset="utf8",
                    db=self.database, init_command='SET time_zone = "+0:00"',
                    sql_mode="TRADITIONAL")
        args["user"] = config['mysql']['user'] if user is None else user
        args["passwd"] = config['mysql']['password'] if password is None else password

        # We accept a path to a MySQL socket file or a host(:port) string
        if "/" in self.host:
            args["unix_socket"] = self.host
        else:
            self.socket = None
            pair = self.host.split(":")
            if len(pair) == 2:
                args["host"] = pair[0]
                args["port"] = int(pair[1])
            else:
                args["host"] = self.host
                args["port"] = 3306

        self._db = None
        self._db_args = args
        self._last_use_time = time.time()
        try:
            self.reconnect()
        except Exception:
            log.error("Cannot connect to MySQL on %s", self.host, exc_info=True)
Exemple #46
0
 def __init__(self, filename, width=None, height=None, kind='direct'):
     Flowable.__init__(self)
     ext = os.path.splitext(filename)[-1]
     self._kind = kind
     # Prefer svglib for SVG, as it works better
     if ext in ('.svg', '.svgz') and svglib is not None:
         self._mode = 'svglib'
         self.doc = svglib.svg2rlg(filename)
         self.width = width
         self.height = height
         _, _, self._w, self._h = self.doc.getBounds()
         if not self.width:
             self.width = self._w
         if not self.height:
             self.height = self._h
     # Use uniconvertor for the rest
     elif load is not None:
         self._mode = 'uniconvertor'
         self.doc = load.load_drawing(filename.encode('utf-8'))
         self.saver = plugins.find_export_plugin(
             plugins.guess_export_plugin('.pdf'))
         self.width = width
         self.height = height
         _, _, self._w, self._h = self.doc.BoundingRect()
         if not self.width:
             self.width = self._w
         if not self.height:
             self.height = self._h
     else:
         self._mode = None
         log.error("Vector image support not enabled,"
                   " please install svglib and/or uniconvertor.")
     if self._mode:
         self.__ratio = float(self.width) / self.height
Exemple #47
0
def __broadcast(user_remain, func, args):
    log.error('================__broadcast user_remain:{0}, func:{1}, args: {2}.'.format(len(user_remain), func, args))
    if user_remain:
        i = 0
        while i < MAX_BROADCAST_PER_LOOP:
            i += 1
            _user = user_remain.pop( 0 )
            if _user:
                if hasattr(_user, 'p'):
                    if hasattr(_user.p, 'transport'):
                        if _user.p.transport:
                            _user.p.send(func, args)
                            log.warn('================uid:{0}, func:{1}, args:{2}'.format(_user.uid, func, args))
                        else:
                            log.warn('__broadcast. uid:{0}, unknown t:{1}.'.format(_user.uid, _user.p.transport))
                            g_UserMgr.del_zombie_user( _user.uid )
                    else:
                        log.warn('__broadcast. uid:{0}, the p has no transport attribute..'.format(_user.uid))
                        g_UserMgr.del_zombie_user( _user.uid )
                else:
                    log.warn('__broadcast. uid:{0}, the user has no p attribute..'.format(_user.uid))
                    g_UserMgr.del_zombie_user( _user.uid )
            else:
                log.info('__broadcast. Unknown user.')

            if not user_remain:
                break
        else:
            reactor.callLater(1, __broadcast, user_remain, func, args)
Exemple #48
0
 def callHooks(self, hook_args):
     """Calls a hook function with the given hook args."""
     numeric, command, parsed_args = hook_args
     # Always make sure TS is sent.
     if 'ts' not in parsed_args:
         parsed_args['ts'] = int(time.time())
     hook_cmd = command
     hook_map = self.proto.hook_map
     # Handlers can return a 'parse_as' key to send their payload to a
     # different hook. An example of this is "/join 0" being interpreted
     # as leaving all channels (PART).
     if command in hook_map:
         hook_cmd = hook_map[command]
     hook_cmd = parsed_args.get('parse_as') or hook_cmd
     log.debug(
         '(%s) Parsed args %r received from %s handler (calling hook %s)',
         self.name, parsed_args, command, hook_cmd)
     # Iterate over hooked functions, catching errors accordingly
     for hook_func in world.hooks[hook_cmd]:
         try:
             log.debug('(%s) Calling hook function %s from plugin "%s"',
                       self.name, hook_func, hook_func.__module__)
             hook_func(self, numeric, command, parsed_args)
         except Exception:
             # We don't want plugins to crash our servers...
             log.exception(
                 '(%s) Unhandled exception caught in hook %r from plugin "%s"',
                 self.name, hook_func, hook_func.__module__)
             log.error('(%s) The offending hook data was: %s', self.name,
                       hook_args)
             continue
Exemple #49
0
    def reconnectUser(self, p, cid, session_key):
        user = self.user_dic.get(cid, None)
        if user:
            if  user.session_key != session_key:
                log.error('Session not match. old sk: {0}, new sk:{1}.'.format( user.session_key, session_key ))
                return RECONNECT_FAIL
            #if False == user.temp_lost:
            #    log.error('It is not temp lost client. cid:', user.cid)
            #    return CONNECTION_LOSE

            # check old protocol is valid or not.
            old_p = user.p
            user.p = None
            if old_p:
                old_p.lose_connect = True
                if hasattr(old_p, 'cid') and old_p.cid:
                    old_p.cid = 0
                if old_p.transport:
                    old_p.transport.loseConnection()

            user.p = p
            user.temp_lost = False
            user.logout_timestamp = 0

            p.cid = user.cid
            p.account = user.account
            p.session_key = user.session_key

            log.info('Reconnect ok. cid: {0}, lose_connect: {1}.'.format( p.cid, p.lose_connect ))
            return NO_ERROR
        else:
            log.error('Can not find cid: {0}.'.format( cid ))
            return CONNECTION_LOSE
Exemple #50
0
    def new(self, item_id, item_num, way_type=WAY_UNKNOWN, way_others=''):
        yield self._load()
        item_conf = get_item_by_itemid(item_id)
        if not item_conf:
            log.error('Can not find conf. cid: {0}, item_id: {1}.'.format(
                self.cid, item_id))
            defer.returnValue((NOT_FOUND_CONF, None))
        # 检查道具类型
        item_type = item_conf['ItemType']
        if item_type not in BAG_JADE:
            log.error('new. Item type error. cid: {0}, item_id: {1}.'.format(
                self.cid, item_id))
            defer.returnValue((ITEM_TYPE_ERROR, None))

        time_now = int(time())
        new_items = []

        while item_num >= 1:
            res_err, new_attrib = yield self.create_table_data(
                item_type, item_id, 1, time_now)
            if res_err:
                defer.returnValue((UNKNOWN_ERROR, None))
            item_num -= 1
            new_items = self.add_new_items(
                [new_attrib.attrib_id, item_type, item_id, 1], new_items)

        # add syslog
        for _item in new_items:
            syslogger(LOG_ITEM_GET, self.cid, self.user.level,
                      self.user.vip_level, self.user.alliance_id, _item[0],
                      _item[2], _item[3], way_type, way_others)
        defer.returnValue((NO_ERROR, new_items))
Exemple #51
0
def hostActionCopyConfig(_config):
    global INITRD_ESX_CONF_CHECKSUM
    
    globsToCopy = [
        '/etc/hosts',
        '/etc/resolv.conf',
        '/etc/vmware/esx.conf',
        '/etc/xinetd.d/vmware-authd', # Referenced when turning off ipv6
        '/etc/modprobe.d/blacklist', # Referenced when turning off ipv6
        '/etc/sysconfig/network',
        '/etc/sysconfig/network-scripts/ifcfg-vswif*',
        ]

    # TODO: remove this configcheck, it should be done on bootup.  It's safe
    # to run multiple times though.
    rc = os.system(os.path.join(HOST_ROOT, "usr/sbin/esxcfg-configcheck"))
    assert rc == 0

    for globPath in globsToCopy:
        for srcPath in glob.glob(globPath):
            dstPath = os.path.join(HOST_ROOT, srcPath.lstrip('/'))
            try:
                clonePath(srcPath, dstPath)
                if os.path.islink(srcPath):
                   os.lchown(dstPath, 0, 0)
                else:
                   os.chown(dstPath, 0, 0)

                # XXX Maybe we should turn the files in the initrd into soft
                # links that point at the installed versions of the files...
            except IOError, e:
                log.error("cannot copy %s to %s -- %s" % (
                    srcPath, dstPath, str(e)))
Exemple #52
0
    def create_table_data(self,
                          item_type,
                          item_id,
                          item_num,
                          time_now,
                          camp_id=0,
                          position_id=0,
                          level=0,
                          exp=0):
        gsattrib = GSAttribute(self.cid, GSBagJadeMgr._table)
        res_err = yield gsattrib.new(cid=self.cid,
                                     item_type=item_type,
                                     item_id=item_id,
                                     item_num=item_num,
                                     camp_id=camp_id,
                                     position_id=position_id,
                                     level=level,
                                     exp=exp,
                                     deleted=0,
                                     create_time=time_now,
                                     update_time=time_now,
                                     del_time=0)
        if res_err:
            log.error('GSBagJadeMgr create table data error. ')
            defer.returnValue((res_err, None))

        self.__gsattribs[gsattrib.attrib_id] = gsattrib
        defer.returnValue((NO_ERROR, gsattrib))
Exemple #53
0
    def reconnectUser(self, p, uid):
        user = self.all_users.get(uid, None)
        if user:
            #if  user.session_key != session_key:
            #    log.error('Session not match. old sk: {0}, new sk:{1}.'.format( user.session_key, session_key ))
            #    return RECONNECT_FAIL
            #if False == user.temp_lost:
            #    log.error('It is not temp lost client. uid:', user.uid)
            #    return CONNECTION_LOSE

            # check old protocol is valid or not.
            old_p = user.p
            user.p = None
            if old_p:
                old_p.lose_connect = True
                if hasattr(old_p, 'uid') and old_p.uid:
                    old_p.uid = 0
                if old_p.transport:
                    old_p.transport.loseConnection()

            user.p = p
            user.uid = user.uid
            user.machine_code = user.machine_code
            user.nickname = user.nickname
            user.temp_lost = False
            user.logout_timestamp = 0

            log.info('Reconnect ok. uid: {0}, lose_connect: {1}.'.format( p.uid, p.lose_connect ))
            return NO_ERROR
        else:
            log.error('Can not find uid: {0}.'.format( uid ))
            return CONNECTION_LOSE
Exemple #54
0
    def set_one_touch(self, *args):
        '''
        @summary: 一键装备玉魄
        '''
        camp_id, one_touch_data = args

        positions = yield self.get_camp_positions(camp_id)

        for pos_id, new_ujid in enumerate(one_touch_data):
            if new_ujid <= 0:
                continue
            attrib = yield self.get(new_ujid)
            if not attrib:
                log.error(
                    'Unknown jade error. cid: {0}, new_ujid: {1}.'.format(
                        self.cid, new_ujid))
                continue
            pos_id += 1
            # 处理该pos_id上的旧的玉魄
            pos_old_attrib = positions.get(pos_id, None)
            if pos_old_attrib:
                pos_old_attrib.camp_id = 0
                pos_old_attrib.position_id = 0

            attrib.camp_id = camp_id
            attrib.position_id = pos_id

        defer.returnValue(NO_ERROR)
Exemple #55
0
def repo_file(owner, repo, path, filename='slides.md'):
    try:
        repo_resp = gh.repos(owner)(repo).contents(path + '/' + filename)

        if 'raw' not in request.args and filename == 'slides.md':
            branch = request.args.get('branch', 'master')
            log.info('Fetching slides(%s): /%s/%s/%s/%s', branch, owner, repo, path, filename)
            repo_resp = repo_resp.get(ref=branch)
            slides = _repo_slides(repo_resp)
            return render_template('slideshow.html', slides=slides)
        else:
            # Fix branch in attachments
            query = urlparse.urlparse(request.referrer).query
            branch = urlparse.parse_qs(query).get('branch', ['master'])[0]

            log.info('Fetching attach(%s): /%s/%s/%s/%s', branch, owner, repo, path, filename)
            log.info('  Referrer: %s', request.referrer)
            repo_resp = repo_resp.get(ref=branch)
            is_style = filename.lower().endswith('.css')
            if request.args.get('raw') == '1' or is_style:
                raw_content = base64.b64decode(repo_resp.get('content', '')).decode('utf-8')
                if is_style:
                    return Response(raw_content, mimetype='text/css')
                else:
                    return raw_content
            else:
                return redirect(_repo_attach(owner, repo, branch, path, filename))

    except ApiNotFoundError, e:
        log.error(e.response)
Exemple #56
0
    def reconnectUser(self, p, cid, session_key):
        user = self.user_dic.get(cid, None)
        if user:
            if user.session_key != session_key:
                log.error('Session not match. old sk: {0}, new sk:{1}.'.format(
                    user.session_key, session_key))
                return RECONNECT_FAIL
            #if False == user.temp_lost:
            #    log.error('It is not temp lost client. cid:', user.cid)
            #    return CONNECTION_LOSE

            # check old protocol is valid or not.
            old_p = user.p
            user.p = None
            if old_p:
                old_p.lose_connect = True
                if hasattr(old_p, 'cid') and old_p.cid:
                    old_p.cid = 0
                if old_p.transport:
                    old_p.transport.loseConnection()

            user.p = p
            user.temp_lost = False
            user.logout_timestamp = 0

            p.cid = user.cid
            p.account = user.account
            p.session_key = user.session_key

            log.info('Reconnect ok. cid: {0}, lose_connect: {1}.'.format(
                p.cid, p.lose_connect))
            return NO_ERROR
        else:
            log.error('Can not find cid: {0}.'.format(cid))
            return CONNECTION_LOSE
Exemple #57
0
    def refine_replace(self, user_equip_id, replace_attribute):
        '''
        @summary: 替换洗炼后的属性
        '''
        res_err = UNKNOWN_ERROR
        attrib  = yield self.get( user_equip_id )
        if not attrib:
            log.error('Can not find user equip. user_equip_id: {0}.'.format( user_equip_id ))
            defer.returnValue( res_err )

        # json格式转为列表
        _old_attribute = loads(attrib.refine_attribute) 
        for _attr in replace_attribute:
            if len(_attr) != 3:
                pass
            for _old in _old_attribute:
                if _attr[0] == _old[0]:
                    _old[1] += _attr[1]
                    _old[1] = 0 if _old[1] < 0 else _old[1]
                    break
            else:
                _attr[1] = 0 if _attr[1] < 0 else _attr[1]
                _old_attribute.append( _attr )

        attrib.refine_attribute = dumps( _old_attribute )

        defer.returnValue( (user_equip_id, _old_attribute) )
def format_body_for_ci(body):
    try:
        body_list = []
        for k,v in body.iteritems():
            body_list.append({
                              "name":k,
                              "value":v
                              })
            
        param_dict = {
                      "parameter":body_list
                      }
        
        param_str = json.dumps(param_dict)
        
        body = "json=%s&Submit=Build" % param_str
        body = {"json":param_str,
                "Submit":"Build"}
        body_urlencoded = urllib.urlencode(body)
        
        return body_urlencoded
        
    except Exception,e:
        log.error(e)
        return ""
Exemple #59
0
    def new(self, **kwargs):

        _dirty_fields = []
        _values       = []

        for k, v in kwargs.iteritems():
            _dirty_fields.append(k)
            if k in self.__time_fields and v:
                v = datetime.fromtimestamp( v )
                kwargs[k] = v
            _values.append(v)
        self.__dict__.update(kwargs)
        _sql = 'INSERT INTO %s (' % self.table  + ','.join(_dirty_fields) + ') VALUES (' \
                            + ','.join(['%s'] * len(_values)) + ')'

        res = yield db.insert(_sql, _values)
        if self.table == 'tb_character':
            if res > 1000000:
                db.execute('DELETE FROM {0} WHERE id={1};'.format(self.table, res))
                log.error('insert error. res:{0}, _values:{1}.'.format( res, _values ))
                raise AttributeError('Attribute: insert new character id error')

            new_res = kwargs.get('sid', 1001)*1000000 + res
            db.execute('UPDATE {0} SET id={1} WHERE id={2};'.format(self.table, new_res, res))
            self.__uid = new_res
            log.error('For Test. table:{0}, res:{1}, new_res:{2}.'.format( self.table, res, new_res ))
        else:
            self.__uid = res
        defer.returnValue(self.__uid)
    def get_camp_treasure(self, camp_id):
        '''
        @summary: 获取camp_id的position_id对应的treasure
        '''
        yield self._load()
        _camp_treasure = [[], []]

        if not self.__camp_position.has_key(camp_id):
            defer.returnValue(_camp_treasure)

        positions = self.__camp_position[camp_id]

        # 6-兵书, 7-战马
        for _pos in range(6, 8):
            if not positions.has_key(_pos):
                continue
            user_treasure_id = positions[_pos]

            attrib = yield self.get(user_treasure_id)
            if not attrib:
                log.error('Can not find user treasure. user_treasure_id: {0}.'.
                          format(user_treasure_id))
                positions[_pos] = 0
                continue
            _camp_treasure[_pos - 6] = [
                user_treasure_id, attrib.item_id, attrib.level,
                attrib.refine_level
            ]

        defer.returnValue(_camp_treasure)