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