def on_hr_report(self, context, mood): if mood == "好": context.finish() return Result.ok(data="Geek文化嘛,多大点儿事") else: context.stop() return Result.ok(data="不诚信,违反价值观,严肃处理")
def _validate_tpl_bind_args(self, flow_meta, bind_args): new_bind_args = {} for job_ref in flow_meta.jobs: job = self._job_mgr.get(job_ref.job_name) new_bind_args[job.name] = {} for event, job_arg_declares in job.job_args.items(): new_bind_args[job.name][event] = {} for job_arg_declare in job_arg_declares: try: bind_value = get_from_nested_dict( bind_args, job.name, event, job_arg_declare.name) # const 类型的参数不允许被绑定 if job_arg_declare.mark == JobArg.MARK_CONST: continue # 如果为None并且是auto类型,那么可以在此不检查 if bind_value is None and \ job_arg_declare.mark == JobArg.MARK_AUTO: continue # 执行校验并替换新值 new_value = job_arg_declare.field_info(bind_value) new_bind_args[job.name][event][ job_arg_declare.name] = new_value except InvalidFieldException as e: field_name = "{job_name}_{event}_{arg_name}".format( job_name=job.name, event=event, arg_name=job_arg_declare.name) full_reason = "{field_name}_{reason}".format( field_name=field_name, reason=e.reason) # 产生错误消息 loc, _ = locale.getlocale(locale.LC_ALL) msg = default_validate_messages[loc][e.reason] if e.expect is None: msg = msg.format(field_name=field_name) else: msg = msg.format(field_name=field_name, expect=e.expect) return Result.bad_request(full_reason, msg=msg) return Result.ok(data=new_bind_args)
def get_all_flow_templates(self): """获取所有的flow_templates列表 """ all_flow_templates = self._flow_tpl_dao.query_all_templates() if not all_flow_templates: return Result.ok(data=[]) users = self._user_dao.query_users_by_id_list( [tpl.creator for tpl in all_flow_templates], to_dict=True) templates_view = [ FlowTemplateView.from_flow_template(tpl, users[tpl.creator]) for tpl in all_flow_templates ] return Result.ok(data=templates_view)
def add_user(self, email: str, password: str, name: str, role: int, operator: int) -> Result: """添加新用户 S1. 检查邮箱是否存在 S2. 检查角色是否存在 S3. 检查operator是否有权限 S4. 创建新用户 :param email: 邮箱地址 :param password: 密码,会经过sha1加密 :param name: 姓名 :param role: 角色编号 :param operator: 操作者 """ # 检查是否已注册 if self._user_dao.is_email_exist(email): raise BadReq("email_exist", email=email) # 检查角色是否合法 if not self._role_dao.query_role_by_id(role): raise BadReq("role_not_found", role=role) # 检查操作者信息及权限 operator_model = self._user_dao.query_user_by_id(operator) if operator_model is None: raise BadReq("operator_not_found") operator_role = self._role_dao.query_role_by_id(operator_model.role) if operator_role.name != "admin": raise BadReq("not_allow_operation") # 创建新用户 new_user = self._user_dao.insert_user( email, sha1(password), name, role) return Result.ok(data=new_user)
def get_all_flow_meta(self) -> Result: """获得所有注册到容器的flow_meta信息 :return [ { "name": "mooncake_flow", "description": "just a test flow", "jobs": [ { "step_name": "programmer", "job_name": "programmer", "bind_args": { "trigger": { "a": 1, "b": 2, } } } ] }, ] """ all_flow_meta = [ FlowMetaView.from_flow_meta(meta, self._job_mgr) for meta in self._flow_meta_mgr.all() ] return Result.ok(data=all_flow_meta)
def _func(self, *args, **kwds): nonlocal fields_dict try: # 组装并验证参数 new_args = [ field(arg_val) for field, arg_val in zip(fields, args) ] new_kwds = { arg_name: fields_dict[arg_name](arg_val) for arg_name, arg_val in kwds.items() } except InvalidFieldException as e: full_reason = "{field_name}_{reason}".format( field_name=e.field_name, reason=e.reason) loc, _ = locale.getlocale(locale.LC_ALL) service_id = self.__class__.__name__ mtd_name = f.__name__ # 先从用户messages集合中获取 msg = get_from_nested_dict(messages, loc, service_id, mtd_name, full_reason) if msg is None: # 用户messages集合取不到再取默认的 msg = default_validate_messages[loc][e.reason] if e.expect is not None or e.expect != "": msg = msg.format(field_name=e.field_name, expect=e.expect) else: msg = msg.format(field_name=e.field_name) else: if e.expect is not None or e.expect != "": msg = msg.format(expect=e.expect) return Result.bad_request(full_reason, msg=msg) else: try: return f(self, *new_args, **new_kwds) except BadReq as e: loc, _ = locale.getlocale(locale.LC_ALL) msg = messages[loc][self.__class__.__name__][f.__name__][ e.reason] if e.args: msg = msg.format(**e.args) return Result.bad_request(e.reason, msg=msg)
def check_token(self, token: str) -> Result: """检查token S1. 查找token相关的用户信息 S2. 返回token关联简单会话数据 """ session_data = self._user_token_dao.query_session_data(token) if session_data is None: raise BadReq("invalid_token") return Result.ok(data=session_data)
def _check_token(self): """检查请求头中的token是否合法 """ try: token = self.request.headers["token"] return self._("UserService").check_token(token) except KeyError: return Result.bad_request("token_not_exist", "Can't find token in request headers")
def _gen_bad_req_result(self, e, full_field_name): loc, _ = locale.getlocale(locale.LC_ALL) full_reason = "{full_field_name}_{reason}".format( full_field_name=full_field_name, reason=e.reason) msg = default_validate_messages[loc][e.reason] if e.expect is None or e.expect == "": msg = msg.format(field_name=full_field_name) else: msg = msg.format(field_name=full_field_name, expect=e.expect) return Result.bad_request(reason=full_reason, msg=msg)
def get_flow_meta_info(self, flow_meta_name) -> Result: """获取单个的flow_meta详情 """ try: flow_meta = self._flow_meta_mgr.get(flow_meta_name) except ObjectNotFoundException: raise BadReq("flow_meta_not_exist", flow_meta=flow_meta_name) return Result.ok( data=FlowMetaView.from_flow_meta(flow_meta, self._job_mgr))
def _check_and_combine_action_args(self, job_def, target_action, request_args, job_ref, flow_template): job_arg_defines = job_def.job_args.get(target_action) # 无参数定义 if not job_arg_defines: return Result.ok(data={}) # 获取各级的参数绑定 meta_bind_args = job_ref.bind_args.get(target_action, {}) tpl_bind_args = flow_template.bind_args.get(job_ref.step_name, {}).get(target_action, {}) args_chain = ChainMap(request_args, tpl_bind_args, meta_bind_args) # 最终生成使用的参数集合 args = {} for job_arg_define in job_arg_defines: try: arg_name = job_arg_define.name # auto 类型,直接从chain中取值 if job_arg_define.mark == JobArg.MARK_AUTO: value = args_chain[arg_name] # static类型,从template中取值 elif job_arg_define.mark == JobArg.MARK_STATIC: value = tpl_bind_args.get(arg_name, None) # const类型,从meta中取值 elif job_arg_define.mark == JobArg.MARK_CONST: value = meta_bind_args.get(arg_name, None) args[arg_name] = job_arg_define.field_info(value) except InvalidFieldException as e: full_field_name = "{step}.{action}.{arg}".format( step=job_ref.step_name, action=target_action, arg=arg_name) return self._gen_bad_req_result(e, full_field_name) return Result.ok(data=args)
def _combine_and_check_args(self, action_name, field_rules, *args_dict): """合并 & 检查参数 先合并,后检查 :param field_rules: 字段规则 :param old_args """ _combined_args = ChainMap(*args_dict).new_child() # 木有验证规则,直接返回数据 if not field_rules: return Result.ok(data=_combined_args) try: for field_rule in field_rules: # 检查并替换掉相关参数 val = field_rule(_combined_args[field_rule.name]) _combined_args[field_rule.name] = val except InvalidFieldException as e: full_field_name = "{action_name}.{field_name}".format( action_name=action_name, field_name=e.field_name) return self._gen_bad_req_result(e, full_field_name) else: return Result.ok(data=_combined_args)
def create_flow_template(self, flow_meta_name, name, bind_args, max_run_instance, creator) -> Result: """创建flow_template """ # 获取flow_meta以及检查其存在性 try: flow_meta = self._flow_meta_mgr.get(flow_meta_name) except ObjectNotFoundException: raise BadReq("flow_meta_not_exist", flow_meta=flow_meta_name) # 检查name是否已经存在 if self._flow_tpl_dao.is_name_existed(name): raise BadReq("name_already_exist", name=name) # 检查creator是否存在 creator_user = self._user_dao.query_user_by_id(creator) if not creator_user: raise BadReq("invalid_creator_id", creator=creator) # 校验参数 rs = self._validate_tpl_bind_args(flow_meta, bind_args) if rs.status_code == Result.STATUS_BADREQUEST: return rs bind_args = rs.data created_on = datetime.datetime.now() # 插入吧! flow_template = self._flow_tpl_dao.insert_flow_template( flow_meta_name, name, json.dumps(bind_args), max_run_instance, creator, created_on) log.acolyte.info("New flow template created, {}".format( to_json(flow_template))) # 返回刚创建的View return Result.ok(data=FlowTemplateView.from_flow_template( flow_template, creator_user))
def login(self, email: str, password: str) -> Result: """登录 S1. 通过email和password检索用户 S2. 创建并获取新的token S3. 存储相关用户数据到session_data """ user = self._user_dao.query_user_by_email_and_password( email=email, password=sha1(password) ) if user is None: raise BadReq("no_match") # do upsert new_token = self._gen_new_token(user.id) self._user_token_dao.upsert_token(user.id, new_token) # save user basic info to session data self._user_token_dao.save_session_data( new_token, name=user.name, email=user.email) return Result.ok(data={"id": user.id, "token": new_token})
def on_found(self, context, who): context.finish() return Result.ok(data="是{who}在抢月饼,我要去报告老板!".format(who=who))
def handle_job_action(self, flow_instance_id: int, target_step: str, target_action: str, actor: int, action_args: Dict[str, Any]) -> Result: """处理Job中的Action S1. 检查并获取flow实例 S2. 检查job以及job_action的存在性 S3. 检查执行人是否合法 S4. 检查当前是否可以允许该step及target_action的执行 S5. 合并以及检查相关参数 S6. 回调相关Action逻辑 S7. 返回回调函数的返回值 :param flow_instance_id: flow的标识 :param target_step: 要执行的Step :param target_action: 自定义的动作名称 :param actor: 执行人 :param action_args: 执行该自定义动作所需要的参数 """ if action_args is None: action_args = {} # 检查flow instance的id合法性 flow_instance = self._flow_instance_dao.query_by_instance_id( flow_instance_id) if flow_instance is None: raise BadReq("invalid_flow_instance", flow_instance_id=flow_instance_id) # 检查flow instance的状态 if flow_instance.status != FlowStatus.STATUS_RUNNING: raise BadReq("invalid_status", status=flow_instance.status) # 获取对应的flow template和flow meta flow_template = self._flow_tpl_dao\ .query_flow_template_by_id(flow_instance.flow_template_id) if flow_template is None: raise BadReq("unknown_flow_template", flow_template_id=flow_instance.flow_template_id) try: flow_meta = self._flow_meta_mgr.get(flow_template.flow_meta) except ObjectNotFoundException: raise BadReq("unknown_flow_meta", flow_meta=flow_meta) actor_info = self._user_dao.query_user_by_id(actor) if actor_info is None: raise BadReq("invalid_actor", actor=actor) # 检查当前step以及当前step是否完成 # 检查下一个状态是否是目标状态 handler_mtd, job_def, job_ref = self._check_step( flow_meta, flow_instance, target_step, target_action) # 合并检查参数 request_args - template_bind_args - meta_bind_args rs = self._check_and_combine_action_args(job_def, target_action, action_args, job_ref, flow_template) if rs.status_code == Result.STATUS_BADREQUEST: return rs job_instance = self._job_instance_dao.query_by_instance_id_and_step( instance_id=flow_instance_id, step=target_step) # 如果是trigger事件,需要创建job_instance记录 if target_action == "trigger": job_instance = self._job_instance_dao.insert( flow_instance_id, target_step, actor) self._flow_instance_dao.update_current_step( flow_instance_id, target_step) action_args = rs.data action = self._job_action_dao.insert(job_instance_id=job_instance.id, action=target_action, actor=actor, arguments=action_args, data={}) ctx = MySQLContext(flow_executor=self, db=self._db, flow_instance_id=flow_instance.id, job_instance_id=job_instance.id, job_action_id=action.id, flow_meta=flow_meta, current_step=target_step) rs = handler_mtd(ctx, **action_args) if not isinstance(rs, Result): rs = Result.ok(data=rs) if not rs.is_success(): # 如果返回结果不成功,那么允许重来 self._job_action_dao.delete_by_id(action.id) log.acolyte.info(("Job action executed, " "action_data = {action_data}, " "action_result = {action_result}").format( action_data=to_json(action), action_result=to_json(rs))) return rs
def method(self, context, x, y): context.finish() return Result.ok(data=(x + y))
def on_angry(self, context): print("I'm angry! 你们这样子是不行的!我要终止整个flow!") context.stop() return Result.bad_request("old_man_angry", msg="I'm angry!")
def on_question(self, context, question): if question == "董先森连任好不好啊": context.finish() return Result.ok(data="吼啊") else: return Result.bad_request("old_man_angry", msg="无可奉告")
def on_trigger(self, context): print("old man job on trigger") return Result.ok(data="跑的比谁都快")
def on_minus(self, context, d, e): print("I received args: d={d}, e={e}".format(d=d, e=e)) r = int(context["multiply_result"]) - d - e context.finish() return Result.ok(data=r)
def on_multiply(self, context, c): print("I received args: c={c}".format(c=c)) r = int(context["add_result"]) * c context["multiply_result"] = r return Result.ok(data=r)
def on_trigger(self, context, a, b): print("I received args: a={a}, b={b}".format(a=a, b=b)) r = a + b context["add_result"] = r return Result.ok(data=r)
def logout(self, token: str) -> Result: """退出 S1. 直接从数据库中删除token记录 """ self._user_token_dao.delete_by_token(token) return Result.ok()
def on_trigger(self, context): return Result.ok(data="好吧,我要开始加班还房贷了")
def on_midautumn(self, context, cake_num): context.finish() return Result.ok(data="我抢了{cake_num}个月饼".format(cake_num=cake_num))
def on_trigger(self, context): return Result.ok(data="刚才好像有人抢了月饼")
def start_flow(self, flow_template_id: int, initiator: int, description: str, start_flow_args: Dict[str, Any]) -> Result: """开启一个flow进程,创建flow_instance并执行第一个Job S1. 根据flow_template_id获取flow_template,然后获取flow_meta,如果获取失败,返回错误 S2. 检查并合并参数 S3. 检查max_run_instance S4. 创建一条新的flow_instance记录 S5. 创建context S6. 回调flow meta中on_start方法的逻辑 :param flow_template_id: 使用的flow template :param initiator: 发起人 :param description: 本次flow描述 :param start_flow_args: 执行FlowMeta的on_start方法时所需要的参数 """ if start_flow_args is None: start_flow_args = {} # 检查flow_template_id是否合法 flow_template = self._flow_tpl_dao.query_flow_template_by_id( flow_template_id) if flow_template is None: raise BadReq("invalid_flow_template", flow_template_id=flow_template_id) flow_meta = self._flow_meta_mgr.get(flow_template.flow_meta) if flow_meta is None: raise BadReq("invalid_flow_meta", flow_meta=flow_meta) # 检查发起者 initiator_user = self._user_dao.query_user_by_id(initiator) if initiator_user is None: raise BadReq("invalid_initiator", initiator=initiator) # 检查并合并start_flow_args field_rules = getattr(flow_meta.on_start, "field_rules", []) rs = self._combine_and_check_args("start", field_rules, start_flow_args, flow_meta.start_args) if rs.status_code == Result.STATUS_BADREQUEST: return rs start_flow_args = rs.data # 锁定检查instance数目并创建第一条记录 flow_instance = None if flow_template.max_run_instance > 0: lock_key = "lock_instance_create_{tpl_id}".format( tpl_id=flow_template_id) with self._db.lock(lock_key): current_instance_num = self._flow_instance_dao.\ query_running_instance_num_by_tpl_id(flow_template_id) if current_instance_num >= flow_template.max_run_instance: raise BadReq( reason="too_many_instance", allow_instance_num=flow_template.max_run_instance) flow_instance = self._flow_instance_dao.insert( flow_template_id, initiator, description) else: flow_instance = self._flow_instance_dao.insert( flow_template_id, initiator, description) # 创建Context ctx = MySQLContext(self, self._db, flow_instance.id) # 回调on_start flow_meta.on_start(ctx, **start_flow_args) # 将状态更新到running self._flow_instance_dao.update_status(flow_instance.id, FlowStatus.STATUS_RUNNING) log.acolyte.info("start flow instance {}".format( to_json(flow_instance))) return Result.ok(data=flow_instance)
def on_trigger(self, context): return Result.ok(data="这个世界不是因为你能做什么,而是你该做什么。")