Ejemplo n.º 1
0
def log_handler(handler: Any) -> None:
    """Override tornado's logging."""
    # log only errors (status >= 500)
    if handler.get_status() >= 500:
        access_log.error(
            '{} {}'.format(handler.get_status(), handler._request_summary())
        )
Ejemplo n.º 2
0
 def render_string(self, filename, **kwargs):
     '''
         Override render_string to use mako template.
         Like tornado render_string method, this method also
         pass request handler environment to template engine
     '''
     try:
         # if not self.is_mobile:
         #     template = self.LOOK_UP.get_template(filename)
         # else:
         #     template = self.LOOK_UP_MOBILE.get_template(filename)
         template = self.LOOK_UP.get_template(filename)
         env_kwargs = dict(
             handler = self,
             request = self.request,
             locale = self.locale,
             _ = self.locale.translate,
             static_url = self.static_url,
             xsrf_form_html = self.xsrf_form_html,
             reverse_url = self.application.reverse_url,
             agent = self.agent,
         )
         env_kwargs.update(kwargs)
         return template.render(**env_kwargs)
     except:
         from mako.exceptions import RichTraceback
         tb = RichTraceback()
         for (module_name, line_no, function_name, line) in tb.traceback:
             print('File:{}, Line:{} in {}'.format(module_name, line_no, function_name))
             print(line)
         access_log.error('Render {} failed, {}:{}'.format(filename, tb.error.__class__.__name__, tb.error), 
                      exc_info=True)
         raise HTTPError(500, 'Render page failed')
Ejemplo n.º 3
0
    def post(self):
        email = self.get_argument("email", None)
        password = self.get_argument("password", None)
        if (not email) or (not password):
            self.redirect("/auth/signin")
            return
        pattern = r"^.+@[^.].*\.[a-z]{2,10}$"
        if isinstance(pattern, basestring):
            pattern = re.compile(pattern, flags=0)

        if not pattern.match(email):
            self.redirect("/auth/signin")
            return

        user = self.get_user_by_email(email)
        if not user:
            access_log.error("Login Error for email: %s" % email)
            self.redirect("/")
            return
        encryped_pass = user.password
        if PasswordCrypto.authenticate(password, encryped_pass):
            token = user.salt + "/" + str(user.id)
            self.set_secure_cookie("token", str(token))
            self.redirect(self.get_argument("next", "/post/new"))
            return
        else:
            access_log.error("Login Error for password: %s!" % password)
            self.redirect("/")
        return
Ejemplo n.º 4
0
def log_handler(handler: Any) -> None:
    """Override tornado's logging."""
    # log only errors (status >= 500)
    if handler.get_status() >= 500:
        access_log.error(
            '{} {}'.format(handler.get_status(), handler._request_summary())
        )
Ejemplo n.º 5
0
 def render_string(self, filename, **kwargs):
     '''
         Override render_string to use mako template.
         Like tornado render_string method, this method also
         pass request handler environment to template engine
     '''
     try:
         # if not self.is_mobile:
         #     template = self.LOOK_UP.get_template(filename)
         # else:
         #     template = self.LOOK_UP_MOBILE.get_template(filename)
         template = self.LOOK_UP.get_template(filename)
         env_kwargs = dict(
             handler=self,
             request=self.request,
             locale=self.locale,
             _=self.locale.translate,
             static_url=self.static_url,
             xsrf_form_html=self.xsrf_form_html,
             reverse_url=self.application.reverse_url,
             agent=self.agent,
         )
         env_kwargs.update(kwargs)
         return template.render(**env_kwargs)
     except:
         from mako.exceptions import RichTraceback
         tb = RichTraceback()
         for (module_name, line_no, function_name, line) in tb.traceback:
             print('File:{}, Line:{} in {}'.format(module_name, line_no,
                                                   function_name))
             print(line)
         access_log.error('Render {} failed, {}:{}'.format(
             filename, tb.error.__class__.__name__, tb.error),
                          exc_info=True)
         raise HTTPError(500, 'Render page failed')
Ejemplo n.º 6
0
    def search(self, query, index, page, size, *args, **kwargs):
        offset = (page - 1) * size
        self.client = sphinxapi.SphinxClient()
        self.client.SetConnectTimeout(2000.0)
        self.client.SetLimits(offset, size)
        self.client.SetMatchMode(sphinxapi.SPH_MATCH_EXTENDED2)
        self.client.SetSortMode(sphinxapi.SPH_SORT_RELEVANCE)

        result = self.client.Query(query, index=index)
        if result is None:
            errmsg = self.client.GetLastError()
            access_log.error(errmsg)
            raise Exception(errmsg)

        entry = {
            'query': query,
            'time': result['time'],
            'total_found': result['total_found'],
            'words': result['words'],
            'results': [],
        }

        for match in result['matches']:
            doc_id = match['id']
            item = self.get_item_from_db(doc_id, index)
            entry['results'].append(item)

        self.render_entry(entry)
        return entry
Ejemplo n.º 7
0
    def post(self):
        email = self.get_argument("email", None)
        password = self.get_argument("password", None)
        if (not email) or (not password):
            self.redirect("/auth/signin")
            return
        pattern = r'^.+@[^.].*\.[a-z]{2,10}$'
        if isinstance(pattern, basestring):
            pattern = re.compile(pattern, flags=0)

        if not pattern.match(email):
            self.redirect("/auth/signin")
            return

        user = self.get_user_by_email(email)
        if not user:
            access_log.error("Login Error for email: %s" % email)
            self.redirect("/")
            return
        encryped_pass = user.password
        if PasswordCrypto.authenticate(password, encryped_pass):
            token = user.salt + "/" + str(user.id)
            self.set_secure_cookie("token", str(token))
            self.redirect(self.get_argument("next", "/post/new"))
            return
        else:
            access_log.error("Login Error for password: %s!" % password)
            self.redirect("/")
        return
Ejemplo n.º 8
0
    def post(self):
        pass
        code = self.get_argument("code", None)
        msg = self.get_argument("msg", None)
        key = self.get_argument("key", None)
        user = self.get_argument("loginname", None)
        if code is None or msg is None or key is None:
            return self.write(json_dumps({"msg": u"参数错误,请检查。密码:{} 描述:{} 关键字:{}".format(code, msg, key),
                                          "error_code": 1}))

        tblcode = self.mysqldb().query(TblCode).filter(TblCode.msg == msg, TblCode.key == key).first()
        if tblcode is not None:
            return self.write(json_dumps({"msg": u"已存在", "error_code": 1}))
        else:
            tblcode = TblCode()
            md_code = self_encode(code)
            tblcode.code = md_code.decode('utf-8')
            tblcode.msg = msg
            tblcode.key = key
            tblcode.user = user

        try:
            self.mysqldb().add(tblcode)
            self.mysqldb().commit()
            return self.write(json_dumps({"msg": u"添加成功", "error_code": 0}))
        except Exception as e:
            weblog.error("add code error. {}".format(e))
            return self.write(json_dumps({"msg": u"添加失败", "error_code": 1}))
Ejemplo n.º 9
0
 def delete(self, uid):
     weblog.info("uid={}".format(uid))
     try:
         self.mysqldb().query(TblAccount).filter(TblAccount.id == uid).delete()
         self.mysqldb().commit()
         return self.write(json_dumps({"error_code": 0, "msg": u"删除成功"}))
     except Exception as e:
         weblog.error("{}".format(e))
         return self.write(json_dumps({"error_code": 1, "msg": u"删除失败。{}".format(e)}))
Ejemplo n.º 10
0
    def log_exception(self, typ, value, tb):
        if isinstance(value, HTTPError):
            if value.log_message:
                format = '%d %s: ' + value.log_message
                args = ([value.status_code, self._request_summary()] + list(value.args))
                access_log.warning(format, *args)

        access_log.error('Exception: %s\n%r', self._request_summary(), 
                     self.request, exc_info=(typ, value, tb))
Ejemplo n.º 11
0
    def __call__(self, request):
        try:
            signals_module.signals.call_started.send(sender=self.__class__)
            self.middleware_manager.run_call_hooks(request)
            handler = web.Application.__call__(self, request)
            self.middleware_manager.run_endcall_hooks(handler)
            signals_module.signals.call_finished.send(sender=self.__class__)

        except Exception, e:
            access_log.error(e)
            raise
Ejemplo n.º 12
0
 def get(self, cid):
     weblog.info("%s.", self._request_summary())
     comp_mt = self.mysqldb().query(TblComponentMaintenance).filter_by(comp_id=cid).first()
     comp_mt.comp_status = -1
     try:
         self.mysqldb().commit()
     except Exception as e:
         weblog.error("delete component maintenance id={} error. {}".format(cid, e))
         self.mysqldb().rollback()
     return self.render('bug/compmtlist.html', bugs=get_compmt_list(self),
                        users=get_user_list(self), projects=get_project_list(self))
Ejemplo n.º 13
0
 def get(self, pjid):
     weblog.info("%s. pjid=%d", self._request_summary(), pjid)
     project = self.mysqldb().query(TblProject).filter_by(
         project_id=pjid).first()  # u"必须查询对象"
     # print(project)
     try:
         project.status = 1
         self.mysqldb().commit()
     except Exception as e:
         weblog.error("delete project id={} fail:{}.".format(pjid, e))
         self.mysqldb().rollback()
     return self.redirect('/project/list')
Ejemplo n.º 14
0
    def response_status(self, code=(500, 'Server Error!')):
        status_code = code[0]
        reason = code[1]

        self.set_status(status_code, reason=reason)
        # self.set_status(code[0], code[1])
        try:
            self.write_error(status_code)
        except Exception:
            access_log.error("Uncaught exception in write_error", exc_info=True)
        if not self._finished:
            self.finish()
Ejemplo n.º 15
0
 def delete(self):
     cid = self.get_argument("cid", None)
     if cid is None:
         return self.write(json_dumps({"msg": u"id不存在", "error_code": 1}))
     else:
         cid = int(cid)
     try:
         ccode = self.mysqldb().query(TblCode).filter(TblCode.id == cid).delete()
         return self.write(json_dumps({"msg": u"删除成功", "error_code": 0}))
     except Exception as e:
         weblog.error("delete code error. {}".format(e))
         return self.write(json_dumps({"msg": u"删除失败", "error_code": 1}))
Ejemplo n.º 16
0
    def log_exception(self, typ, value, tb):
        if isinstance(value, HTTPError):
            if value.log_message:
                format = '%d %s: ' + value.log_message
                args = ([value.status_code,
                         self._request_summary()] + list(value.args))
                access_log.warning(format, *args)

        access_log.error('Exception: %s\n%r',
                         self._request_summary(),
                         self.request,
                         exc_info=(typ, value, tb))
Ejemplo n.º 17
0
    def get(self, bid):
        weblog.info("%s.", self._request_summary())
        bug_track = self.mysqldb().query(TblBugTrack).filter_by(
            comp_id=bid).first()
        bug_track.bug_project_id = -1
        try:
            self.mysqldb().commit()
        except Exception as e:
            weblog.error("delete bug track id={} error. {}".format(bid, e))
            self.mysqldb().rollback()

        return self.render('bug/bugtracklist.html',
                           bugtracks=get_bugtrack_list(self))
Ejemplo n.º 18
0
 def post(self):
     destr = self.get_argument("destr", "")
     bstr = destr.encode('utf-8')
     # print(bstr)
     error_code = 0
     weblog.info("destr:{}".format(bstr))
     try:
         result = self_decode(bstr)
     except Exception as e:
         weblog.error("{}".format(e))
         result = u"解密失败"
         error_code = 1
     return self.write(json_dumps({"decode": result, "error_code": error_code}))
Ejemplo n.º 19
0
    def get(self, code):
        try:
            email = check_signature(code, 86400)  # 24 hours
        except:
            error = 'Signature %s did not authenticate.' % code
            access_log.error(error)
            self.render(template('auth/signature_invalid.html'), error='')

        email = str(email)[2:-1]
        yield activate_user(self.db, email)
        access_log.info('%s email verified, \
                        user account activated and logged in.' % email)
        self.set_current_user(email)
        self.redirect('/')
Ejemplo n.º 20
0
 def get(self, *args, **kwargs):
     req_path = self.request.path
     func = CONTROLLER_MAP.get(req_path)
     if func is None:
         self.send_error(404)
         self.finish()
         return
     try:
         func(self, self._callback)
     except:
         logger.error(traceback.print_exc())
         self.send_error(500)
         if not self._finished:
             self.finish()
Ejemplo n.º 21
0
    def rule_del(self, rule_id):
        """ 删除操作并不是真的删除, 只是进行置位
            {
              "ANALYZER_ID": 0,         // ID为0, 表示这是一种广播操作.
              "MESSAGE": {              // 报文主体
                "COMMOND": "ADD_RULE",  // 重载过程, 这里就认为是热重启
                "SWH_ID": [
                    14, 23, 19, 40
                ],
                "COUNTER": [           // 计数器的filter
                    {
                        "CNT_ID" : 1
                        "SRC_IP": "192.118.0.2",
                        "DST_IP": "192.119.0.1"
                    }
                ]
              }
            }
        """
        if rule_id == -1:
            access_log.error('Get wrong id, del failed')

        del_sql = """UPDATE `counter_rule`
                SET `is_valid` = '0'
                WHERE `counter_rule`.`id` = {}"""

        del_sql = del_sql.format(rule_id)
        access_log.debug(del_sql)

        try:
            cur = self.db.cursor()
            cur.execute(del_sql)
            self.db.commit()
        except Exception as e:
            access_log.error('Get error {}'.format(e))
            self.write_json(None, status_code=400, msg='删除错误')
            return
        finally:
            cur.close()

        from q_listen import get_counter_rules, generate_sub
        pub_msg = {}
        pub_msg['ANALYZER_ID'] = 0
        msg = {}
        msg['COMMOND'] = 'DEL_RULE'
        msg['COUNTER'] = [rule_id]
        pub_msg['MESSAGE'] = msg
        generate_sub(pub_msg)

        self.write_json('success')
Ejemplo n.º 22
0
 def process(self):
     """
     依存关系树解析流程:
     :return:
     """
     try:
         # 1、解析每棵树
         self.parse_tree(self.tree)
         # 对实体排序
         sorted(self.entity_list.items(),
                key=lambda start: start[1].get('start_index'))
         return self.entity_list.values()
     except Exception as ex:
         access_log.error('解析树出现异常')
Ejemplo n.º 23
0
    def post(self):
        """ 对规则的操作分为两种
                1: 添加规则, 需要提供规则所需的几个信息
                    规则名称, 源IP, 目的IP, 协议类型, 镜像时的交换机ID

                2: 删除规则, 提供rule_id即可
        """

        act = self.get_argument('act', '')
        rule_name = self.get_argument('rule_name', '')
        rule_id = self.get_argument('rule_id', -1)
        ip_src = self.get_argument('ip_src', '0.0.0.0')
        ip_dst = self.get_argument('ip_dst', '0.0.0.0')
        switch_id = self.get_argument('switch_id', -1)
        protocol = self.get_argument('protocol', -1)

        try:  # IP检验
            import socket
            socket.inet_aton(ip_src)
            socket.inet_aton(ip_dst)
        except OSError as e:
            access_log.error('Get wrong ip {}, {}'.format(ip_src, ip_dst))
            self.write_json(None, status_code=400, msg='参数错误')
            return
        except Exception as e:
            access_log.error('Get error {}'.format(e))

        try:  # 试图进行转换
            rule_id = int(rule_id)
            switch_id = int(switch_id)
            protocol = int(protocol)
        except (ValueError, TypeError) as e:
            access_log.error('Get Err {} {} {}' \
                              .format(rule_id, switch_id, protocol))
            self.write_json(None, status_code=400, msg='参数错误')
            return
        except Exception as e:
            access_log.error('Get error {}'.format(e))

        if act == 'ADD':
            self.rule_add(rule_name, ip_src, ip_dst, switch_id, protocol)
        elif act == 'DEL':
            self.rule_del(rule_id)
        else:
            access_log.error('Not valid action: {}'.format(act))
            self.write_json(None, status_code=400, msg='参数错误')

        return
Ejemplo n.º 24
0
    def token_entity_process(self, token):
        """
        依据树节点生成实体对象并填充属性建立关系:
            1、建实体对象、直接关系的属性、关系建立
            2、总结的依存树规则修正实体列表及关系
        :return:
        """
        try:
            # 1、建实体对象、直接关系的属性、关系建立
            self.generate_entity_atb_relation(token)

            # 2、总结的依存树规则修正实体列表及关系
            #
            return
        except Exception as ex:
            access_log.error('生成实体列表出现问题')
Ejemplo n.º 25
0
    def post(self):
        weblog.info("%s ,sign in.", self._request_summary())
        # weblog.info("tbl_admin:%s", self.localVariable)
        userAccount = self.get_argument("userAccount")
        password = self.get_argument("password")
        inputCode = self.get_argument("inputCode")

        user = self.mysqldb().query(
            TblAccount.username,
            TblAccount.password).filter_by(username=userAccount).first()
        if user is None:
            return self.write(
                json_dumps({
                    "msg": msg_define.USER_IS_NONE,
                    "error_code": 1
                }))
        if user.username != userAccount or user.password != MD5(password):
            weblog.error("user password input:{}, ori:{}".format(
                user.password, MD5(password)))
            return self.write(
                json_dumps({
                    "msg": msg_define.USER_OR_PASSWORD_ERROR,
                    "error_code": 1
                }))
        if inputCode.upper() != self.get_secure_cookie("code").decode(
                'utf-8').upper():
            weblog.error("code you inut:{}, ori code:{}".format(
                inputCode.upper(),
                self.get_secure_cookie("code").decode('utf-8').upper()))
            return self.write(
                json_dumps({
                    "msg": msg_define.VER_CODE_ERROR,
                    "error_code": 1
                }))
        # return self.redirect("/download")
        # self.set_secure_cookie("user_account", userAccount)
        session_id = generate_uuid()
        self.set_secure_cookie(SESSION_ID, session_id)
        # print("timeout:", self.application.settings['session_timeout'])
        self.redis.set(session_id, userAccount,
                       self.application.settings['session_timeout'])
        # session manager
        # self.session["user_account"] = userAccount
        # self.session.save()
        # weblog.info(self.session.get('user_account'))
        # weblog.info(self.session.get(self))
        return self.write(json_dumps({"msg": "", "error_code": 0}))
Ejemplo n.º 26
0
 def write_error(self, status, **kargs):
     self.set_headers()
     exc_info = kargs.pop('exc_info', None)
     if exc_info:
         stack_trace = traceback.format_exception(*exc_info)
         stack_trace = str.join('', stack_trace).rstrip('\n')
         stack_trace = ('%s\n%s' % (self.uuid, stack_trace))
         if status >= 500:
             access_log.error(stack_trace)
         elif status >= 400:
             access_log.warning(stack_trace)
         elif status >= 200:
             access_log.info(stack_trace)
     data = kargs.pop('data', None)
     if data:
         self.write_json(data)
     self.finish()
Ejemplo n.º 27
0
    def post(self):
        """ 对于程序来说, 必须提供时间以及rule_id
        """
        start_time = self.get_argument('start_time', None)
        end_time = self.get_argument('end_time', None)

        rule_id = self.get_argument('rule_id', 0)

        try:  # 时间检验
            start_time = to_time_stamp(start_time)
            end_time = to_time_stamp(end_time)
        except (ValueError, TypeError) as e:
            access_log.error('Get err time {}, {}'.format(
                start_time, end_time))
            self.write_json(None, status_code=400, msg='参数错误')
            return
        except Exception as e:
            access_log.error('Get error {}'.format(e))

        try:  # 试图进行转换
            rule_id = int(rule_id)
        except (ValueError, TypeError) as e:
            access_log.error('Get Err {}' \
                              .format(rule_id))
            self.write_json(None, status_code=400, msg='参数错误')
            return
        except Exception as e:
            access_log.error('Get error {}'.format(e))

        last_sql = QUERY_SQL
        day1 = int(time_to_day(start_time))
        day2 = int(time_to_day(end_time))

        last_sql += ' AND fdate BETWEEN {} AND {}'.format(day1, day2)
        last_sql +=  ' AND generate_time > \'{}\' AND generate_time < \'{}\'' \
                    .format(time_print(start_time), time_print(end_time))

        if rule_id != 0:
            last_sql += ' AND rule_id = {}'.format(rule_id)

        access_log.debug(last_sql)

        rlts = []
        try:
            cur = self.db.cursor()
            cur.execute(last_sql)
            rlts = cur.fetchall()
        finally:
            cur.close()

        for r in rlts:
            r['generate_time'] = time_print(
                (date_to_stamp(r['generate_time'])))

        self.write_json(rlts)
    def __file_check_hash__(self, tgt, check_file, md5value):

        result = self.local.cmd(tgt, 'file.check_hash', [check_file, md5value],
                                expr_form='list', timeout=10)

        result_list = []
        for i in tgt:
            if result.has_key(i):
                result_list.append({"id": i, "ret": result[i], "result": result[i]})
                if result[i] == True:
                    access_log.info('%s md5_check %s result %s' % (i, check_file, result[i]))
                else:
                    access_log.error('%s md5_check %s result %s' % (i, check_file, result[i]))
            else:
                result_list.append({"id": i, "result": False})
                access_log.error('%s md5_check result %s' % (i, 'No Connect'))

        return result_list
Ejemplo n.º 29
0
    def add_topic(self, title, content, category):
        uid = get_user_id(self)
        if uid is None:
            return self.write(json_dumps({"msg": u"您已掉线,请重新登录"}))
        topic = TblTopic()
        topic.title = title
        topic.content = content
        topic.author = uid
        topic.category = category

        try:
            self.mysqldb().add(topic)
            self.mysqldb().commit()
            return self.write(json_dumps({"msg": None}))
        except Exception as e:
            weblog.error("add topic to mysql error:{}".format(e))
            self.mysqldb().rollback()
            return self.write(json_dumps({"msg": u"写入数据库失败"}))
Ejemplo n.º 30
0
    def edit_topic(self, title, content, category, topic_id):

        topic = self.mysqldb().query(TblTopic).filter(
            TblTopic.id == topic_id).first()
        if topic is None:
            return self.write(json_dumps({"msg": u"该话题不存在,请刷新"}))

        topic.title = title
        topic.content = content
        topic.category = category

        try:
            self.mysqldb().commit()
            return self.write(json_dumps({"msg": None}))
        except Exception as e:
            weblog.error("add topic to mysql error:{}".format(e))
            self.mysqldb().rollback()
            return self.write(json_dumps({"msg": u"修改失败"}))
Ejemplo n.º 31
0
    def post(self):
        email = self.get_argument('email')
        password = self.get_argument('password')
        if not is_valid_email(email):
            error = 'Please enter a valid email address'
            self.render(template('auth/register.html'), error=error)

        yield send_verification_email(email)

        rdb = yield add_user(self.db, email, password)
        if rdb.get('first_error') is None:
            access_log.info('%s registered and \
                            verification email sent.' % email)
            self.render(template('auth/verify_email.html'))
        else:
            access_log.error(rdb.get('first_error'))
            error = 'An error occurred adding user to the database.'
            self.render(template('auth/register.html'), error=error)
Ejemplo n.º 32
0
    def put(self):
        enstr = self.get_argument("enstr", "")
        bstr = enstr.encode('utf-8')

        # print(bstr)
        weblog.info("enstr:{}".format(bstr))
        error_code = 0
        if len(bstr) > 20:
            error_code = 1
            return self.write(json_dumps({"encode": u"字符长度需小于20", "error_code": error_code}))
        try:
            result = self_encode(bstr)
            if isinstance(result, bytes):
                result = result.decode()
        except Exception as e:
            weblog.error("{}".format(e))
            result = u"加密失败"
            error_code = 1
        return self.write(json_dumps({"encode": result, "error_code": error_code}))
    def __rsync_cmd__(self, tgt, source_file, dst_file):
        dict = {
            'delete': True,
            'update': True,
        }
        result = self.local.cmd(tgt, 'rsync.rsync', [source_file, dst_file],
                                kwarg=dict,
                                expr_form='list', timeout=10)

        result_list = []
        for i in tgt:
            if result.has_key(i):
                result_list.append({"id": i, "ret": result[i], "result": True})
                access_log.info('%s rsync %s to %s success' % (i, source_file, dst_file))
            else:
                result_list.append({"id": i, "result": False})
                access_log.error('%s rsync %s to %s No Connect' % (i, source_file, dst_file))

        return result_list
Ejemplo n.º 34
0
    async def get(self, *args, **kwargs):
        try:
            method_info = self.methods.get('get')
            if method_info is None:
                self.send_error(status_code=404, reason="not found")
                return
            call_func = method_info['func']
            filter_funcs = method_info['filters']
            request_obj = MetaRequest(self)

            for each_filter in filter_funcs:
                view_obj = each_filter(request_obj)
                if not isinstance(view_obj, BasicView):
                    self.send_error(status_code=500, reason="internal error")
                    return

                if isinstance(view_obj, ChainView):
                    continue

                view_obj.render(request=self)
                return

            try:
                view_obj = await call_func(request_obj, *args, **kwargs)
            except CoreError as e:
                logger.error('%s:%s' % (e.__class__.__name__, e.message))
                if getattr(e, "can_out_put", None):
                    msg = e.message
                else:
                    msg = ""
                view_obj = JsonView({'code': 'ERROR', 'msg': msg, 'data': {}})
                view_obj.render(request=self)
                return

            if not isinstance(view_obj, BasicView):
                self.send_error(status_code=500, reason="internal error")
                return
            view_obj.render(request=self)
        except Exception as e:
            logger.exception(e)
            self.send_error(status_code=500, reason='internal error')
    def __file_copy_cmd__(self, tgt, source_file, dst_file, **kwargs):

        dict = {
            'recurse': True,
            'remove_existing': True,
        }

        result = self.local.cmd(tgt, 'file.copy', [source_file, dst_file],
                                kwargs=dict,
                                expr_form='list', timeout=10)

        result_list = []
        for i in tgt:
            if result.has_key(i):
                result_list.append({"id": i, "ret": result[i], "result": True})
                access_log.info('%s copy %s to %s success' %(i, source_file, dst_file))
            else:
                result_list.append({"id": i, "result": False})
                access_log.error('%s copy %s to %s No Connect' %(i, source_file, dst_file))

        return result_list
Ejemplo n.º 36
0
    def _handle_request_exception(self, e):
        if isinstance(e, tornado.web.Finish):
            # not an error; just finish the request without loggin.
            if not self._finished:
                self.finish(*e.args)
            return
        try:
            self.log_exception(*sys.exc_info())
        except Exception:
            access_log.error('Error in exception logger', exc_info=True)

        if self._finished:
            return 
        if isinstance(e, HTTPError):
            if e.status_code not in BaseHandler.RESPONSES and not e.reason:
                tornado.gen_log.error('Bad HTTP status code: %d', e.status_code)
                self.send_error(500, exc_info=sys.exc_info())
            else:
                self.send_error(e.status_code, exc_info=sys.exc_info())
        else:
            self.send_error(500, exc_info=sys.exc_info())
Ejemplo n.º 37
0
    def handle(self, string, connection):
        """
        used to find which function will be called due to command string
        """

        try:
            cmd = simplejson.loads(string)
        except Exception:
            raise CeQuantCoreError('can not parse import json', trace=True)
        taskname = cmd.get('taskname', 'None')
        immediately = cmd.get('immediately')
        if immediately is None:
            immediately = False
        else:
            immediately = True
        if taskname:
            if self.cmdmanager.hascmd(taskname):
                try:
                    resobj = self.cmdmanager.excute(taskname, cmd)
                    msgobj = create_success_msg(
                        '%s successfully executed' % taskname, resobj)
                except CeQuantError as e:
                    logger.error(e.get_format_error_info())
                    msgobj = create_error_msg(e.detail, e.err_source)
                except:
                    logger.error(traceback.format_exc())
                    msgobj = create_error_msg('unknown error')
                finally:
                    callback(connection, msgobj.out())
                    return
            else:
                try:
                    msgobj = self.instructmanager.handle(
                        taskname, cmd, callback, connection)
                except CeQuantError as e:
                    logger.error(e.get_format_error_info())
                    msgobj = create_error_msg(e.detail, e.err_source)
                    callback(connection, msgobj.out())
                except:
                    logger.error(traceback.format_exc())
                    msgobj = create_error_msg('unknown error')
                    callback(connection, msgobj.out())
                else:
                    if immediately:
                        callback(connection, msgobj.out())
                    return
        else:
            msgobj = create_error_msg('no such taskname')
            callback(connection, msgobj.out())
            return
Ejemplo n.º 38
0
 def _load_script(path: str):
     if importlib.util.find_spec(
             f"simserve.plugins.{os.path.splitext(os.path.basename(path))[0]}"
     ):
         return importlib.import_module(f"simserve.plugins.{path}")
     elif os.path.isfile(f"{os.getcwd()}/{path}.py") or os.path.isfile(
             f"{os.getcwd()}/{path}"):
         path = f"{os.getcwd()}/{path}"
         path = f"{path}.py" if os.path.isfile(f"{path}.py") else f"{path}"
         module_name = f"__simserve_plugin__.{os.path.splitext(os.path.basename(path))[0]}"
         try:
             spec = importlib.util.spec_from_file_location(
                 module_name, path)
             module = importlib.util.module_from_spec(spec)
             sys.modules[module_name] = module
             spec.loader.exec_module(module)
         except Exception as e:
             access_log.error(f"Could not load plugin. {e}")
             raise tornado.web.HTTPError(500)
         return module
     elif os.path.isfile(path):
         module_name = f"__simserve_plugin__.{os.path.splitext(os.path.basename(path))[0]}"
         try:
             spec = importlib.util.spec_from_file_location(
                 module_name, path)
             module = importlib.util.module_from_spec(spec)
             sys.modules[module_name] = module
             spec.loader.exec_module(module)
         except Exception as e:
             access_log.error(f"Could not load plugin. {e}")
             raise tornado.web.HTTPError(500)
         return module
     else:
         access_log.error("Couldn't find plugin to load.")
         raise tornado.web.HTTPError(500)
Ejemplo n.º 39
0
    def post(self, topic_id, *args, **kwargs):
        dicuess = self.get_argument("discuss")
        did = self.get_argument("did", '0')
        # topic_id = self.get_argument("topic_id", None)

        if dicuess is None or dicuess == "":
            msg = u"评论不能为空"
            return self.write(json_dumps({"msg": msg}))
        if did is None or topic_id is None:
            msg = u"获取信息失败"
            return self.write(json_dumps({"msg": msg}))
        else:
            topic_id = int(topic_id)
            did = int(did)

        user_id = self.mysqldb().query(TblAccount.id).filter(
            TblAccount.username == self.current_user).first()
        if user_id is None:
            uid = 1
        else:
            uid = user_id[0]
        new_discuss = TblDiscuss()
        new_discuss.status = 0
        new_discuss.discuss = dicuess
        new_discuss.original = did
        new_discuss.topic_id = topic_id
        new_discuss.author = uid
        topic = self.mysqldb().query(TblTopic).filter(
            TblTopic.id == topic_id).first()
        topic.discuss += 1
        print(self.current_user, topic.discuss)
        try:
            self.mysqldb().add(new_discuss)
            self.mysqldb().commit()
            return self.write(json_dumps({"msg": None}))
        except Exception as e:
            self.mysqldb().rollback()
            msg = u"发布失败"
            weblog.error("publish dicuess error:{}".format(e))
            return self.write(json_dumps({"msg": msg}))
Ejemplo n.º 40
0
    def load_json(self):
        """Load JSON from the request body and store them in
        self.request.arguments, like Tornado does by default for POSTed form
        parameters.

        If JSON cannot be decoded, raises an HTTPError with status 400.
        """
        json_headers = (
            "text/json",
            # "text/javascript",
            "application/json",  # default
            # "application/javascript",
        )
        if self.request.headers['Content-Type'] in json_headers:
            try:
                self._json_args = json_decode(self.request.body)
            except ValueError:
                msg = "Could not decode JSON: %s" % self.request.body
                access_log.error(msg)
                raise tornado.web.HTTPError(400, msg)
        else:
            access_log.error('Content-Type is not application/json.')
            raise tornado.web.HTTPError(400)