2017-12-25 17:23:09 +01:00
|
|
|
import logging
|
|
|
|
|
|
|
|
from ..config import Config
|
|
|
|
from ..message.request import Request
|
2018-01-05 23:20:39 +01:00
|
|
|
from ..message.response import Response
|
2017-12-25 17:23:09 +01:00
|
|
|
|
|
|
|
class Procedure(object):
|
|
|
|
""" Procedure class. A procedure is a pre-configured list of requests """
|
|
|
|
|
2018-01-06 00:21:25 +01:00
|
|
|
def __init__(self, name, async, requests, backend=None):
|
2017-12-25 17:23:09 +01:00
|
|
|
"""
|
|
|
|
Params:
|
|
|
|
name -- Procedure name
|
2018-01-06 00:21:25 +01:00
|
|
|
async -- Whether the actions in the procedure are supposed to
|
|
|
|
be executed sequentially or in parallel (True or False)
|
2017-12-25 17:23:09 +01:00
|
|
|
requests -- List of platylist.message.request.Request objects
|
|
|
|
"""
|
|
|
|
|
|
|
|
self.name = name
|
2018-01-06 00:21:25 +01:00
|
|
|
self.async = async
|
2017-12-25 17:23:09 +01:00
|
|
|
self.requests = requests
|
|
|
|
self.backend = backend
|
|
|
|
|
|
|
|
for req in requests:
|
|
|
|
req.backend = self.backend
|
|
|
|
|
|
|
|
@classmethod
|
2018-01-06 00:21:25 +01:00
|
|
|
def build(cls, name, async, requests, backend=None, id=None, **kwargs):
|
2017-12-25 17:23:09 +01:00
|
|
|
reqs = []
|
|
|
|
for request_config in requests:
|
|
|
|
request_config['origin'] = Config.get('device_id')
|
|
|
|
request_config['id'] = id
|
|
|
|
if 'target' not in request_config:
|
|
|
|
request_config['target'] = request_config['origin']
|
|
|
|
|
|
|
|
request = Request.build(request_config)
|
|
|
|
reqs.append(request)
|
|
|
|
|
2018-01-06 00:21:25 +01:00
|
|
|
return cls(name=name, async=async, requests=reqs, backend=backend, **kwargs)
|
2017-12-25 17:23:09 +01:00
|
|
|
|
|
|
|
def execute(self, n_tries=1):
|
|
|
|
"""
|
|
|
|
Execute the requests in the procedure
|
|
|
|
Params:
|
|
|
|
n_tries -- Number of tries in case of failure before raising a RuntimeError
|
|
|
|
"""
|
|
|
|
|
|
|
|
logging.info('Executing request {}'.format(self.name))
|
2018-01-05 23:20:39 +01:00
|
|
|
context = {}
|
|
|
|
response = Response()
|
|
|
|
|
2017-12-25 17:23:09 +01:00
|
|
|
for request in self.requests:
|
2018-01-06 00:21:25 +01:00
|
|
|
if self.async:
|
|
|
|
request.execute(n_tries, async=True, **context)
|
|
|
|
else:
|
|
|
|
response = request.execute(n_tries, async=False, **context)
|
2018-01-07 23:31:19 +01:00
|
|
|
|
|
|
|
if isinstance(response.output, dict):
|
|
|
|
for (k,v) in response.output.items():
|
|
|
|
context[k] = v
|
2018-01-06 00:21:25 +01:00
|
|
|
|
|
|
|
context['output'] = response.output
|
|
|
|
context['errors'] = response.errors
|
2018-01-05 23:20:39 +01:00
|
|
|
|
|
|
|
return response
|
2017-12-25 17:23:09 +01:00
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|
|
|
|
|