StackStorm使用了规则和工作流来捕获可操作的模式来做自动化。
规则对trigger触发器到action(或工作流)做了映射。应用匹配的criteria并且
映射trigger payloads到动作的输入。
规则定义在YAML中。规则定义结构,一些碧血的和可选的元素如下所示:
---
name: "rule_name" # required
pack: "examples" # optional
description: "Rule description." # optional
enabled: true # required
trigger: # required
type: "trigger_type_ref"
criteria: # optional
trigger.payload_parameter_name1:
type: "regex"
pattern : "^value$"
trigger.payload_parameter_name2:
type: "iequals"
pattern : "watchevent"
action: # required
ref: "action_ref"
parameters: # optional
foo: "bar"
baz: "{{ trigger.payload_parameter_1 }}"
rule的主要格式如下:
name: 规则名称
pack: 规则的属于方,如果没有指定pack则为default
description: 规则的描述
enabled: 规则是否开启(true或者false)
trigger:emitted from sensors to monitor, and optionally parameters associated with that trigger.
criteria:可选择的集合,包含
一个trigger的payload的属性
criteria比较的类型
pattern: to match against.
action:当一个规则被满足时,执行的动作,包含:
ref:动作或工作流的名称
parameters: 执行动作的参数(可选)
rule中的trigger指定了哪一个即将到来的事件会被检测并被用于规则的匹配。
查看系统中配置的所有触发器可以通过命令:
st2 trigger list
输出结果:
+----------------------------------+----------+----------------------------------+
| ref | pack | description |
+----------------------------------+----------+----------------------------------+
| core.st2.CronTimer | core | Triggers whenever current time |
| | | matches the specified time |
| | | constaints like a UNIX cron |
| | | scheduler. |
| core.st2.DateTimer | core | Triggers exactly once when the |
| | | current time matches the |
| | | specified time. e.g. |
| | | timezone:UTC date:2014-12-31 |
| | | 23:59:59. |
| core.st2.IntervalTimer | core | Triggers on specified intervals. |
| | | e.g. every 30s, 1week etc. |
| core.st2.action.file_writen | core | Trigger encapsulating action |
| | | file being written on disk. |
| core.st2.generic.actiontrigger | core | Trigger encapsulating the |
| | | completion of an action |
| | | execution. |
| core.st2.generic.inquiry | core | Trigger indicating a new |
| | | "inquiry" has entered "pending" |
| | | status |
| core.st2.generic.notifytrigger | core | Notification trigger. |
| core.st2.key_value_pair.create | core | Trigger encapsulating datastore |
| | | item creation. |
| core.st2.key_value_pair.delete | core | Trigger encapsulating datastore |
| | | item deletion. |
| core.st2.key_value_pair.update | core | Trigger encapsulating datastore |
| | | set action. |
| core.st2.key_value_pair.value_ch | core | Trigger encapsulating a change |
| ange | | of datastore item value. |
| core.st2.sensor.process_exit | core | Trigger indicating sensor |
| | | process is stopped. |
| core.st2.sensor.process_spawn | core | Trigger indicating sensor |
| | | process is started up. |
| core.st2.webhook | core | Trigger type for registering |
| | | webhooks that can consume |
| | | arbitrary payload. |
| default.event1 | default | An example trigger. |
| examples.echoflasksensor | examples | Echo flask sensor. |
| examples.event | examples | An example trigger. |
| examples.fibonacci | examples | A fibonacci trigger. |
| examples.polling_event | examples | An example trigger. |
| examples.sample_trigger | examples | Sample trigger |
| linux.file_watch.line | linux | Trigger which indicates a new |
| | | line has been detected |
+----------------------------------+----------+----------------------------------+
Rule中的criteria是需要匹配的,逻辑操作符为AND。
Rule中的Criteria被表示成如下形式:
# more variables
criteria:
trigger.payload_parameter_name1:
type: "regex"
pattern : "^value$"
trigger.payload_parameter_name2:
type: "iequals"
pattern : "watchevent"
注意:你可以通过创建多个独立的规则(每个criteria表达式)实现逻辑操作符OR的行为
type: 制定了准则中比较操作符。类型有:
equals,nequals,lessthan,greaterthan,matchwildcard,regex等
pattern: 指定了模式
支持的比较操作符:
Operator Description
equals Values are equal (for values of arbitrary type).
nequals Values are not equal (for values of arbitrary type).
lessthan Trigger value is less than the provided value.
greaterthan Trigger value is greater than the provided value.
matchwildcard Trigger value matches the provided wildcard-like string. This operator provides support for Unix shell-style wildcards which means you can use characters such as * and ?. This operator is preferred over regex for simple string matches.
regex Trigger value matches the provided regular expression pattern. This operator behaves like re.search('pattern', trigger_value).
iregex Trigger value matches the provided regular expression pattern case insensitively. This operator behaves like re.search('pattern', trigger_value, re.IGNORECASE).
matchregex Trigger value matches the provided regular expression pattern. This operator is deprecated in favor of regex and iregex
iequals String trigger value equals the provided value case insensitively.
contains Trigger value contains the provided value. Keep in mind that the trigger value can be either a string or an array (list).
ncontains Trigger value does not contain the provided value. Keep in mind that the trigger value can be either a string or an array (list).
icontains String trigger value contains the provided value case insensitively.
incontains String trigger value does not contain the provided string value case insensitively.
startswith Beginning of the string trigger value matches the provided string value.
istartswith Beginning of the string trigger value matches the provided string value case insensitively.
endswith End of the string trigger value matches the provided string value.
iendswith End of the string trigger value matches the provided string value case insensitively.
timediff_lt Time difference between trigger value and current time is less than the provided value.
timediff_gt Time difference between trigger value and current time is greater than the provided value.
exists Key exists in payload.
nexists Key doesn’t exist in payload.
inside Trigger payload is inside provided value. (e.g. testing if “trigger.payload in provided_value”). Reverse of contains. (where contains would test for “trigger.payload contains provided_value”).
ninside Trigger payload is not inside provided value. (e.g. testing if “trigger.payload not in provided_value”). Reverse of ncontains (where contains would test for “trigger.payload does not contain provided_value”).
search Search an array (list) in the trigger payload that matches child criteria. See the Advanced Comparison section for more information and examples.
高级的比较:
search操作符可以用于更复杂的操作。它有一个额外的condition参数,
可以嵌套的criteria应用。
例子如下:
---
criteria:
trigger.issue_fields:
type: "search"
# Controls whether all items in the trigger payload must match the child criteria,
# or if any single item matching the child criteria is sufficient
condition: any # <- *At least one* item must match all child patterns
pattern:
# Here our context is each item of the list
# All of these patterns must match the item for the item to be considered a match
# These are simply other operators applied to each item of the list
item.field_name:
type: "equals"
pattern: "Status"
item.to_value:
type: "equals"
pattern: "Approved"
省略search操作符的用法
当成功匹配到一个触发器和一个准则时执行的动作或者工作流。
最低限度,一个规则应该指定要执行的动作。一个规则也可以指定动作执行需要的参数。
action: # required
ref: "action_ref"
parameters: # optional
foo: "bar"
baz: 1
变量篡改
有时候,当一个规则匹配的时候,需要解析一个触发器的上下文中动作。规则引擎
可以借助Jinja模板语法来串该变量
action:
ref: "action_ref"
parameters:
foo: "bar"
baz: "{{ trigger.payload_parameter_1 }}"
使用use_none来过去确保null/None值被序列化了
action:
ref: "action_ref"
parameters:
foo: "bar"
baz: "{{ trigger.payload_parameter_1 | use_none }}"
通过命令
st2 rule create ${PATH_TO_RULE}
来部署规则
例如:
st2 rule create /usr/share/doc/st2/examples/rules/sample_rule_with_webhook.yaml
加载所有规则,使用:
st2ctl reload --register-rules
如果一个同名的规则已经存在,上述命令会返回错误
为了更新规则,编辑规则定义文件并运行命令:
st2 rule update
例子:
st2 rule update examples.sample_rule_with_webhook /usr/share/doc/st2/examples/rules/sample_rule_with_webhook.yaml
注意:
最佳实践是编辑原始的规则文件,获取规则通过:
st2 rule get
st2 rule list
st2 rule get examples.sample_rule_with_webhook
卸载一个规则:
st2 rule delete ${RULE_NAME_OR_ID}
例如:
st2 rule delete examples.sample_rule_with_webhook
自定义规则被放在:
/opt/stackstorm/packs/
目录。
例如:
/opt/stackstorm/packs/examples/rules
为了使得测试规则更简单,我们提供了一个
st2-rule-testr
tool which can evaluate rules against trigger instances without running any of the StackStorm components
这个工具通过将一个路径存储到文件中,该文件包含了规则定义和触发示例的定义
st2-rule-tester --rule=${RULE_FILE} --trigger-instance=${TRIGGER_INSTANCE_DEFINITION} --config-file=/etc/st2/st2.conf
echo $?
文件需要同时包含YAML或JSON格式的定义。为了规则,你可以使用你准备部署的相同文件。
定义的文件需要包含如下的keys:
trigger: 完全参考自trigger,例如: core.st2.IntervalTimer
payload: Trigger的payload。这个payload本身。为了弄明白trigger的结构,
你可以参考sensor元数据文件中trigger_types部分或pack的README。
如果trigger instance匹配,=== RULE MATCHES ===将会被打印,工具将会返回
状态码0.
如果trigger instance不匹配,=== RULE MATCHES ===将不会被打印,工具将会返回
状态码1.
样例如下:
my_rule.yaml:
---
name: "relayed_matched_irc_message"
pack: "irc"
description: "Relay IRC message to Slack if the message contains word StackStorm"
enabled: true
trigger:
type: "irc.pubmsg"
parameters: {}
criteria:
trigger.message:
type: "icontains"
pattern: "StackStorm"
action:
ref: "slack.post_message"
parameters:
message: "{{ trigger.source.nick }} on {{ trigger.channel }}: {{ trigger.message }}"
channel: "#irc-relay"
trigger_instance_1.yaml:
---
trigger: "irc.pubmsg"
payload:
source:
nick: "Kami_"
host: "gateway/web/irccloud.com/x-uvv"
channel: "#stackstorm"
timestamp: 1419166748,
message: "stackstorm is cool!"
trigger_instance_2.yaml:
---
trigger: "irc.pubmsg"
payload:
source:
nick: "Kami_"
host: "gateway/web/irccloud.com/x-uvv"
channel: "#stackstorm"
timestamp: 1419166748,
message: "blah blah"
st2-rule-tester --rule=./my_rule.yaml --trigger-instance=./trigger_instance_1.yaml
echo $?
Output:
2015-12-11 14:35:03,249 INFO [-] Connecting to database "st2" @ "0.0.0.0:27017" as user "None".
2015-12-11 14:35:03,318 INFO [-] Validating rule irc.relayed_matched_irc_message for pubmsg.
2015-12-11 14:35:03,331 INFO [-] 1 rule(s) found to enforce for pubmsg.
2015-12-11 14:35:03,333 INFO [-] === RULE MATCHES ===
0
st2-rule-tester --rule=./my_rule.yaml --trigger-instance=./trigger_instance_2.yaml
echo $?
Output:
2015-12-11 14:35:57,380 INFO [-] Connecting to database "st2" @ "0.0.0.0:27017" as user "None".
2015-12-11 14:35:57,444 INFO [-] Validating rule irc.relayed_matched_irc_message for pubmsg.
2015-12-11 14:35:57,459 INFO [-] Validation for rule irc.relayed_matched_irc_message failed on -
key: trigger.message
pattern: StackStorm
type: icontains
payload: blah blah
2015-12-11 14:35:57,461 INFO [-] 0 rule(s) found to enforce for pubmsg.
2015-12-11 14:35:57,462 INFO [-] === RULE DOES NOT MATCH ===
1
st2-rule-tester --rule-ref=my_pack.fire_on_execution --trigger-instance-id=566b4be632ed352a09cd347d --config-file=/etc/st2/st2.conf
echo $?
如果你正在调试,并且希望可以看到发送给StackStorm触发器实例的列表,可以执行如下命令:
st2 trigger-instance list
输出结果:
+--------------------------+---------------------------------+-------------------------------+-----------+
| id | trigger | occurrence_time | status |
+--------------------------+---------------------------------+-------------------------------+-----------+
| 5c3859e89dc6d67c76ad700c | core.e9534e98-2d1c-4087-97a8-ce | Fri, 11 Jan 2019 16:55:04 UTC | processed |
| | 856bf87380 | | |
| 5c3859ed9dc6d67c76ad700f | core.e9534e98-2d1c-4087-97a8-ce | Fri, 11 Jan 2019 16:55:09 UTC | processed |
你可以
st2 trigger-instance list --trigger=core.e9534e98-2d1c-4087-97a8-ce856bf87380
输出结果:
+--------------------------+---------------------------------+-------------------------------+-----------+
| id | trigger | occurrence_time | status |
+--------------------------+---------------------------------+-------------------------------+-----------+
| 5c385ad89dc6d67c76ad709b | core.e9534e98-2d1c-4087-97a8-ce | Fri, 11 Jan 2019 16:59:04 UTC | processed |
| | 856bf87380 | | |
| 5c385add9dc6d67c76ad709e | core.e9534e98-2d1c-4087-97a8-ce | Fri, 11 Jan 2019 16:59:09 UTC | processed |
你可以通过timestamp_gt和timestamp_lt获取指定时间范围触发器实例
st2 trigger-instance list --trigger="core.e9534e98-2d1c-4087-97a8-ce856bf87380" -timestamp_gt=2019-01-11T12:00:00Z -timestamp_lt=2019-01-11T15:00:00Z
查看trigger-instance
st2 trigger-instance get 5c385ad89dc6d67c76ad709b
输出结果:
+-----------------+---------------------------------------------------------+
| Property | Value |
+-----------------+---------------------------------------------------------+
| id | 5c385ad89dc6d67c76ad709b |
| trigger | core.e9534e98-2d1c-4087-97a8-ce856bf87380 |
| occurrence_time | 2019-01-11T16:59:04.000000Z |
| payload | { |
| | "executed_at": "2019-01-11 08:59:04.348620+00:00", |
| | "schedule": null |
| | } |
| status | processed |
调试一个规则的时候,重发一个trigger instance到StackStorm。你可以使用re-emit命令
st2 trigger-instance re-emit 5c385ad89dc6d67c76ad709b
输出结果:
Trigger instance 5c385ad89dc6d67c76ad709b succesfully re-sent.
Timers允许运行一个特别的动作,该动作可以在一个给定的时间间隔重发,或者在一个指定的
日期和时间重复执行。你可以认为它们是定时任务,但是具备额外的灵活性。
例如在给定的日期和时间,值运行一次动作。
目前,我们支持如下的 timer trigger类型:
core.st2.IntervalTimer: 在指定时间间隔内运行一个动作(例如每隔30秒,每隔24小时,每个星期等)
core.st2.DateTimer: 在给丁的日期和时间运行动作
core.st2.CronTimer: 当当前时间满足了已经定义的UNIX cron格式的时间限制时运行动作。
Timers被作为triggers来实现,这意味着你可以在规则内部使用它们。
在下面的部分中,你可以找到如何在规则定义中使用timers。
1) core.st2.IntervalTimer
可选择的参数: unit, delta
unite的值有: seconds, minutes, hours, days, weeks
每隔30秒运行
---
...
trigger:
type: "core.st2.IntervalTimer"
parameters:
unit: "seconds"
delta: 30
action:
...
每隔24小时运行
---
...
trigger:
type: "core.st2.IntervalTimer"
parameters:
unit: "hours"
delta: 24
action:
...
2) core.st2.DateTimer
可选择的参数有: timezone, date
在一个指定日期运行action
---
...
trigger:
type: "core.st2.DateTimer"
parameters:
timezone: "UTC"
date: "2014-12-31 23:59:59"
action:
...
3) core.st2.CronTimer
支持类似cron的表达式。
查看完全支持的表达式:
请参见:
https://apscheduler.readthedocs.io/en/3.0/modules/triggers/cron.html#api
每天运行
---
...
trigger:
type: "core.st2.CronTimer"
parameters:
timezone: "UTC"
day_of_week: "*"
hour: 0
minute: 0
second: 0
action:
...
注意:
*被认为如果没有值提供,表示每隔一定时间都会触发
等同于下面的:
---
...
trigger:
type: "core.st2.CronTimer"
parameters:
timezone: "UTC"
hour: 0
minute: 0
second: 0
action:
...
每小时运行:
---
...
trigger:
type: "core.st2.CronTimer"
parameters:
timezone: "UTC"
hour: "*"
minute: 0
second: 0
action:
...
以上内容翻译自:
https://docs.stackstorm.com/rules.html