Brad Bishop | c342db3 | 2019-05-15 21:57:59 -0400 | [diff] [blame] | 1 | # |
| 2 | # SPDX-License-Identifier: GPL-2.0-only |
| 3 | # |
| 4 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 5 | import os,sys,logging |
| 6 | import signal, time |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 7 | import socket |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 8 | import io |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 9 | import sqlite3 |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 10 | import prserv |
| 11 | import prserv.db |
| 12 | import errno |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 13 | import bb.asyncrpc |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 14 | |
| 15 | logger = logging.getLogger("BitBake.PRserv") |
| 16 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 17 | PIDPREFIX = "/tmp/PRServer_%s_%s.pid" |
| 18 | singleton = None |
| 19 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 20 | class PRServerClient(bb.asyncrpc.AsyncServerConnection): |
| 21 | def __init__(self, reader, writer, table, read_only): |
| 22 | super().__init__(reader, writer, 'PRSERVICE', logger) |
| 23 | self.handlers.update({ |
| 24 | 'get-pr': self.handle_get_pr, |
| 25 | 'import-one': self.handle_import_one, |
| 26 | 'export': self.handle_export, |
| 27 | 'is-readonly': self.handle_is_readonly, |
| 28 | }) |
| 29 | self.table = table |
| 30 | self.read_only = read_only |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 31 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 32 | def validate_proto_version(self): |
| 33 | return (self.proto_version == (1, 0)) |
| 34 | |
| 35 | async def dispatch_message(self, msg): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 36 | try: |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 37 | await super().dispatch_message(msg) |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 38 | except: |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 39 | self.table.sync() |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 40 | raise |
| 41 | |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 42 | self.table.sync_if_dirty() |
| 43 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 44 | async def handle_get_pr(self, request): |
| 45 | version = request['version'] |
| 46 | pkgarch = request['pkgarch'] |
| 47 | checksum = request['checksum'] |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 48 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 49 | response = None |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 50 | try: |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 51 | value = self.table.getValue(version, pkgarch, checksum) |
| 52 | response = {'value': value} |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 53 | except prserv.NotFoundError: |
| 54 | logger.error("can not find value for (%s, %s)",version, checksum) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 55 | except sqlite3.Error as exc: |
| 56 | logger.error(str(exc)) |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 57 | |
| 58 | self.write_message(response) |
| 59 | |
| 60 | async def handle_import_one(self, request): |
| 61 | response = None |
| 62 | if not self.read_only: |
| 63 | version = request['version'] |
| 64 | pkgarch = request['pkgarch'] |
| 65 | checksum = request['checksum'] |
| 66 | value = request['value'] |
| 67 | |
| 68 | value = self.table.importone(version, pkgarch, checksum, value) |
| 69 | if value is not None: |
| 70 | response = {'value': value} |
| 71 | |
| 72 | self.write_message(response) |
| 73 | |
| 74 | async def handle_export(self, request): |
| 75 | version = request['version'] |
| 76 | pkgarch = request['pkgarch'] |
| 77 | checksum = request['checksum'] |
| 78 | colinfo = request['colinfo'] |
| 79 | |
| 80 | try: |
| 81 | (metainfo, datainfo) = self.table.export(version, pkgarch, checksum, colinfo) |
| 82 | except sqlite3.Error as exc: |
| 83 | logger.error(str(exc)) |
| 84 | metainfo = datainfo = None |
| 85 | |
| 86 | response = {'metainfo': metainfo, 'datainfo': datainfo} |
| 87 | self.write_message(response) |
| 88 | |
| 89 | async def handle_is_readonly(self, request): |
| 90 | response = {'readonly': self.read_only} |
| 91 | self.write_message(response) |
| 92 | |
| 93 | class PRServer(bb.asyncrpc.AsyncServer): |
| 94 | def __init__(self, dbfile, read_only=False): |
| 95 | super().__init__(logger) |
| 96 | self.dbfile = dbfile |
| 97 | self.table = None |
| 98 | self.read_only = read_only |
| 99 | |
| 100 | def accept_client(self, reader, writer): |
| 101 | return PRServerClient(reader, writer, self.table, self.read_only) |
| 102 | |
| 103 | def _serve_forever(self): |
| 104 | self.db = prserv.db.PRData(self.dbfile, read_only=self.read_only) |
| 105 | self.table = self.db["PRMAIN"] |
| 106 | |
| 107 | logger.info("Started PRServer with DBfile: %s, Address: %s, PID: %s" % |
| 108 | (self.dbfile, self.address, str(os.getpid()))) |
| 109 | |
| 110 | super()._serve_forever() |
| 111 | |
| 112 | self.table.sync_if_dirty() |
| 113 | self.db.disconnect() |
| 114 | |
| 115 | def signal_handler(self): |
| 116 | super().signal_handler() |
| 117 | if self.table: |
| 118 | self.table.sync() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 119 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 120 | class PRServSingleton(object): |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 121 | def __init__(self, dbfile, logfile, host, port): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 122 | self.dbfile = dbfile |
| 123 | self.logfile = logfile |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 124 | self.host = host |
| 125 | self.port = port |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 126 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 127 | def start(self): |
| 128 | self.prserv = PRServer(self.dbfile) |
| 129 | self.prserv.start_tcp_server(socket.gethostbyname(self.host), self.port) |
| 130 | self.process = self.prserv.serve_as_process() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 131 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 132 | if not self.prserv.address: |
| 133 | raise PRServiceConfigError |
| 134 | if not self.port: |
| 135 | self.port = int(self.prserv.address.rsplit(':', 1)[1]) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 136 | |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 137 | def run_as_daemon(func, pidfile, logfile): |
| 138 | """ |
| 139 | See Advanced Programming in the UNIX, Sec 13.3 |
| 140 | """ |
| 141 | try: |
| 142 | pid = os.fork() |
| 143 | if pid > 0: |
| 144 | os.waitpid(pid, 0) |
| 145 | #parent return instead of exit to give control |
| 146 | return pid |
| 147 | except OSError as e: |
| 148 | raise Exception("%s [%d]" % (e.strerror, e.errno)) |
| 149 | |
| 150 | os.setsid() |
| 151 | """ |
| 152 | fork again to make sure the daemon is not session leader, |
| 153 | which prevents it from acquiring controlling terminal |
| 154 | """ |
| 155 | try: |
| 156 | pid = os.fork() |
| 157 | if pid > 0: #parent |
| 158 | os._exit(0) |
| 159 | except OSError as e: |
| 160 | raise Exception("%s [%d]" % (e.strerror, e.errno)) |
| 161 | |
| 162 | os.chdir("/") |
| 163 | |
| 164 | sys.stdout.flush() |
| 165 | sys.stderr.flush() |
| 166 | |
| 167 | # We could be called from a python thread with io.StringIO as |
| 168 | # stdout/stderr or it could be 'real' unix fd forking where we need |
| 169 | # to physically close the fds to prevent the program launching us from |
| 170 | # potentially hanging on a pipe. Handle both cases. |
| 171 | si = open('/dev/null', 'r') |
| 172 | try: |
| 173 | os.dup2(si.fileno(),sys.stdin.fileno()) |
| 174 | except (AttributeError, io.UnsupportedOperation): |
| 175 | sys.stdin = si |
| 176 | so = open(logfile, 'a+') |
| 177 | try: |
| 178 | os.dup2(so.fileno(),sys.stdout.fileno()) |
| 179 | except (AttributeError, io.UnsupportedOperation): |
| 180 | sys.stdout = so |
| 181 | try: |
| 182 | os.dup2(so.fileno(),sys.stderr.fileno()) |
| 183 | except (AttributeError, io.UnsupportedOperation): |
| 184 | sys.stderr = so |
| 185 | |
| 186 | # Clear out all log handlers prior to the fork() to avoid calling |
| 187 | # event handlers not part of the PRserver |
| 188 | for logger_iter in logging.Logger.manager.loggerDict.keys(): |
| 189 | logging.getLogger(logger_iter).handlers = [] |
| 190 | |
| 191 | # Ensure logging makes it to the logfile |
| 192 | streamhandler = logging.StreamHandler() |
| 193 | streamhandler.setLevel(logging.DEBUG) |
| 194 | formatter = bb.msg.BBLogFormatter("%(levelname)s: %(message)s") |
| 195 | streamhandler.setFormatter(formatter) |
| 196 | logger.addHandler(streamhandler) |
| 197 | |
| 198 | # write pidfile |
| 199 | pid = str(os.getpid()) |
| 200 | with open(pidfile, 'w') as pf: |
| 201 | pf.write("%s\n" % pid) |
| 202 | |
| 203 | func() |
| 204 | os.remove(pidfile) |
| 205 | os._exit(0) |
| 206 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 207 | def start_daemon(dbfile, host, port, logfile, read_only=False): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 208 | ip = socket.gethostbyname(host) |
| 209 | pidfile = PIDPREFIX % (ip, port) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 210 | try: |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 211 | with open(pidfile) as pf: |
| 212 | pid = int(pf.readline().strip()) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 213 | except IOError: |
| 214 | pid = None |
| 215 | |
| 216 | if pid: |
| 217 | sys.stderr.write("pidfile %s already exist. Daemon already running?\n" |
| 218 | % pidfile) |
| 219 | return 1 |
| 220 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 221 | dbfile = os.path.abspath(dbfile) |
| 222 | def daemon_main(): |
| 223 | server = PRServer(dbfile, read_only=read_only) |
| 224 | server.start_tcp_server(ip, port) |
| 225 | server.serve_forever() |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 226 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 227 | run_as_daemon(daemon_main, pidfile, os.path.abspath(logfile)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 228 | return 0 |
| 229 | |
| 230 | def stop_daemon(host, port): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 231 | import glob |
| 232 | ip = socket.gethostbyname(host) |
| 233 | pidfile = PIDPREFIX % (ip, port) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 234 | try: |
Brad Bishop | 64c979e | 2019-11-04 13:55:29 -0500 | [diff] [blame] | 235 | with open(pidfile) as pf: |
| 236 | pid = int(pf.readline().strip()) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 237 | except IOError: |
| 238 | pid = None |
| 239 | |
| 240 | if not pid: |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 241 | # when server starts at port=0 (i.e. localhost:0), server actually takes another port, |
| 242 | # so at least advise the user which ports the corresponding server is listening |
| 243 | ports = [] |
| 244 | portstr = "" |
| 245 | for pf in glob.glob(PIDPREFIX % (ip,'*')): |
| 246 | bn = os.path.basename(pf) |
| 247 | root, _ = os.path.splitext(bn) |
| 248 | ports.append(root.split('_')[-1]) |
| 249 | if len(ports): |
| 250 | portstr = "Wrong port? Other ports listening at %s: %s" % (host, ' '.join(ports)) |
| 251 | |
| 252 | sys.stderr.write("pidfile %s does not exist. Daemon not running? %s\n" |
| 253 | % (pidfile,portstr)) |
| 254 | return 1 |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 255 | |
| 256 | try: |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 257 | if is_running(pid): |
| 258 | print("Sending SIGTERM to pr-server.") |
| 259 | os.kill(pid, signal.SIGTERM) |
| 260 | time.sleep(0.1) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 261 | |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 262 | if os.path.exists(pidfile): |
| 263 | os.remove(pidfile) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 264 | |
| 265 | except OSError as e: |
| 266 | err = str(e) |
| 267 | if err.find("No such process") <= 0: |
| 268 | raise e |
| 269 | |
| 270 | return 0 |
| 271 | |
| 272 | def is_running(pid): |
| 273 | try: |
| 274 | os.kill(pid, 0) |
| 275 | except OSError as err: |
| 276 | if err.errno == errno.ESRCH: |
| 277 | return False |
| 278 | return True |
| 279 | |
| 280 | def is_local_special(host, port): |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 281 | if (host == 'localhost' or host == '127.0.0.1') and not port: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 282 | return True |
| 283 | else: |
| 284 | return False |
| 285 | |
| 286 | class PRServiceConfigError(Exception): |
| 287 | pass |
| 288 | |
| 289 | def auto_start(d): |
| 290 | global singleton |
| 291 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 292 | host_params = list(filter(None, (d.getVar('PRSERV_HOST') or '').split(':'))) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 293 | if not host_params: |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 294 | # Shutdown any existing PR Server |
| 295 | auto_shutdown() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 296 | return None |
| 297 | |
| 298 | if len(host_params) != 2: |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 299 | # Shutdown any existing PR Server |
| 300 | auto_shutdown() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 301 | logger.critical('\n'.join(['PRSERV_HOST: incorrect format', |
| 302 | 'Usage: PRSERV_HOST = "<hostname>:<port>"'])) |
| 303 | raise PRServiceConfigError |
| 304 | |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 305 | host = host_params[0].strip().lower() |
| 306 | port = int(host_params[1]) |
| 307 | if is_local_special(host, port): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 308 | import bb.utils |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 309 | cachedir = (d.getVar("PERSISTENT_DIR") or d.getVar("CACHE")) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 310 | if not cachedir: |
| 311 | logger.critical("Please set the 'PERSISTENT_DIR' or 'CACHE' variable") |
| 312 | raise PRServiceConfigError |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 313 | dbfile = os.path.join(cachedir, "prserv.sqlite3") |
| 314 | logfile = os.path.join(cachedir, "prserv.log") |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 315 | if singleton: |
| 316 | if singleton.dbfile != dbfile: |
| 317 | # Shutdown any existing PR Server as doesn't match config |
| 318 | auto_shutdown() |
| 319 | if not singleton: |
| 320 | bb.utils.mkdirhier(cachedir) |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 321 | singleton = PRServSingleton(os.path.abspath(dbfile), os.path.abspath(logfile), host, port) |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 322 | singleton.start() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 323 | if singleton: |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 324 | host = singleton.host |
| 325 | port = singleton.port |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 326 | |
| 327 | try: |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 328 | ping(host, port) |
| 329 | return str(host) + ":" + str(port) |
| 330 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 331 | except Exception: |
| 332 | logger.critical("PRservice %s:%d not available" % (host, port)) |
| 333 | raise PRServiceConfigError |
| 334 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 335 | def auto_shutdown(): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 336 | global singleton |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 337 | if singleton and singleton.process: |
| 338 | singleton.process.terminate() |
| 339 | singleton.process.join() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 340 | singleton = None |
| 341 | |
| 342 | def ping(host, port): |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 343 | from . import client |
| 344 | |
| 345 | conn = client.PRClient() |
| 346 | conn.connect_tcp(host, port) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 347 | return conn.ping() |
Andrew Geissler | c926e17 | 2021-05-07 16:11:35 -0500 | [diff] [blame] | 348 | |
| 349 | def connect(host, port): |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 350 | from . import client |
| 351 | |
| 352 | global singleton |
| 353 | |
| 354 | if host.strip().lower() == 'localhost' and not port: |
| 355 | host = 'localhost' |
| 356 | port = singleton.port |
| 357 | |
| 358 | conn = client.PRClient() |
| 359 | conn.connect_tcp(host, port) |
| 360 | return conn |