-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathopen_lambda.py
More file actions
64 lines (46 loc) · 1.96 KB
/
open_lambda.py
File metadata and controls
64 lines (46 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
''' OpenLambda's Python API '''
import json as pyjson
import requests
from requests import Session
class OpenLambda:
''' Represents a client connection to OpenLambda '''
def __init__(self, address="localhost:5000"):
self._address = address
self._session = Session()
def _post(self, path, data=None, timeout=None):
''' Issues a _post request to the OL worker '''
return self._session.post(f'http://{self._address}/{path}', pyjson.dumps(data), timeout=timeout)
def run(self, fn_name, args, json=True, timeout=60):
''' Execute a serverless function '''
resp = self._post(f"run/{fn_name}", args, timeout=timeout)
self._check_status_code(resp, "run")
if json:
return resp.json()
return resp.text
def create(self, args):
''' Create a new sandbox '''
resp = self._post("create", args)
self._check_status_code(resp, "create")
return resp.text.strip()
def destroy(self, sandbox_id):
''' Destroy a new sandbox '''
resp = self._post(f"destroy/{sandbox_id}", {})
self._check_status_code(resp, "destroy")
def pause(self, sandbox_id):
''' Pause a new sandbox '''
resp = self._post(f"pause/{sandbox_id}", None)
self._check_status_code(resp, "pause")
def get_statistics(self):
''' Returns stats of the OpenLambda server '''
resp = self._session.get(f"http://{self._address}/stats")
self._check_status_code(resp, "get_statistics")
return resp.json()
@staticmethod
def _check_status_code(resp, name):
if resp.status_code != 200:
msg = f'"{name}" failed with status code {resp.status_code}: {resp.text}'
raise requests.HTTPError(msg)
def check_status(self):
''' Checks the status of the OpenLambda server '''
resp = self._session.get(f"http://{self._address}/status")
self._check_status_code(resp, "check_status")