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 | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 7 | from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 8 | import threading |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 9 | import queue |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 10 | import socket |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 11 | import io |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 12 | import sqlite3 |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 13 | import bb.server.xmlrpcclient |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 14 | import prserv |
| 15 | import prserv.db |
| 16 | import errno |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 17 | import select |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 18 | |
| 19 | logger = logging.getLogger("BitBake.PRserv") |
| 20 | |
| 21 | if sys.hexversion < 0x020600F0: |
| 22 | print("Sorry, python 2.6 or later is required.") |
| 23 | sys.exit(1) |
| 24 | |
| 25 | class Handler(SimpleXMLRPCRequestHandler): |
| 26 | def _dispatch(self,method,params): |
| 27 | try: |
| 28 | value=self.server.funcs[method](*params) |
| 29 | except: |
| 30 | import traceback |
| 31 | traceback.print_exc() |
| 32 | raise |
| 33 | return value |
| 34 | |
| 35 | PIDPREFIX = "/tmp/PRServer_%s_%s.pid" |
| 36 | singleton = None |
| 37 | |
| 38 | |
| 39 | class PRServer(SimpleXMLRPCServer): |
| 40 | def __init__(self, dbfile, logfile, interface, daemon=True): |
| 41 | ''' constructor ''' |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 42 | try: |
| 43 | SimpleXMLRPCServer.__init__(self, interface, |
| 44 | logRequests=False, allow_none=True) |
| 45 | except socket.error: |
| 46 | ip=socket.gethostbyname(interface[0]) |
| 47 | port=interface[1] |
| 48 | msg="PR Server unable to bind to %s:%s\n" % (ip, port) |
| 49 | sys.stderr.write(msg) |
| 50 | raise PRServiceConfigError |
| 51 | |
| 52 | self.dbfile=dbfile |
| 53 | self.daemon=daemon |
| 54 | self.logfile=logfile |
| 55 | self.working_thread=None |
| 56 | self.host, self.port = self.socket.getsockname() |
| 57 | self.pidfile=PIDPREFIX % (self.host, self.port) |
| 58 | |
| 59 | self.register_function(self.getPR, "getPR") |
| 60 | self.register_function(self.quit, "quit") |
| 61 | self.register_function(self.ping, "ping") |
| 62 | self.register_function(self.export, "export") |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 63 | self.register_function(self.dump_db, "dump_db") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 64 | self.register_function(self.importone, "importone") |
| 65 | self.register_introspection_functions() |
| 66 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 67 | self.quitpipein, self.quitpipeout = os.pipe() |
| 68 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 69 | self.requestqueue = queue.Queue() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 70 | self.handlerthread = threading.Thread(target = self.process_request_thread) |
| 71 | self.handlerthread.daemon = False |
| 72 | |
| 73 | def process_request_thread(self): |
| 74 | """Same as in BaseServer but as a thread. |
| 75 | |
| 76 | In addition, exception handling is done here. |
| 77 | |
| 78 | """ |
| 79 | iter_count = 1 |
| 80 | # 60 iterations between syncs or sync if dirty every ~30 seconds |
| 81 | iterations_between_sync = 60 |
| 82 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 83 | bb.utils.set_process_name("PRServ Handler") |
| 84 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 85 | while not self.quitflag: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 86 | try: |
| 87 | (request, client_address) = self.requestqueue.get(True, 30) |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 88 | except queue.Empty: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 89 | self.table.sync_if_dirty() |
| 90 | continue |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 91 | if request is None: |
| 92 | continue |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 93 | try: |
| 94 | self.finish_request(request, client_address) |
| 95 | self.shutdown_request(request) |
| 96 | iter_count = (iter_count + 1) % iterations_between_sync |
| 97 | if iter_count == 0: |
| 98 | self.table.sync_if_dirty() |
| 99 | except: |
| 100 | self.handle_error(request, client_address) |
| 101 | self.shutdown_request(request) |
| 102 | self.table.sync() |
| 103 | self.table.sync_if_dirty() |
| 104 | |
| 105 | def sigint_handler(self, signum, stack): |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 106 | if self.table: |
| 107 | self.table.sync() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 108 | |
| 109 | def sigterm_handler(self, signum, stack): |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 110 | if self.table: |
| 111 | self.table.sync() |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 112 | self.quit() |
| 113 | self.requestqueue.put((None, None)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 114 | |
| 115 | def process_request(self, request, client_address): |
| 116 | self.requestqueue.put((request, client_address)) |
| 117 | |
| 118 | def export(self, version=None, pkgarch=None, checksum=None, colinfo=True): |
| 119 | try: |
| 120 | return self.table.export(version, pkgarch, checksum, colinfo) |
| 121 | except sqlite3.Error as exc: |
| 122 | logger.error(str(exc)) |
| 123 | return None |
| 124 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 125 | def dump_db(self): |
| 126 | """ |
| 127 | Returns a script (string) that reconstructs the state of the |
| 128 | entire database at the time this function is called. The script |
| 129 | language is defined by the backing database engine, which is a |
| 130 | function of server configuration. |
| 131 | Returns None if the database engine does not support dumping to |
| 132 | script or if some other error is encountered in processing. |
| 133 | """ |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 134 | buff = io.StringIO() |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 135 | try: |
| 136 | self.table.sync() |
| 137 | self.table.dump_db(buff) |
| 138 | return buff.getvalue() |
| 139 | except Exception as exc: |
| 140 | logger.error(str(exc)) |
| 141 | return None |
| 142 | finally: |
| 143 | buff.close() |
| 144 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 145 | def importone(self, version, pkgarch, checksum, value): |
| 146 | return self.table.importone(version, pkgarch, checksum, value) |
| 147 | |
| 148 | def ping(self): |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 149 | return not self.quitflag |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 150 | |
| 151 | def getinfo(self): |
| 152 | return (self.host, self.port) |
| 153 | |
| 154 | def getPR(self, version, pkgarch, checksum): |
| 155 | try: |
| 156 | return self.table.getValue(version, pkgarch, checksum) |
| 157 | except prserv.NotFoundError: |
| 158 | logger.error("can not find value for (%s, %s)",version, checksum) |
| 159 | return None |
| 160 | except sqlite3.Error as exc: |
| 161 | logger.error(str(exc)) |
| 162 | return None |
| 163 | |
| 164 | def quit(self): |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 165 | self.quitflag=True |
| 166 | os.write(self.quitpipeout, b"q") |
| 167 | os.close(self.quitpipeout) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 168 | return |
| 169 | |
| 170 | def work_forever(self,): |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 171 | self.quitflag = False |
| 172 | # This timeout applies to the poll in TCPServer, we need the select |
| 173 | # below to wake on our quit pipe closing. We only ever call into handle_request |
| 174 | # if there is data there. |
| 175 | self.timeout = 0.01 |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 176 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 177 | bb.utils.set_process_name("PRServ") |
| 178 | |
| 179 | # DB connection must be created after all forks |
| 180 | self.db = prserv.db.PRData(self.dbfile) |
| 181 | self.table = self.db["PRMAIN"] |
| 182 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 183 | logger.info("Started PRServer with DBfile: %s, IP: %s, PORT: %s, PID: %s" % |
| 184 | (self.dbfile, self.host, self.port, str(os.getpid()))) |
| 185 | |
| 186 | self.handlerthread.start() |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 187 | while not self.quitflag: |
| 188 | ready = select.select([self.fileno(), self.quitpipein], [], [], 30) |
| 189 | if self.quitflag: |
| 190 | break |
| 191 | if self.fileno() in ready[0]: |
| 192 | self.handle_request() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 193 | self.handlerthread.join() |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 194 | self.db.disconnect() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 195 | logger.info("PRServer: stopping...") |
| 196 | self.server_close() |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 197 | os.close(self.quitpipein) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 198 | return |
| 199 | |
| 200 | def start(self): |
| 201 | if self.daemon: |
| 202 | pid = self.daemonize() |
| 203 | else: |
| 204 | pid = self.fork() |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 205 | self.pid = pid |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 206 | |
| 207 | # Ensure both the parent sees this and the child from the work_forever log entry above |
| 208 | logger.info("Started PRServer with DBfile: %s, IP: %s, PORT: %s, PID: %s" % |
| 209 | (self.dbfile, self.host, self.port, str(pid))) |
| 210 | |
| 211 | def delpid(self): |
| 212 | os.remove(self.pidfile) |
| 213 | |
| 214 | def daemonize(self): |
| 215 | """ |
| 216 | See Advanced Programming in the UNIX, Sec 13.3 |
| 217 | """ |
| 218 | try: |
| 219 | pid = os.fork() |
| 220 | if pid > 0: |
| 221 | os.waitpid(pid, 0) |
| 222 | #parent return instead of exit to give control |
| 223 | return pid |
| 224 | except OSError as e: |
| 225 | raise Exception("%s [%d]" % (e.strerror, e.errno)) |
| 226 | |
| 227 | os.setsid() |
| 228 | """ |
| 229 | fork again to make sure the daemon is not session leader, |
| 230 | which prevents it from acquiring controlling terminal |
| 231 | """ |
| 232 | try: |
| 233 | pid = os.fork() |
| 234 | if pid > 0: #parent |
| 235 | os._exit(0) |
| 236 | except OSError as e: |
| 237 | raise Exception("%s [%d]" % (e.strerror, e.errno)) |
| 238 | |
| 239 | self.cleanup_handles() |
| 240 | os._exit(0) |
| 241 | |
| 242 | def fork(self): |
| 243 | try: |
| 244 | pid = os.fork() |
| 245 | if pid > 0: |
Brad Bishop | 1d80a2e | 2019-11-15 16:35:03 -0500 | [diff] [blame] | 246 | self.socket.close() # avoid ResourceWarning in parent |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 247 | return pid |
| 248 | except OSError as e: |
| 249 | raise Exception("%s [%d]" % (e.strerror, e.errno)) |
| 250 | |
| 251 | bb.utils.signal_on_parent_exit("SIGTERM") |
| 252 | self.cleanup_handles() |
| 253 | os._exit(0) |
| 254 | |
| 255 | def cleanup_handles(self): |
| 256 | signal.signal(signal.SIGINT, self.sigint_handler) |
| 257 | signal.signal(signal.SIGTERM, self.sigterm_handler) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 258 | os.chdir("/") |
| 259 | |
| 260 | sys.stdout.flush() |
| 261 | sys.stderr.flush() |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 262 | |
| 263 | # We could be called from a python thread with io.StringIO as |
| 264 | # stdout/stderr or it could be 'real' unix fd forking where we need |
| 265 | # to physically close the fds to prevent the program launching us from |
| 266 | # potentially hanging on a pipe. Handle both cases. |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 267 | si = open('/dev/null', 'r') |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 268 | try: |
| 269 | os.dup2(si.fileno(),sys.stdin.fileno()) |
| 270 | except (AttributeError, io.UnsupportedOperation): |
| 271 | sys.stdin = si |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 272 | so = open(self.logfile, 'a+') |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 273 | try: |
| 274 | os.dup2(so.fileno(),sys.stdout.fileno()) |
| 275 | except (AttributeError, io.UnsupportedOperation): |
| 276 | sys.stdout = so |
| 277 | try: |
| 278 | os.dup2(so.fileno(),sys.stderr.fileno()) |
| 279 | except (AttributeError, io.UnsupportedOperation): |
| 280 | sys.stderr = so |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 281 | |
| 282 | # Clear out all log handlers prior to the fork() to avoid calling |
| 283 | # event handlers not part of the PRserver |
| 284 | for logger_iter in logging.Logger.manager.loggerDict.keys(): |
| 285 | logging.getLogger(logger_iter).handlers = [] |
| 286 | |
| 287 | # Ensure logging makes it to the logfile |
| 288 | streamhandler = logging.StreamHandler() |
| 289 | streamhandler.setLevel(logging.DEBUG) |
| 290 | formatter = bb.msg.BBLogFormatter("%(levelname)s: %(message)s") |
| 291 | streamhandler.setFormatter(formatter) |
| 292 | logger.addHandler(streamhandler) |
| 293 | |
| 294 | # write pidfile |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 295 | pid = str(os.getpid()) |
| 296 | with open(self.pidfile, 'w') as pf: |
| 297 | pf.write("%s\n" % pid) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 298 | |
| 299 | self.work_forever() |
| 300 | self.delpid() |
| 301 | |
| 302 | class PRServSingleton(object): |
| 303 | def __init__(self, dbfile, logfile, interface): |
| 304 | self.dbfile = dbfile |
| 305 | self.logfile = logfile |
| 306 | self.interface = interface |
| 307 | self.host = None |
| 308 | self.port = None |
| 309 | |
| 310 | def start(self): |
| 311 | self.prserv = PRServer(self.dbfile, self.logfile, self.interface, daemon=False) |
| 312 | self.prserv.start() |
| 313 | self.host, self.port = self.prserv.getinfo() |
| 314 | |
| 315 | def getinfo(self): |
| 316 | return (self.host, self.port) |
| 317 | |
| 318 | class PRServerConnection(object): |
| 319 | def __init__(self, host, port): |
| 320 | if is_local_special(host, port): |
| 321 | host, port = singleton.getinfo() |
| 322 | self.host = host |
| 323 | self.port = port |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 324 | self.connection, self.transport = bb.server.xmlrpcclient._create_server(self.host, self.port) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 325 | |
| 326 | def terminate(self): |
| 327 | try: |
| 328 | logger.info("Terminating PRServer...") |
| 329 | self.connection.quit() |
| 330 | except Exception as exc: |
| 331 | sys.stderr.write("%s\n" % str(exc)) |
| 332 | |
| 333 | def getPR(self, version, pkgarch, checksum): |
| 334 | return self.connection.getPR(version, pkgarch, checksum) |
| 335 | |
| 336 | def ping(self): |
| 337 | return self.connection.ping() |
| 338 | |
| 339 | def export(self,version=None, pkgarch=None, checksum=None, colinfo=True): |
| 340 | return self.connection.export(version, pkgarch, checksum, colinfo) |
| 341 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 342 | def dump_db(self): |
| 343 | return self.connection.dump_db() |
| 344 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 345 | def importone(self, version, pkgarch, checksum, value): |
| 346 | return self.connection.importone(version, pkgarch, checksum, value) |
| 347 | |
| 348 | def getinfo(self): |
| 349 | return self.host, self.port |
| 350 | |
| 351 | def start_daemon(dbfile, host, port, logfile): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 352 | ip = socket.gethostbyname(host) |
| 353 | pidfile = PIDPREFIX % (ip, port) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 354 | try: |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 355 | with open(pidfile) as pf: |
| 356 | pid = int(pf.readline().strip()) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 357 | except IOError: |
| 358 | pid = None |
| 359 | |
| 360 | if pid: |
| 361 | sys.stderr.write("pidfile %s already exist. Daemon already running?\n" |
| 362 | % pidfile) |
| 363 | return 1 |
| 364 | |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 365 | server = PRServer(os.path.abspath(dbfile), os.path.abspath(logfile), (ip,port)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 366 | server.start() |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 367 | |
| 368 | # Sometimes, the port (i.e. localhost:0) indicated by the user does not match with |
| 369 | # the one the server actually is listening, so at least warn the user about it |
| 370 | _,rport = server.getinfo() |
| 371 | if port != rport: |
| 372 | sys.stdout.write("Server is listening at port %s instead of %s\n" |
| 373 | % (rport,port)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 374 | return 0 |
| 375 | |
| 376 | def stop_daemon(host, port): |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 377 | import glob |
| 378 | ip = socket.gethostbyname(host) |
| 379 | pidfile = PIDPREFIX % (ip, port) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 380 | try: |
Brad Bishop | 64c979e | 2019-11-04 13:55:29 -0500 | [diff] [blame] | 381 | with open(pidfile) as pf: |
| 382 | pid = int(pf.readline().strip()) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 383 | except IOError: |
| 384 | pid = None |
| 385 | |
| 386 | if not pid: |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 387 | # when server starts at port=0 (i.e. localhost:0), server actually takes another port, |
| 388 | # so at least advise the user which ports the corresponding server is listening |
| 389 | ports = [] |
| 390 | portstr = "" |
| 391 | for pf in glob.glob(PIDPREFIX % (ip,'*')): |
| 392 | bn = os.path.basename(pf) |
| 393 | root, _ = os.path.splitext(bn) |
| 394 | ports.append(root.split('_')[-1]) |
| 395 | if len(ports): |
| 396 | portstr = "Wrong port? Other ports listening at %s: %s" % (host, ' '.join(ports)) |
| 397 | |
| 398 | sys.stderr.write("pidfile %s does not exist. Daemon not running? %s\n" |
| 399 | % (pidfile,portstr)) |
| 400 | return 1 |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 401 | |
| 402 | try: |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 403 | PRServerConnection(ip, port).terminate() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 404 | except: |
| 405 | logger.critical("Stop PRService %s:%d failed" % (host,port)) |
| 406 | |
| 407 | try: |
| 408 | if pid: |
| 409 | wait_timeout = 0 |
| 410 | print("Waiting for pr-server to exit.") |
| 411 | while is_running(pid) and wait_timeout < 50: |
| 412 | time.sleep(0.1) |
| 413 | wait_timeout += 1 |
| 414 | |
| 415 | if is_running(pid): |
| 416 | print("Sending SIGTERM to pr-server.") |
| 417 | os.kill(pid,signal.SIGTERM) |
| 418 | time.sleep(0.1) |
| 419 | |
| 420 | if os.path.exists(pidfile): |
| 421 | os.remove(pidfile) |
| 422 | |
| 423 | except OSError as e: |
| 424 | err = str(e) |
| 425 | if err.find("No such process") <= 0: |
| 426 | raise e |
| 427 | |
| 428 | return 0 |
| 429 | |
| 430 | def is_running(pid): |
| 431 | try: |
| 432 | os.kill(pid, 0) |
| 433 | except OSError as err: |
| 434 | if err.errno == errno.ESRCH: |
| 435 | return False |
| 436 | return True |
| 437 | |
| 438 | def is_local_special(host, port): |
| 439 | if host.strip().upper() == 'localhost'.upper() and (not port): |
| 440 | return True |
| 441 | else: |
| 442 | return False |
| 443 | |
| 444 | class PRServiceConfigError(Exception): |
| 445 | pass |
| 446 | |
| 447 | def auto_start(d): |
| 448 | global singleton |
| 449 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 450 | host_params = list(filter(None, (d.getVar('PRSERV_HOST') or '').split(':'))) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 451 | if not host_params: |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 452 | # Shutdown any existing PR Server |
| 453 | auto_shutdown() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 454 | return None |
| 455 | |
| 456 | if len(host_params) != 2: |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 457 | # Shutdown any existing PR Server |
| 458 | auto_shutdown() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 459 | logger.critical('\n'.join(['PRSERV_HOST: incorrect format', |
| 460 | 'Usage: PRSERV_HOST = "<hostname>:<port>"'])) |
| 461 | raise PRServiceConfigError |
| 462 | |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 463 | if is_local_special(host_params[0], int(host_params[1])): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 464 | import bb.utils |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 465 | cachedir = (d.getVar("PERSISTENT_DIR") or d.getVar("CACHE")) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 466 | if not cachedir: |
| 467 | logger.critical("Please set the 'PERSISTENT_DIR' or 'CACHE' variable") |
| 468 | raise PRServiceConfigError |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 469 | dbfile = os.path.join(cachedir, "prserv.sqlite3") |
| 470 | logfile = os.path.join(cachedir, "prserv.log") |
Andrew Geissler | 82c905d | 2020-04-13 13:39:40 -0500 | [diff] [blame] | 471 | if singleton: |
| 472 | if singleton.dbfile != dbfile: |
| 473 | # Shutdown any existing PR Server as doesn't match config |
| 474 | auto_shutdown() |
| 475 | if not singleton: |
| 476 | bb.utils.mkdirhier(cachedir) |
| 477 | singleton = PRServSingleton(os.path.abspath(dbfile), os.path.abspath(logfile), ("localhost",0)) |
| 478 | singleton.start() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 479 | if singleton: |
| 480 | host, port = singleton.getinfo() |
| 481 | else: |
| 482 | host = host_params[0] |
| 483 | port = int(host_params[1]) |
| 484 | |
| 485 | try: |
| 486 | connection = PRServerConnection(host,port) |
| 487 | connection.ping() |
| 488 | realhost, realport = connection.getinfo() |
| 489 | return str(realhost) + ":" + str(realport) |
| 490 | |
| 491 | except Exception: |
| 492 | logger.critical("PRservice %s:%d not available" % (host, port)) |
| 493 | raise PRServiceConfigError |
| 494 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 495 | def auto_shutdown(): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 496 | global singleton |
| 497 | if singleton: |
| 498 | host, port = singleton.getinfo() |
| 499 | try: |
| 500 | PRServerConnection(host, port).terminate() |
| 501 | except: |
| 502 | logger.critical("Stop PRService %s:%d failed" % (host,port)) |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 503 | |
| 504 | try: |
| 505 | os.waitpid(singleton.prserv.pid, 0) |
| 506 | except ChildProcessError: |
| 507 | pass |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 508 | singleton = None |
| 509 | |
| 510 | def ping(host, port): |
| 511 | conn=PRServerConnection(host, port) |
| 512 | return conn.ping() |