Skip to content

Instantly share code, notes, and snippets.

@lidaobing
Created January 22, 2019 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lidaobing/b4020357f3bcb2b9cdaebacafadc7bf4 to your computer and use it in GitHub Desktop.
Save lidaobing/b4020357f3bcb2b9cdaebacafadc7bf4 to your computer and use it in GitHub Desktop.
#coding=utf-8
import json, os, sys, uuid, datetime, subprocess, traceback
def runCmd(cmd):
return [str(x) for x in subprocess.check_output(cmd, shell=True).splitlines()]
def getServerId():
try:
return open('/tmp/serverId').read()
except IOError:
serverId = str(uuid.uuid4())+" "+str(datetime.datetime.now())
ofile = open('/tmp/serverId', 'w')
ofile.write(serverId)
ofile.close()
return serverId
def handler(event, context):
try:
return handler2(event, context)
except Exception:
exstr = traceback.format_exc()
result = {
'statusCode': 500,
'headers': {'Content-Type': 'application/json; charset=utf-8'},
'body': json.dumps({
"exception": exstr.splitlines(),
})}
return result
def handler2(event, context):
reqid = event['detail']["headers"]["x-jdcloud-request-id"]
print(reqid)
serverId = None
try:
serverId = getServerId()
except Exception as e:
serverId = str(e)
cmds = event['detail']["queryParameters"].get("cmds", None)
if cmds is None:
cmds = []
elif type(cmds) is str:
cmds = [cmds]
cmdResult = []
for cmd in cmds:
cmdResult.append([cmd, runCmd(cmd)])
result = {
'statusCode': 200,
'headers': {'Content-Type': 'application/json; charset=utf-8'},
'body': json.dumps({
'serverId': serverId,
"sys.version": sys.version,
"event":event,
"uid":os.getuid(),
"context":str(context),
"cmdResult": cmdResult,
#"environ":dict(os.environ.items()),
}, sort_keys=True),
}
return result
if __name__ == '__main__':
import jdcloud_apim_mock as mock
import sys
if len(sys.argv) == 2:
mock.run(handler, sys.argv[1])
else:
mock.run(handler, "127.0.0.1:8080")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment