# Invoke with
# index.py {
# "executionId":"f64900d3-2a5a-4646-b0e1-bbeeb6c79b07",
# "sessionId": "1a289c47-166a-4d16-86ec-c72eacb9df42",
# "returnType": "Properties",
# "vcoUrl": "http://localhost:8280/vco"
# }
import importlib
import json
import os
import sys
import truststore
import urllib.parse
import urllib.request
# Add the environment directory to sys.path for module resolution
sys.path.append(
"/var/run/vco-polyglot/environment/environment-bundle/lib"
)
# Replace the python trust store with the system one
truststore.inject_into_ssl()
VCO_ENTRYPOINT = os.getenv("VCO_ENTRYPOINT")
moduleName = "handler"
functionName = "handler"
# change current dir to the one of the function so relative
# file loads will be handled properly
os.chdir("./function/")
if VCO_ENTRYPOINT is not None:
parts = VCO_ENTRYPOINT.split(".")
if len(parts) != 2:
print(
("Function entrypoint must be specified in the "
"following format: scriptFileName.functionName, "
"e.g. index.handler"),
file=sys.stderr
)
exit(1)
moduleName = parts[0]
functionName = parts[1]
try:
loadedModule = importlib.import_module(
"function." + moduleName
)
except ModuleNotFoundError:
print("Cannot find module " + moduleName, file=sys.stderr)
raise
if not hasattr(loadedModule, functionName):
print(
"Cannot find handler function " + functionName + \
" in module " + moduleName, file=sys.stderr
)
exit(1)
handler = getattr(loadedModule, functionName)
if os.getenv("DEBUG_PORT"):
import debugpy
debugpy.listen(("0.0.0.0", int(os.getenv("DEBUG_PORT"))))
print("Waiting for debugger attach on " + \
os.getenv("DEBUG_PORT"))
debugpy.wait_for_client()
debugpy.breakpoint()
print("Break on this line")
def removeCircularRefs(obj, _refs = None, _elementDetail = None):
if _refs is None:
_refs = set()
res = obj
if isinstance(obj, dict) or isinstance(obj, list):
objId = id(obj)
if objId in _refs:
# circular reference, remove it
print(
"Detected circular reference in " + \
_elementDetail + ", from returned result, " + \
"breaking cycle in order to serialize result."
)
return None
_refs.add(objId)
if isinstance(obj, list):
res = []
for index, el in enumerate(obj):
res.append(
removeCircularRefs(
el,
_refs,
"array element with index [" + \
str(index) + "]"
)
)
else:
res = {}
for key in obj:
res[key] = removeCircularRefs(
obj[key],
_refs,
"object element with key [" + key + "]"
)
_refs.remove(objId)
return res
def getTokenFactory(vcoUrl, sessionId):
def getToken():
url = vcoUrl + \
"/internal/session-access-token?sessionId=" + \
sessionId
headers = {
"client-id": os.environ.get("VCO_FID"),
"client-type": "polyglot",
}
data = urllib.parse.urlencode({}).encode("utf-8")
req = urllib.request.Request(url, data, headers)
res = urllib.request.urlopen(req)
charset = res.info().get_content_charset()
if not charset:
charset = "utf-8"
content = json.loads(res.read().decode(charset))
return content
return getToken
if __name__ == "__main__":
context = json.loads(sys.argv[1])
inputs_file = open(
os.getenv("INPUTS_FILE"), "r", encoding="utf-8"
)
inputs = json.loads(inputs_file.read())
sessionId = context["sessionId"]
vcoUrl = context["vcoUrl"]
context["getToken"] = getTokenFactory(vcoUrl, sessionId)
del context["sessionId"]
try:
ret = handler(context, inputs)
compactRet = ""
if ret is not None:
ret = removeCircularRefs(ret)
compactRet = json.dumps(ret, separators=(",", ":"))
f = open(
"/var/run/vco-polyglot/outputs/output.json",
"w+"
)
f.write(compactRet)
f.close()
except Exception as e:
errorToWrite = {
"error": str(e)
}
f = open(
"/var/run/vco-polyglot/outputs/error.json",
"w+"
)
f.write(json.dumps(errorToWrite, separators=(",", ":")))
f.close()
raise
|