StackStorm分析(七)Sensor说明

StackStorm介绍

       StackStorm是一个强大的自动化平台,结合DevOpsChatOps,提供可扩展、灵活和健壮的工具链用于应用、服务和工作流的自动化能力。

 


 

Sensor

       Sensor是一系列的感应器用于接受或者监测事件,当事件发生的时候,Sensor将会通知Trigger提交事件到StackStorm。

       StackStorm定义了Sensor的接口,第三方系统可以方便的和StackStorm对接。

我们现在创建一个Sensor, 首先需要实现Python脚本sample_sensor.py:

from st2reactor.sensor.base import Sensor
 
class SampleSensor(Sensor):
    """
    * self.sensor_service
        - provides utilities like
            - get_logger() - returns logger instance specific to this sensor.
            - dispatch() for dispatching triggers into the system.
    * self._config
        - contains parsed configuration that was specified as
          config.yaml in the pack.
    """
 
    def setup(self):
        # Setup stuff goes here. For example, you might establish connections
        # to external system once and reuse it. This is called only once by the system.
        pass
 
    def run(self):
        # This is where the crux of the sensor work goes.
        # This is called once by the system.
        # (If you want to sleep for regular intervals and keep
        # interacting with your external system, you'd inherit from PollingSensor.)
        # For example, let's consider a simple flask app. You'd run the flask app here.
        # You can dispatch triggers using sensor_service like so:
        # self.sensor_service(trigger, payload, trace_tag)
        #   # You can refer to the trigger as dict
        #   # { "name": ${trigger_name}, "pack": ${trigger_pack} }
        #   # or just simply by reference as string.
        #   # i.e. dispatch(${trigger_pack}.${trigger_name}, payload)
        #   # E.g.: dispatch('examples.foo_sensor', {'k1': 'stuff', 'k2': 'foo'})
        #   # trace_tag is a tag you would like to associate with the dispatched TriggerInstance
        #   # Typically the trace_tag is unique and a reference to an external event.
        pass
 
    def cleanup(self):
        # This is called when the st2 system goes down. You can perform cleanup operations like
        # closing the connections to external system here.
        pass
 
    def add_trigger(self, trigger):
        # This method is called when trigger is created
        pass
 
    def update_trigger(self, trigger):
        # This method is called when trigger is updated
        pass
 
    def remove_trigger(self, trigger):
        # This method is called when trigger is deleted

        pass

Python脚本实现了一个类SampleSensor继承了Sensor,并且重写了Sensor中定义的方法。

 

然后定义Sensor的规格文件sample_sensor.yaml:

---

  class_name: "SampleSensor"

  entry_point: "sample_sensor.py"

  description: "Sample sensor that emits triggers."

  trigger_types:

    -

      name: "event"

      description: "An example trigger."

      payload_schema:

        type: "object"

        properties:

          executed_at:

            type: "string"

            format: "date-time"

            default: "2014-07-30 05:04:24.578325"

  • class_name:Python脚本实现的类名称
  • entry_point:   指定Python脚本
  • trigger_types:  Sensor中定义的Trigger类型,需要指定Trigger的name和payload_schema。

 

 

最后将Python脚本和Sensor规格文件放在Pack的目录下,比如Pack examples放在/opt/stackstorm/packs/examples/sensors/目录下。然后Reload,

$ st2ctl reload --register-all
或者
$ st2ctl reload --register-sensors --register-fail-on-failure --verbose

备注:安装Pack的时候,如果Pack已经包含了Sensor,就会加载运行。

 

每个Sensor是以独立进程运行的,StackStorm中的组件st2sensorcontainer 负责管理Sensor进程。

 

Sensor注册成功后,可以查询:

$ st2 sensor list

+------------------------------+----------+-----------------------------------------------------+---------+

| ref                          | pack     | description                                         | enabled |

+------------------------------+----------+-----------------------------------------------------+---------+

| linux.FileWatchSensor        | linux    | Sensor which monitors files for new lines           | True    |

| examples.EchoFlaskSensor     | examples | Simple echo flask app sensor that echoes its input. | True    |

| examples.FibonacciSensor     | examples | Simple polling sensor that emits fibonacci number.  | True    |

| examples.SamplePollingSensor | examples | Simple polling sensor that emits triggers.          | True    |

| examples.SampleSensor        | examples | Sample sensor that emits triggers.                  | True    |

| docker.DockerSensor          | docker   | Docker sensor                                       | True    |

+------------------------------+----------+-----------------------------------------------------+---------+


Trigger

       Trigger代表事件,一般事件是由外部系统产生,比如监控告警,JIRA问题更新等等,另外也有通用的事件触发器,比如定时器或者WebHook。

       在StackStorm系统中,Trigger只是String类型的对象,有StromStack内置的,也有由Sensor注册的,。可以通过通过st2trigger list查询:

$ st2 trigger list

+--------------------------------------+----------+--------------------------------------------------------------------------------------------+
| ref                                  | pack     | description                                                                                |
+--------------------------------------+----------+--------------------------------------------------------------------------------------------+
| core.st2.IntervalTimer               | core     | Triggers on specified intervals. e.g. every 30s, 1week etc.                                |
| 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.CronTimer                   | core     | Triggers whenever current time matches the specified time constaints like a UNIX cron      |
|                                      |          | scheduler.                                                                                 |
| core.st2.generic.actiontrigger       | core     | Trigger encapsulating the completion of an action execution.                               |
| core.st2.generic.notifytrigger       | core     | Notification trigger.                                                                      |
| core.st2.action.file_writen          | core     | Trigger encapsulating action file being written on disk.                                   |
| core.st2.generic.inquiry             | core     | Trigger indicating a new "inquiry" has entered "pending" status                            |
| core.st2.key_value_pair.create       | core     | Trigger encapsulating datastore item creation.                                             |
| core.st2.key_value_pair.update       | core     | Trigger encapsulating datastore set action.                                                |
| core.st2.key_value_pair.value_change | core     | Trigger encapsulating a change of datastore item value.                                    |
| core.st2.key_value_pair.delete       | core     | Trigger encapsulating datastore item deletion.                                             |
| core.st2.sensor.process_spawn        | core     | Trigger indicating sensor process is started up.                                           |
| core.st2.sensor.process_exit         | core     | Trigger indicating sensor process is stopped.                                              |
| linux.file_watch.line                | linux    | Trigger which indicates a new line has been detected                                       |
| core.st2.webhook                     | core     | Trigger type for registering webhooks that can consume arbitrary payload.                  |
| examples.sample_trigger              | examples | Sample trigger                                                                             |
| examples.echoflasksensor             | examples | Echo flask sensor.                                                                         |
| examples.fibonacci                   | examples | A fibonacci trigger.                                                                       |
| examples.polling_event               | examples | An example trigger.                                                                        |
| examples.event                       | examples | An example trigger.                                                                        |
| sensu.event_handler                  | sensu    | Trigger type for sensu event handler.                                                      |
| docker.container_tracker.started     | docker   | Trigger which indicates that a container has been started                                  |
| docker.container_tracker.stopped     | docker   | Trigger which indicates that a container has been stopped                                  |
+--------------------------------------+----------+--------------------------------------------------------------------------------------------+

 

对于内置的Trigger类型主要是由StackStorm本身进行触发,比如core.st2.CronTimer是一个定时器Trigger,这是由StackStorm本身去安装Cron触发的。如果是Sensor注册的Trigger,就需要在Sensor根据业务场景去触发,比如监测docker容器停止了,然后去触发docker.container_tracker.stopped。自然触发就需要在Sensor的Python脚本去实现:

trigger ='pack.name'
payload = {
    'executed_at': '2014-08-01T00:00:00.000000Z'
}
trace_tag = uuid.uuid4().hex
 
self.sensor_service.dispatch(trigger=trigger, payload=payload, trace_tag=trace_tag)

 

当Trigger触发后,会生成TriggerInstace,可以通过命令查询到:

$ st2 trigger-instance list -n 5

+--------------------------+-------------------------------------------+-------------------------------+-----------+

| id                       | trigger                                   | occurrence_time               | status    |

+--------------------------+-------------------------------------------+-------------------------------+-----------+

| 5afd32e02b25560037bfef8b | core.0f7df637-70eb-46f9-9391-f67bd965ba2f | Thu, 17 May 2018 07:44:32 UTC | processed |

| 5afd32e52b25560037bfef8d | core.0f7df637-70eb-46f9-9391-f67bd965ba2f | Thu, 17 May 2018 07:44:37 UTC | processed |

| 5afd32ea2b25560037bfef8f | core.0f7df637-70eb-46f9-9391-f67bd965ba2f | Thu, 17 May 2018 07:44:42 UTC | processed |

| 5afd32ef2b25560037bfef91 | core.0f7df637-70eb-46f9-9391-f67bd965ba2f | Thu, 17 May 2018 07:44:47 UTC | processed |

| 5afd32f42b25560037bfef93 | core.0f7df637-70eb-46f9-9391-f67bd965ba2f | Thu, 17 May 2018 07:44:52 UTC | processed |

+--------------------------+-------------------------------------------+-------------------------------+-----------+

+------------------------------------------------------------------------------------------------------------------+

| Note: Only first 5 triggerinstances are displayed. Use -n/--last flag for more results.                          |

+------------------------------------------------------------------------------------------------------------------+


 

也可以通过类型和范围检索:

$ st2 trigger-instance list --trigger="core.f9e09284-b2b1-4127-aedd-dcde7a752819" -timestamp_gt=2015-06-01T12:00:00Z -timestamp_lt=2015-06-02T12:00:00Z

 

 

可以查询某个Trigger Instance的详情:

$ st2 trigger-instance get 5afd32e02b25560037bfef8b

+-----------------+---------------------------------------------------------+

| Property        | Value                                                   |

+-----------------+---------------------------------------------------------+

| id              | 5afd32e02b25560037bfef8b                                |

| trigger         | core.0f7df637-70eb-46f9-9391-f67bd965ba2f               |

| occurrence_time | 2018-05-17T07:44:32.508000Z                             |

| payload         | {                                                       |

|                 |     "executed_at": "2018-05-17 07:44:32.505842+00:00",  |

|                 |     "schedule": null                                    |

|                 | }                                                       |

| status          | processed                                               |

+-----------------+---------------------------------------------------------+

 

可以去重新触发这个TriggerInstance:

$ st2 trigger-instance re-emit 5afd32e02b25560037bfef8b

Trigger instance 5afd32e02b25560037bfef8b succesfully re-sent.

 

参考

  • https://github.com/StackStorm/st2docs/blob/master/docs/source/sensors.rst

作者简介

吴龙辉,现任网宿科技云计算架构师,致力于云计算PaaS的研究和实践,《Kubernetes实战》作者,活跃于CloudFoundry,Docker,Kubernetes等开源社区,贡献代码和撰写技术文档。 
邮箱:wlh6666@qq.com

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wlhdo71920145/article/details/80352264
个人分类: StackStorm
上一篇StackStorm分析(六)Pack说明
下一篇StackStorm分析(八)Rule说明
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭