Merge branch '8465-cwl-containers-stdin-stderr' closes #8465
[arvados.git] / services / nodemanager / arvnodeman / status.py
1 from __future__ import absolute_import, print_function
2 from future import standard_library
3
4 import http.server
5 import json
6 import logging
7 import socketserver
8 import threading
9
10 _logger = logging.getLogger('status.Handler')
11
12
13 class Server(socketserver.ThreadingMixIn, http.server.HTTPServer, object):
14     def __init__(self, config):
15         port = config.getint('Manage', 'port')
16         self.enabled = port >= 0
17         if not self.enabled:
18             _logger.warning("Management server disabled. "+
19                             "Use [Manage] config section to enable.")
20             return
21         self._config = config
22         self._tracker = tracker
23         super(Server, self).__init__(
24             (config.get('Manage', 'address'), port), Handler)
25         self._thread = threading.Thread(target=self.serve_forever)
26         self._thread.daemon = True
27
28     def start(self):
29         if self.enabled:
30             self._thread.start()
31
32
33 class Handler(http.server.BaseHTTPRequestHandler, object):
34     def do_GET(self):
35         if self.path == '/status.json':
36             self.send_response(200)
37             self.send_header('Content-type', 'application/json')
38             self.end_headers()
39             self.wfile.write(tracker.get_json())
40         else:
41             self.send_response(404)
42
43     def log_message(self, fmt, *args, **kwargs):
44         _logger.info(fmt, *args, **kwargs)
45
46
47 class Tracker(object):
48     def __init__(self):
49         self._mtx = threading.Lock()
50         self._latest = {}
51
52     def get_json(self):
53         with self._mtx:
54             return json.dumps(self._latest)
55
56     def keys(self):
57         with self._mtx:
58             return self._latest.keys()
59
60     def update(self, updates):
61         with self._mtx:
62             self._latest.update(updates)
63
64
65 tracker = Tracker()