-
Notifications
You must be signed in to change notification settings - Fork 23
/
hosted.py
1379 lines (1189 loc) · 39.8 KB
/
hosted.py
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Part of info-beamer hosted. You can find the latest version
# of this file at:
#
# https://github.com/info-beamer/package-sdk
#
# Copyright (c) 2014-2020 Florian Wesch <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
VERSION = "1.9"
import os, re, sys, json, time, traceback, marshal, hashlib
import errno, socket, select, threading, Queue, ctypes
import pyinotify, requests
from functools import wraps
from collections import namedtuple
from tempfile import NamedTemporaryFile
types = {}
def init_types():
def type(fn):
types[fn.__name__] = fn
return fn
@type
def color(value):
return value
@type
def string(value):
return value
@type
def text(value):
return value
@type
def section(value):
return value
@type
def boolean(value):
return value
@type
def select(value):
return value
@type
def duration(value):
return value
@type
def integer(value):
return value
@type
def float(value):
return value
@type
def font(value):
return value
@type
def device(value):
return value
@type
def resource(value):
return value
@type
def device_token(value):
return value
@type
def json(value):
return value
@type
def custom(value):
return value
@type
def date(value):
return value
init_types()
def log(msg, name='hosted.py'):
sys.stderr.write("[{}] {}\n".format(name, msg))
def abort_service(reason):
log("restarting service (%s)" % reason)
os._exit(0)
time.sleep(2)
os.kill(os.getpid(), 2)
time.sleep(2)
os.kill(os.getpid(), 15)
time.sleep(2)
os.kill(os.getpid(), 9)
time.sleep(100)
CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
class timespec(ctypes.Structure):
_fields_ = [
('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long),
]
librt = ctypes.CDLL('librt.so.1')
clock_gettime = librt.clock_gettime
clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
def monotonic_time():
t = timespec()
clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t))
return t.tv_sec + t.tv_nsec * 1e-9
class InfoBeamerQueryException(Exception):
pass
class InfoBeamerQuery(object):
def __init__(self, host='127.0.0.1', port=4444):
self._sock = None
self._conn = None
self._host = host
self._port = port
self._timeout = 2
self._version = None
def _reconnect(self):
if self._conn is not None:
return
try:
self._sock = socket.create_connection((self._host, self._port), self._timeout)
self._conn = self._sock.makefile()
intro = self._conn.readline()
except socket.timeout:
self._reset()
raise InfoBeamerQueryException("Timeout while reopening connection")
except socket.error as err:
self._reset()
raise InfoBeamerQueryException("Cannot connect to %s:%s: %s" % (
self._host, self._port, err))
m = re.match("^Info Beamer PI ([^ ]+)", intro)
if not m:
self._reset()
raise InfoBeamerQueryException("Invalid handshake. Not info-beamer?")
self._version = m.group(1)
def _parse_line(self):
line = self._conn.readline()
if not line:
return None
return line.rstrip()
def _parse_multi_line(self):
lines = []
while 1:
line = self._conn.readline()
if not line:
return None
line = line.rstrip()
if not line:
break
lines.append(line)
return '\n'.join(lines)
def _send_cmd(self, min_version, cmd, multiline=False):
for retry in (1, 2):
self._reconnect()
if self._version <= min_version:
raise InfoBeamerQueryException(
"This query is not implemented in your version of info-beamer. "
"%s or higher required, %s found" % (min_version, self._version)
)
try:
self._conn.write(cmd + "\n")
self._conn.flush()
response = self._parse_multi_line() if multiline else self._parse_line()
if response is None:
self._reset()
continue
return response
except socket.error:
self._reset()
continue
except socket.timeout:
self._reset()
raise InfoBeamerQueryException("Timeout waiting for response")
except Exception:
self._reset()
continue
raise InfoBeamerQueryException("Failed to get a response")
def _reset(self, close=True):
if close:
try:
if self._conn: self._conn.close()
if self._sock: self._sock.close()
except:
pass
self._conn = None
self._sock = None
@property
def addr(self):
return "%s:%s" % (self._host, self._port)
def close(self):
self._reset()
@property
def ping(self):
"tests if info-beamer is reachable"
return self._send_cmd(
"0.6", "*query/*ping",
) == "pong"
@property
def uptime(self):
"returns the uptime in seconds"
return int(self._send_cmd(
"0.6", "*query/*uptime",
))
@property
def objects(self):
"returns the number of allocated info-beamer objects"
return int(self._send_cmd(
"0.9.4", "*query/*objects",
))
@property
def version(self):
"returns the running info-beamer version"
return self._send_cmd(
"0.6", "*query/*version",
)
@property
def fps(self):
"returns the FPS of the top level node"
return float(self._send_cmd(
"0.6", "*query/*fps",
))
@property
def display(self):
"returns the display configuration"
return json.loads(self._send_cmd(
"1.0", "*query/*display",
))
ResourceUsage = namedtuple("ResourceUsage", "user_time system_time memory")
@property
def resources(self):
"returns information about used resources"
return self.ResourceUsage._make(int(v) for v in self._send_cmd(
"0.6", "*query/*resources",
).split(','))
ScreenSize = namedtuple("ScreenSize", "width height")
@property
def screen(self):
"returns the native screen size"
return self.ScreenSize._make(int(v) for v in self._send_cmd(
"0.8.1", "*query/*screen",
).split(','))
@property
def runid(self):
"returns a unique run id that changes with every restart of info-beamer"
return self._send_cmd(
"0.9.0", "*query/*runid",
)
@property
def nodes(self):
"returns a list of nodes"
nodes = self._send_cmd(
"0.9.3", "*query/*nodes",
).split(',')
return [] if not nodes[0] else nodes
class Node(object):
def __init__(self, ib, path):
self._ib = ib
self._path = path
@property
def mem(self):
"returns the Lua memory usage of this node"
return int(self._ib._send_cmd(
"0.6", "*query/*mem/%s" % self._path
))
@property
def fps(self):
"returns the framerate of this node"
return float(self._ib._send_cmd(
"0.6", "*query/*fps/%s" % self._path
))
def io(self, raw=True):
"creates a tcp connection to this node"
status = self._ib._send_cmd(
"0.6", "%s%s" % ("*raw/" if raw else '', self._path),
)
if status != 'ok!':
raise InfoBeamerQueryException("Cannot connect to node %s" % self._path)
sock = self._ib._sock
sock.settimeout(None)
return self._ib._conn
@property
def has_error(self):
"queries the error flag"
return bool(int(self._ib._send_cmd(
"0.8.2", "*query/*has_error/%s" % self._path,
)))
@property
def error(self):
"returns the last Lua traceback"
return self._ib._send_cmd(
"0.8.2", "*query/*error/%s" % self._path, multiline=True
)
def __repr__(self):
return "%s/%s" % (self._ib, self._path)
def node(self, node):
return self.Node(self, node)
def __repr__(self):
return "<info-beamer@%s>" % self.addr
class Configuration(object):
def __init__(self):
self._restart = False
self._options = []
self._config = {}
self._parsed = {}
self.parse_node_json(do_update=False)
self.parse_config_json()
def restart_on_update(self):
log("going to restart when config is updated")
self._restart = True
def parse_node_json(self, do_update=True):
with open("node.json") as f:
self._options = json.load(f).get('options', [])
if do_update:
self.update_config()
def parse_config_json(self, do_update=True):
with open("config.json") as f:
self._config = json.load(f)
if do_update:
self.update_config()
def update_config(self):
if self._restart:
return abort_service("restart_on_update set")
def parse_recursive(options, config, target):
# print 'parsing', config
for option in options:
if not 'name' in option:
continue
if option['type'] == 'list':
items = []
for item in config[option['name']]:
parsed = {}
parse_recursive(option['items'], item, parsed)
items.append(parsed)
target[option['name']] = items
continue
target[option['name']] = types[option['type']](config[option['name']])
parsed = {}
parse_recursive(self._options, self._config, parsed)
log("updated config")
self._parsed = parsed
@property
def raw(self):
return self._config
@property
def metadata(self):
return self._config['__metadata']
@property
def metadata_timezone(self):
import pytz
return pytz.timezone(self.metadata['timezone'])
def __getitem__(self, key):
return self._parsed[key]
def __getattr__(self, key):
return self._parsed[key]
def setup_inotify(configuration):
class EventHandler(pyinotify.ProcessEvent):
def process_default(self, event):
basename = os.path.basename(event.pathname)
if basename == 'node.json':
log("node.json changed")
configuration.parse_node_json()
elif basename == 'config.json':
log("config.json changed!")
configuration.parse_config_json()
elif basename.endswith('.py'):
abort_service("python file changed")
wm = pyinotify.WatchManager()
notifier = pyinotify.ThreadedNotifier(wm, EventHandler())
notifier.daemon = True
notifier.start()
wm.add_watch('.', pyinotify.IN_MOVED_TO)
class RPC(object):
def __init__(self, path, callbacks):
self._path = path
self._callbacks = callbacks
self._lock = threading.Lock()
self._con = None
thread = threading.Thread(target=self._listen_thread)
thread.daemon = True
thread.start()
def _get_connection(self):
if self._con is None:
try:
self._con = InfoBeamerQuery().node(
self._path + "/rpc/python"
).io(raw=True)
except InfoBeamerQueryException:
return None
return self._con
def _close_connection(self):
with self._lock:
if self._con:
try:
self._con.close()
except:
pass
self._con = None
def _send(self, line):
with self._lock:
con = self._get_connection()
if con is None:
return
try:
con.write(line + '\n')
con.flush()
return True
except:
self._close_connection()
return False
def _recv(self):
with self._lock:
con = self._get_connection()
try:
return con.readline()
except:
self._close_connection()
def _listen_thread(self):
while 1:
line = self._recv()
if not line:
self._close_connection()
time.sleep(0.5)
continue
try:
args = json.loads(line)
method = args.pop(0)
callback = self._callbacks.get(method)
if callback:
callback(*args)
else:
log("callback '%s' not found" % (method,))
except:
traceback.print_exc()
def register(self, name, fn):
self._callbacks[name] = fn
def call(self, fn):
self.register(fn.__name__, fn)
def __getattr__(self, method):
def call(*args):
args = list(args)
args.insert(0, method)
return self._send(json.dumps(
args,
ensure_ascii=False,
separators=(',',':'),
).encode('utf8'))
return call
class Cache(object):
def __init__(self, scope='default'):
self._touched = set()
self._prefix = 'cache-%s-' % scope
def key_to_fname(self, key):
return self._prefix + hashlib.md5(key).hexdigest()
def has(self, key, max_age=None):
try:
stat = os.stat(self.key_to_fname(key))
if max_age is not None:
now = time.time()
if now > stat.st_mtime + max_age:
return False
return True
except:
return False
def get(self, key, max_age=None):
try:
with open(self.file_ref(key)) as f:
if max_age is not None:
stat = os.fstat(f.fileno())
now = time.time()
if now > stat.st_mtime + max_age:
return None
return f.read()
except:
return None
def get_json(self, key, max_age=None):
data = self.get(key, max_age)
if data is None:
return None
return json.loads(data)
def set(self, key, value):
with open(self.file_ref(key), "wb") as f:
f.write(value)
def set_json(self, key, data):
self.set(key, json.dumps(data))
def file_ref(self, key):
fname = self.key_to_fname(key)
self._touched.add(fname)
return fname
def start(self):
self._touched = set()
def prune(self):
existing = set()
for fname in os.listdir("."):
if not fname.startswith(self._prefix):
continue
existing.add(fname)
prunable = existing - self._touched
for fname in prunable:
try:
log("pruning %s" % fname)
os.unlink(fname)
except:
pass
def clear(self):
self.start()
self.prune()
def call(self, max_age=None):
def deco(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
key = marshal.dumps((fn.__name__, args, kwargs), 2)
cached = self.get(key, max_age)
if cached is not None:
return marshal.loads(cached)
val = fn(*args, **kwargs)
self.set(key, marshal.dumps(val, 2))
return val
return wrapper
return deco
def file_producer(self, max_age=None):
def deco(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
key = marshal.dumps((fn.__name__, args, kwargs), 2)
if self.has(key, max_age):
return self.file_ref(key)
val = fn(*args, **kwargs)
if val is None:
return None
self.set(key, val)
return self.file_ref(key)
return wrapper
return deco
class Node(object):
def __init__(self, node):
self._node = node
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def send_raw(self, raw):
log("sending %r" % (raw,))
self._sock.sendto(raw, ('127.0.0.1', 4444))
def send(self, data):
self.send_raw(self._node + data)
def send_json(self, path, data):
self.send('%s:%s' % (path, json.dumps(
data,
ensure_ascii=False,
separators=(',',':'),
).encode('utf8')))
@property
def is_top_level(self):
return self._node == "root"
@property
def path(self):
return self._node
def write_file(self, filename, content):
f = NamedTemporaryFile(prefix='.hosted-py-tmp', dir=os.getcwd())
try:
f.write(content)
except:
traceback.print_exc()
f.close()
raise
else:
f.delete = False
f.close()
os.rename(f.name, filename)
def write_json(self, filename, data):
self.write_file(filename, json.dumps(
data,
ensure_ascii=False,
separators=(',',':'),
).encode('utf8'))
class Sender(object):
def __init__(self, node, path):
self._node = node
self._path = path
def __call__(self, data):
if isinstance(data, (dict, list)):
raw = "%s:%s" % (self._path, json.dumps(
data,
ensure_ascii=False,
separators=(',',':'),
).encode('utf8'))
else:
raw = "%s:%s" % (self._path, data)
self._node.send_raw(raw)
def __getitem__(self, path):
return self.Sender(self, self._node + path)
def __call__(self, data):
return self.Sender(self, self._node)(data)
def connect(self, suffix=""):
ib = InfoBeamerQuery()
return ib.node(self.path + suffix).io(raw=True)
def rpc(self, **callbacks):
return RPC(self.path, callbacks)
def cache(self, scope='default'):
return Cache(scope)
def scratch_cached(self, filename, generator):
cached = os.path.join(os.environ['SCRATCH'], filename)
if not os.path.exists(cached):
f = NamedTemporaryFile(prefix='scratch-cached-tmp', dir=os.environ['SCRATCH'])
try:
generator(f)
except:
raise
else:
f.delete = False
f.close()
os.rename(f.name, cached)
if os.path.exists(filename):
try:
os.unlink(filename)
except:
pass
os.symlink(cached, filename)
class APIError(Exception):
pass
class APIProxy(object):
def __init__(self, apis, api_name):
self._apis = apis
self._api_name = api_name
@property
def url(self):
index = self._apis.get_api_index()
if not self._api_name in index:
raise APIError("api '%s' not available" % (self._api_name,))
return index[self._api_name]['url']
def unwrap(self, r):
r.raise_for_status()
if r.status_code == 304:
return None
if r.headers['content-type'] == 'application/json':
resp = r.json()
if not resp['ok']:
raise APIError(u"api call failed: %s" % (
resp.get('error', '<unknown error>'),
))
return resp.get(self._api_name)
else:
return r.content
def add_default_args(self, kwargs):
if not 'timeout' in kwargs:
kwargs['timeout'] = 10
return kwargs
def get(self, **kwargs):
try:
return self.unwrap(self._apis.session.get(
url = self.url,
**self.add_default_args(kwargs)
))
except APIError:
raise
except Exception as err:
raise APIError(err)
def post(self, **kwargs):
try:
return self.unwrap(self._apis.session.post(
url = self.url,
**self.add_default_args(kwargs)
))
except APIError:
raise
except Exception as err:
raise APIError(err)
def delete(self, **kwargs):
try:
return self.unwrap(self._apis.session.delete(
url = self.url,
**self.add_default_args(kwargs)
))
except APIError:
raise
except Exception as err:
raise APIError(err)
class OnDeviceAPIs(object):
def __init__(self, config):
self._config = config
self._index = None
self._valid_until = 0
self._lock = threading.Lock()
self._session = requests.Session()
self._session.headers.update({
'User-Agent': 'hosted.py version/%s' % (VERSION,)
})
def update_apis(self):
log("fetching api index")
r = self._session.get(
url = self._config.metadata['api'],
timeout = 5,
)
r.raise_for_status()
resp = r.json()
if not resp['ok']:
raise APIError("cannot retrieve api index")
self._index = resp['apis']
self._valid_until = resp['valid_until'] - 300
def get_api_index(self):
with self._lock:
now = time.time()
if now > self._valid_until:
self.update_apis()
return self._index
@property
def session(self):
return self._session
def list(self):
try:
index = self.get_api_index()
return sorted(index.keys())
except Exception as err:
raise APIError(err)
def __getitem__(self, api_name):
return APIProxy(self, api_name)
def __getattr__(self, api_name):
return APIProxy(self, api_name)
class HostedAPI(object):
def __init__(self, api, on_device_token):
self._api = api
self._on_device_token = on_device_token
self._lock = threading.Lock()
self._next_refresh = 0
self._api_key = None
self._uses = 0
self._expire = 0
self._base_url = None
self._session = requests.Session()
self._session.headers.update({
'User-Agent': 'hosted.py version/%s - on-device' % (VERSION,)
})
def use_api_key(self):
with self._lock:
now = time.time()
self._uses -= 1
if self._uses <= 0:
log('hosted API adhoc key used up')
self._api_key = None
elif now > self._expire:
log('hosted API adhoc key expired')
self._api_key = None
else:
log('hosted API adhoc key usage: %d uses, %ds left' %(
self._uses, self._expire - now
))
if self._api_key is None:
if time.time() < self._next_refresh:
return None
log('refreshing hosted API adhoc key')
self._next_refresh = time.time() + 15
try:
r = self._api['api_key'].get(
params = dict(
on_device_token = self._on_device_token
),
timeout = 5,
)
except:
return None
self._api_key = r['api_key']
self._uses = r['uses']
self._expire = now + r['expire'] - 1
self._base_url = r['base_url']
return self._api_key
def add_default_args(self, kwargs):
if not 'timeout' in kwargs:
kwargs['timeout'] = 10
return kwargs
def ensure_api_key(self, kwargs):
api_key = self.use_api_key()
if api_key is None:
raise APIError('cannot retrieve API key')
kwargs['auth'] = ('', api_key)
def get(self, endpoint, **kwargs):
try:
self.ensure_api_key(kwargs)
r = self._session.get(
url = self._base_url + endpoint,
**self.add_default_args(kwargs)
)
r.raise_for_status()
return r.json()
except APIError:
raise
except Exception as err:
raise APIError(err)
def post(self, endpoint, **kwargs):
try:
self.ensure_api_key(kwargs)
r = self._session.post(
url = self._base_url + endpoint,
**self.add_default_args(kwargs)
)
r.raise_for_status()
return r.json()
except APIError:
raise
except Exception as err:
raise APIError(err)
def delete(self, endpoint, **kwargs):
try:
self.ensure_api_key(kwargs)
r = self._session.delete(
url = self._base_url + endpoint,
**self.add_default_args(kwargs)
)
r.raise_for_status()
return r.json()
except APIError:
raise
except Exception as err:
raise APIError(err)
class DeviceKV(object):
def __init__(self, api):
self._api = api
self._cache = {}
self._cache_complete = False
self._use_cache = True
def cache_enabled(self, enabled):
self._use_cache = enabled
self._cache = {}
self._cache_complete = False
def __setitem__(self, key, value):
if self._use_cache:
if key in self._cache and self._cache[key] == value:
return
self._api['kv'].post(
data = {
key: value
}
)
if self._use_cache:
self._cache[key] = value
def __getitem__(self, key):
if self._use_cache:
if key in self._cache:
return self._cache[key]
result = self._api['kv'].get(
params = dict(
keys = key,
),
timeout = 5,
)['v']
if key not in result:
raise KeyError(key)
value = result[key]
if self._use_cache:
self._cache[key] = value
return value
# http api cannot reliably determine if a key has