conductor-worker-python/pyexecplugins/pyexecplugins.py

105 lines
3.3 KiB
Python

import requests
import json
class PyExecPlugins(type):
def __init__(cls, name, bases, attrs):
if not hasattr(cls, "plugins"):
print("Initializing plugins")
cls.plugins = {}
else:
print("Appending a plugin ", cls.name, cls)
cls.plugins[cls.name] = cls
def getPlugins(cls):
return cls.plugins
def get(cls, name):
return cls.plugins.get(name)
class PyExecPlugin(object, metaclass=PyExecPlugins):
def __init__(self, data=None):
self.data = data
class Nop(PyExecPlugin):
name = "Nop"
def __init__(self, data=None):
super().__init__(data)
def execute(self):
return None
class Identity(PyExecPlugin):
name = "Identity"
def __init__(self, data=None):
super().__init__(data)
def execute(self):
return self.data
class Http(PyExecPlugin):
name = "Http"
def __init__(self, data):
super().__init__(data)
self.method = data.get("method") or "get"
self.url = data.get("url")
self.headers = data.get("headers") or {}
self.contenttype = self.headers.get("Content-Type")
self.accept = self.headers.get("Accept")
self.body = data.get("body")
self.expect = data.get("expect")
self.fail = data.get("fail")
def doRequest(self):
#print(self.method, self.url, self.contenttype, self.accept)
if self.contenttype != None and self.contenttype.find("json") != -1:
self.response = requests.request(self.method, self.url, headers=self.headers, json = self.body)
else:
self.response = requests.request(self.method, self.url, headers=self.headers, data = self.body)
return self.response
def computeStatus(self):
if self.fail == False:
return "COMPLETED"
elif self.expect == None:
return "COMPLETED" if self.response.ok else "FAILED"
else:
if type(self.expect) == list:
return "COMPLETED" if (self.response.status_code in self.expect) else "FAILED"
else:
return "COMPLETED" if (self.response.status_code == self.expect) else "FAILED"
def buildOutput(self, status):
hdrs = {}
for k in self.response.headers.keys(): hdrs[k] = self.response.headers[k]
print("Response: {} {}".format(self.response.status_code, self.response.reason))
if hdrs.get("Content-Type") != None and hdrs["Content-Type"].find("json") != -1 or self.accept != None and self.accept.find("json") != -1:
outbody = self.response.json()
else:
outbody = self.response.text
return {
'status': status,
'output': {
"body" : outbody,
"headers" : hdrs,
"status" : self.response.status_code,
"reason" : self.response.reason},
'logs': ['one', 'two']}
def execute(self):
try:
self.doRequest()
status = self.computeStatus()
return self.buildOutput(status)
except Exception as err:
return {
"status" : "FAILED",
"output" : { "message" : "Internal error: {}".format(err)}, "logs" : ["one","two"]
}