管理服务器的训练有素的猫。
catops的Python项目详细描述
catops
管理服务器的训练有素的猫。
什么是catops
catops是一个非常简单的noops框架,用于部署您自己的chatops bot。
要添加到catops实现中的命令将添加到plugins
文件夹在同一目录中,然后将自动导入并可调用
使用函数名。
为什么是catops
没有。
- 轻松地部署、重写和重新部署faas,无需担心服务器的设置和管理。
- 仅在调用catops时才收费。
制定通用维护程序。
- 在不熟悉低级知识的情况下执行高级动作。
- 防止在执行复杂但例行的任务时出错。
统一文件。
- catops可以作为一个统一的go-to位置来获取帮助,将所有文档合并/汇集到一个位置。
透明度。
- 团队成员可以看到其他人在解决问题时采取的所有行动。有机学习。
- 某些维护任务没有“去找”人。
- 所有人都知道服务器的变化。如果他们在聊天中看到
/meow restart server
,没有人会惊讶服务器已经关闭。 - 传播知识;每个人都变得同样有能力解决问题。
- 过时的帮助消息或文档对每个人来说都更为明显。
上下文感知的建议、建议操作和根据上下文显示帮助。
- 文档/过程/等是有用的,但可能太多,无法阅读,很难找到,不是最新的。
- 在试图找出下一步行动时减少混乱。
减少上下文切换。
- 不需要bash、linux、ssh或vpn来解决大多数服务器问题。
- 不检查服务器日志。
- 易于访问和可读的输出。
控制访问。
- 只提供必要的访问,没有必要的ssh进入生产!
功能
- 完全没有。
- 易于扩展。
- 按调用付费。
- 提供者不可知。
快速启动
- 安装catops
pip install catops
- 运行
meow install [--template] [--target-dir]
- 根据需要调整模板,例如添加松弛的OAuth令牌、调整服务名称等。
- 在模板目录中安装无服务器依赖项
npm install
。 - 运行
serverless deploy
- 配置Slack应用程序(即将斜杠命令/bot端点URL设置为适当的URL)
示例
处理程序
每个lambda函数都需要一个处理程序,它接受参数(event, context)
。在这种情况下,需要立即用200
响应请求,因此下面的处理程序异步调用实际功能,然后返回200
响应。
示例处理程序
importjsonfromsix.moves.urllib.parseimportparse_qsimportrequestsimportboto3fromcatopsimportconvert_dispatchdefrespond(event,context):"""Call handler.main asynchronously and then return instant response."""lambda_client=boto3.client('lambda')response={'statusCode':'200'}# Call actual function asynchronouslylambda_client.invoke(FunctionName='CatOps-dev-dispatcher',InvocationType='Event',Payload=json.dumps(event))returnresponsedefmain(event,context):"""Main lamda function logic, to be called asynchronously."""params=parse_qs(event.get('body'))payload=convert_dispatch(params)username=params.get('user_name',['catops'])[0]# Post to Slack channelresponse_url=params.get('response_url')iftype(response_url)islist:response_url=response_url[0]r=requests.post(response_url,data=json.dumps(payload))ifnotr.ok:print(r)print(r.reason)print(r.text)return
插件
catops围绕插件工作。
- 插件是存储在“plugins/”目录中的python文件。
- catops扫描此目录以查找要导入的有效函数。
- 所有以
_
开头的文件和/或函数都将被忽略。(_
表示它们是私有的,不会添加到catops调度程序中) - 其他函数被添加到catops调度程序中,可以通过
/catops <functionname> [argv]
调用。
- 所有函数都需要参数
(argv, params)
- argv将包含传递给函数的参数,例如对于
/catops role --user t.user
,argv将包含`['role','--user',t.user'] - params将包含parse lambda事件体,它包含slack中的所有信息,例如
{"text": ... , "username": ..., "response_url": ...}
。
- argv将包含传递给函数的参数,例如对于
插件示例
"""example.py - example plugin for ChatOps."""fromcatopsimportcreate_slack_payloaddefping(argv,params):"""Check is working."""text='@{} Meow!'.format(params.get('user_name',['CatOps'])[0]),returncreate_slack_payload(text=text)
无服务器配置
service:CatOpspackage:include:-handler.py-plugins/**custom:pythonRequirements:slim:trueprovider:name:awsstage:${opt:stage, 'dev'}runtime:python3.6profile:serverless# Permissions for the lambda function# If using boto3, ensure correct permissions# have been granted to the lambda functioniamRoleStatements:-Effect:AllowAction:-lambda:InvokeFunction-lambda:InvokeAsyncResource:"*"functions:dispatcher:handler:handler.mainrespond:handler:handler.respondevents:-http:path:pingmethod:postplugins:-serverless-python-requirements
展开并测试
serverless deploy
serverless invoke --function dispatcher --path /path/to/json/data --log
有用功能
# auth.pydefverify_request(event,slack_secret,timeout=True):"""Verify that Lambda event came from Slack"""defget_user_slack(event,oauth,team_id=None,channel_id=None):"""Check whether user exists and is in specified team and channel. Arguments: event - AWS Lambda event oauth - Slack OAUTH token team_id - Slack team_id (workspace, i.e. BBOXX) channel_id - Channel user must be in Returns: False, err_msg True, user_dict with id, name, team_id, channel_id, email """# dispatcher.pydefdispatch(command,params=None,plugin_dir='plugins/'):"""Create Dispatcher object and run parse_command on (command, params)"""# helpers.pydefget_slack_colour(level):"""Return Slack colour value based on log level."""defget_text(params):"""Return event_text from parse_qs event.get('body')."""defcreate_slack_attachment(fallback=None,color=None,pretext=None,author_name=None,author_link=None,author_icon=None,title=None,title_link=None,text=None,fields=None,image_url=None,thumb_url=None,footer=None,footer_icon=None,ts=None):"""Create slack attachment payload See https://api.slack.com/docs/message-attachments for more info. Arguments: fallback - Required plain-text summary of the attachment [color] - Colour of the attachment [pretext] - Optional text that appears above the attachment block [author_name] [author_link] [author_icon] - URL to author icon [title] - Title of the attachment [title_link] [text] - Optional text that appears inside the attachment [fields] - Array of dicts containing more values [image_url] - URL to image attached [thumb_url] - URL to image thumbnail [footer] - Footer message [footer_icon] - URL to footer icon [ts] - timestamp """defcreate_slack_payload(response_type='ephemeral',text="",attachments=None):"""Create a Slack payload formatted correctly."""defconvert_dispatch(params,convert_function=None,plugin_dir='plugins/'):"""Call dispatch and convert the output accordingly into a payload."""# slack_handler.pyclassSlackHandler(logging.Handler):"""Logger slack_handler which posts json log body to lambda_url."""# install.pydefinstall(argv=None):"""Install catops serverless Slack template."""# parser.py classArgumentParserError(Exception):"""Error raised by ArgumentParser"""passclassCatParser(argparse.ArgumentParser):"""Overrides error method to throw an error instead of exiting"""deferror(self,message):raiseArgumentParserError(message)
安装
sudo apt-get install npm sudo npm install -g serverless npm install serverless-python-requirements pip install catops
安装serverless-python-requirements
与serverless.yml
在同一目录中。
限制
- 被动而非主动;需要触发(例如,通过松弛斜杠命令(可以运行每个命令))
- faas的局限性
- 最大大小(AWS Lambda为256MB)
- 执行时间限制(AWS Lambda为5分钟)
- 无状态(建议对状态使用基于云的数据库,如用于aws的dynamodb)
- 松弛区域内没有自动完成。