| 15 | import logging |
| 16 | |
| 17 | class SiblingKiller: |
| 18 | |
| 19 | def __init__(self, port, ping_timeout): |
| 20 | self.all_processes = self.ps_dash_w() |
| 21 | self.all_pids = self.all_process_ids() |
| 22 | self.__allow_serving = False |
| 23 | self.__my_pid = self.my_process_id() |
| 24 | self.port = port |
| 25 | self.ping_timeout = ping_timeout |
| 26 | logging.debug(f"Sibling killer: my process id = {self.__my_pid}") |
| 27 | |
| 28 | |
| 29 | def allow_serving(self): |
| 30 | return self.__allow_serving |
| 31 | |
| 32 | def give_process_time_to_kill_port_user(self): |
| 33 | sleep(5) |
| 34 | |
| 35 | |
| 36 | def kill_siblings(self): |
| 37 | """ |
| 38 | The idea is to get the list of all processes by the current user, check which one of them is using the port. |
| 39 | If there is such a process, let's wait for 10 seconds for it to start serving, if it doesn't, kill it. |
| 40 | |
| 41 | If there is NO such process, let's see if there is a process with the same name as us but with a lower process id. |
| 42 | We shall wait for 10 seconds for it to start, if it doesn't, kill it. |
| 43 | |
| 44 | If we are the process with the same name as ours and with the lowest process id, let's start serving and kill everyone else. |
| 45 | """ |
| 46 | |
| 47 | if self.wait_for_server(): |
| 48 | self.__allow_serving = False |
| 49 | logging.debug("There is a server that is currently serving on our port... Disallowing to start a new one") |
| 50 | return |
| 51 | |
| 52 | logging.debug("There are no servers that are currently serving. Will try to kill our siblings.") |
| 53 | |
| 54 | |
| 55 | sibs = list(self.siblings()) |
| 56 | |
| 57 | for sibling in sibs: |
| 58 | logging.debug(f"Checking whether we should kill sibling id: {sibling}") |
| 59 | |
| 60 | self.give_process_time_to_kill_port_user() |
| 61 | |
| 62 | if self.wait_for_server(): |
| 63 | serving_pid = self.serving_process_id() |
| 64 | if serving_pid: |
| 65 | logging.debug(f"There is a serving sibling with process id: {serving_pid}") |
| 66 | self.kill(pids=list(map(lambda x: x != serving_pid, sibs))) |
| 67 | self.__allow_serving = False |
| 68 | return |
| 69 | else: |
| 70 | self.kill(pid=sibling) |
| 71 | |
| 72 | self.kill_process_on_port() # changes __allow_serving to True if the process was alive and serving |
| 73 | |
| 74 | |