def _start_wpa_supplicant(interface, config_filename): """Starts a babysat wpa_supplicant. Args: interface: The interface on which to start wpa_supplicant. config_filename: The filename of the wpa_supplicant configuration. Raises: BinWifiException: if wpa_supplicant fails to connect and also cannot be stopped to cleanup after the failure. Returns: Whether wpa_supplicant was started successfully. """ pid_filename = utils.get_filename('wpa_supplicant', utils.FILENAME_KIND.pid, interface, tmp=True) utils.log('Starting wpa_supplicant.') utils.babysit([ 'wpa_supplicant', '-Dnl80211', '-i', interface, '-c', config_filename ] + _hostapd_debug_options(), 'wpa_supplicant-%s' % interface, 10, pid_filename) # Wait for wpa_supplicant to start, and return False if it doesn't. i = j = 0 for i in xrange(100): if utils.check_pid(pid_filename): break sys.stderr.write('.') sys.stderr.flush() time.sleep(0.1) else: return False # wpa_supplicant_cli returns success on command timeouts. If we time this # perfectly and manage to connect but then wpa_supplicant dies right after, # we'd think it succeeded. So sleep a bit to try to give wpa_supplicant a # chance to die from its error before we try to connect to it. time.sleep(0.5) for j in xrange(50): if not utils.check_pid(pid_filename): utils.log('wpa_supplicant process died.') return False if _is_wpa_supplicant_running(interface): utils.log('wpa_supplicant process started after %.1fs', (i + j) / 10.0) break sys.stderr.write('.') sys.stderr.flush() time.sleep(0.1) else: utils.log('failed after %.1fs', (i + j) / 10.0) return False return _wait_for_wpa_supplicant_to_associate(interface)
def DeletePost(c, connection, c_id, db_conn, db_cur, argv): if len(argv) != 1: msg = 'delete-post <post-id>\n' elif not connection.check_login(c_id): msg = 'Please login first.\n' else: pid = utils.check_pid(argv[0]) if not pid: msg = 'Post does not exist.\n' c.sendall(msg.encode('utf-8')) return db_cur.execute(f''' select author from post where pid={argv[0]} ''') author = db_cur.fetchone() if author is None: msg = 'Post does not exist.\n' elif author[0] != connection.get_uname(c_id): msg = 'Not the post owner.\n' else: db_cur.execute(f'delete from post where pid={argv[0]}') db_conn.commit() msg = 'Delete successfully.\n' c.sendall(msg.encode('utf-8'))
def Comment(c, connection, c_id, db_conn, db_cur, argv): if len(argv) < 2: msg = 'comment <post-id> <comment>\n' elif not connection.check_login(c_id): msg = 'Please login first.\n' else: pid = utils.check_pid(argv[0]) if not pid: msg = 'Post does not exist.\n' c.sendall(msg.encode('utf-8')) return db_cur.execute(f''' select count(*) from post where pid={pid} ''') cnt = db_cur.fetchone()[0] if cnt == 0: msg = 'Post does not exist.\n' else: try: uname = connection.get_uname(c_id) content = ' '.join(argv[1:]) db_cur.execute(f''' insert into comment (author, content, pid) values ("{uname}", "{content}", "{pid}") ''') db_conn.commit() msg = 'Comment successfully.\n' except: msg = 'Post does not exist.\n' c.sendall(msg.encode('utf-8'))
def Read(c, db_cur, argv): if len(argv) != 1: msg = 'read <post-id>\n' else: pid = utils.check_pid(argv[0]) if not pid: msg = 'Post does not exist.\n' c.sendall(msg.encode('utf-8')) return db_cur.execute(f''' select author, title, date_time, content from post where pid={pid} ''') res = db_cur.fetchone() if res is None: msg = 'Post does not exist.\n' else: msg = f"Author\t:{res[0]}\nTitle\t:{res[1]}\nDate\t:{res[2].split(' ')[0]}\n--\n{res[3]}\n--\n" db_cur.execute(f''' select author, content from comment where pid={pid} order by date(date_time) desc ''') res = db_cur.fetchall() for row in res: msg += f"{row[0]}: {row[1]}\n" c.sendall(msg.encode('utf-8'))
def dashboard(): if utils.needs_user(): return flask.redirect(flask.url_for('setup')) if ('logged_in' not in flask.session) or (not flask.session['logged_in']): return flask.redirect(flask.url_for('login')) running = utils.check_pid(Config["pidfile"]) tstate = utils.get_state("alarm_thread") tutime_s = "" trunning = False if tstate: trunning, tutime = tstate tutime_s = time.strftime("%c", time.localtime(tutime)) thread_state = { "running": bool(trunning), "utime": tutime_s} utime = time.strftime("%c", time.localtime()) state_text = "Not Runnning" flags = { "alarm": False, "armed": False, "disarmed": False, "tripped": False, "faulted": False} state_data = None alarm_state_d = utils.get_state("alarm") if alarm_state_d: alarm_state, state_time_i = alarm_state_d if alarm_state is not None: utime = time.strftime("%c", time.localtime(state_time_i)) state_text = Alarm.ALARM_STATES[alarm_state] flags["alarm"] = alarm_state == Alarm.ALARMED flags["disarmed"] = alarm_state == Alarm.DISARMED flags["tripped"] = alarm_state == Alarm.TRIPPED flags["faulted"] = alarm_state == Alarm.FAULT flags["armed"] = alarm_state == Alarm.ARMED states = utils.get_states_not("alarm", "alarm_thread") state_data = { state['key']: { 'data': state['data'], 'time': time.strftime("%c", time.localtime(state['state_time']))} for state in states} interfaces = utils.get_interfaces() return flask.render_template( 'dashboard.j2', flags=flags, running=running, thread_state=thread_state, state_text=state_text, state_data=state_data, utime=utime, interfaces=interfaces, smbio=smbio)
def dashboard(): if utils.needs_user(): return flask.redirect(flask.url_for('setup')) if ('logged_in' not in flask.session) or (not flask.session['logged_in']): return flask.redirect(flask.url_for('login')) running = utils.check_pid(Config["pidfile"]) tstate = utils.get_state("alarm_thread") tutime_s = "" trunning = False if tstate: trunning, tutime = tstate tutime_s = time.strftime("%c", time.localtime(tutime)) thread_state = {"running": bool(trunning), "utime": tutime_s} utime = time.strftime("%c", time.localtime()) state_text = "Not Runnning" flags = { "alarm": False, "armed": False, "disarmed": False, "tripped": False, "faulted": False } state_data = None alarm_state_d = utils.get_state("alarm") if alarm_state_d: alarm_state, state_time_i = alarm_state_d if alarm_state is not None: utime = time.strftime("%c", time.localtime(state_time_i)) state_text = Alarm.ALARM_STATES[alarm_state] flags["alarm"] = alarm_state == Alarm.ALARMED flags["disarmed"] = alarm_state == Alarm.DISARMED flags["tripped"] = alarm_state == Alarm.TRIPPED flags["faulted"] = alarm_state == Alarm.FAULT flags["armed"] = alarm_state == Alarm.ARMED states = utils.get_states_not("alarm", "alarm_thread") state_data = { state['key']: { 'data': state['data'], 'time': time.strftime("%c", time.localtime(state['state_time'])) } for state in states } interfaces = utils.get_interfaces() return flask.render_template('dashboard.j2', flags=flags, running=running, thread_state=thread_state, state_text=state_text, state_data=state_data, utime=utime, interfaces=interfaces, smbio=smbio)
def main(): logger = get_logger() if len(sys.argv) != 2: print "Usage: python stop_nodes.py <all|port>" return port_to_stop = sys.argv[1] if port_to_stop == "all": port_to_stop = 0 else: port_to_stop = int(port_to_stop) instances = get_running_instances() if len(instances) == 0: logger.info("no running instances") return # stop instances to_kill = [] for instance in instances: pid = instance['pid'] port = instance['port'] remove_pid_file = False if port_to_stop == 0 or port == port_to_stop: to_kill.append(pid) logger.debug("stop: port=%r pid=%r", port, pid) try: os.kill(pid, signal.SIGTERM) except OSError as e: if e.args[0] == 3 and e.args[1] == 'No such process': remove_pid_file = True logger.error("missing node process: port=%r pid=%r", port, pid) except Exception as e: logger.exception("error: %r", e.args) if remove_pid_file: logger.info("remove pid file: %s", instance['pid_file_path']) os.remove(instance['pid_file_path']) #wait until all processes are stopped while True: try: has_running = False for pid in to_kill: if check_pid(pid, "acestreamengine"): logger.info("still running, wait: pid=%r", pid) has_running = True break if has_running: time.sleep(1.0) else: break except KeyboardInterrupt: break
def stop(self): utils.close_named_pipe(self.fin) utils.close_named_pipe(self.fout) pid = self.process.pid self.process.kill() # kill -9 !!!!!!!!!!!!!!!!!!!! self.process.wait() while utils.check_pid(pid): print 'waiting for game to die' time.sleep(0.01) # 10 millis if not INTEGRATE_HUMAN_FEEDBACK: # We've already recorded this game if we are integrating feedback. self.log_frames( ) # Keep this at end to avoid stalling atari close.
def check_download_alive(download): if not utils.check_pid(download.pid_plowdown): # utils.kill_proc_tree(download.pid_python) log.log(__name__, sys._getframe().f_code.co_name, 'Process %s for download %s killed for inactivity ...\r\n' % ( str(download.pid_python), download.name), log.LEVEL_DEBUG) download.pid_plowdown = 0 download.pid_python = 0 download.status = Download.STATUS_WAITING download.time_left = 0 download.average_speed = 0 download.logs = 'updated by check_download_alive_method\r\nProcess killed by inactivity ...\r\n' ManageDownload.update_download(download, True)
def UpdatePost(c, connection, c_id, db_conn, db_cur, argv): if len(argv) < 3: msg = 'update-post <post-id> --title/content <new>\n' elif not connection.check_login(c_id): msg = 'Please login first.\n' else: pid = utils.check_pid(argv[0]) if not pid: msg = 'Post does not exist.\n' c.sendall(msg.encode('utf-8')) return if argv[1] == '--title' or argv[1] == '--content': update_type = argv[1][2:] new_content = ' '.join(argv[2:]).replace('<br>', '\n') db_cur.execute(f''' select author from post where pid={pid} ''') author = db_cur.fetchone() if author is None: msg = 'Post does not exist.\n' elif author[0] != connection.get_uname(c_id): msg = 'Not the post owner.\n' else: db_cur.execute(f''' update post set {update_type} = "{new_content}" where pid={argv[0]} ''') db_conn.commit() msg = 'Update successfully.\n' else: msg = 'update-post <post-id> --title/content <new>\n' c.sendall(msg.encode('utf-8'))
def _start_hostapd(interface, config_filename, band, ssid): """Starts a babysat hostapd. Args: interface: The interface on which to start hostapd. config_filename: The filename of the hostapd configuration. band: The band on which hostapd is being started. ssid: The SSID with which hostapd is being started. Returns: Whether hostapd was started successfully. """ aggfiles = glob.glob('/sys/kernel/debug/ieee80211/phy*/' + 'netdev:%s/default_agg_timeout' % interface) if not aggfiles: # This can happen on non-mac80211 interfaces. utils.log('agg_timeout: no default_agg_timeout files for %r', interface) else: if experiment.enabled('WifiShortAggTimeout'): utils.log('Using short agg_timeout.') agg = 500 elif experiment.enabled('WifiNoAggTimeout'): utils.log('Disabling agg_timeout.') agg = 0 else: utils.log('Using default long agg_timeout.') agg = 5000 for aggfile in aggfiles: open(aggfile, 'w').write(str(agg)) pid_filename = utils.get_filename('hostapd', utils.FILENAME_KIND.pid, interface, tmp=True) alivemonitor_filename = utils.get_filename('hostapd', utils.FILENAME_KIND.alive, interface, tmp=True) # Don't use alivemonitor on Windcharger since no waveguide. b/32376077 if _is_wind_charger() or experiment.enabled('WifiNoAliveMonitor'): alive_monitor = [] else: alive_monitor = [ 'alivemonitor', alivemonitor_filename, '30', '2', '65' ] utils.log('Starting hostapd.') utils.babysit( alive_monitor + [ 'hostapd', '-A', alivemonitor_filename, '-F', _FINGERPRINTS_DIRECTORY ] + bandsteering.hostapd_options(band, ssid) + _hostapd_debug_options() + [config_filename], 'hostapd-%s' % interface, 10, pid_filename) # Wait for hostapd to start, and return False if it doesn't. i = j = 0 for i in xrange(100): if utils.check_pid(pid_filename): break sys.stderr.write('.') sys.stderr.flush() time.sleep(0.1) else: return False # hostapd_cli returns success on command timeouts. If we time this perfectly # and manage to connect but then hostapd dies right after, we'd think it # succeeded. So sleep a bit to try to give hostapd a chance to die from its # error before we try to connect to it. time.sleep(0.5) for j in xrange(100): if not utils.check_pid(pid_filename): break if _is_hostapd_running(interface): utils.log('started after %.1fs', (i + j) / 10.0) return True sys.stderr.write('.') sys.stderr.flush() time.sleep(0.1) utils.log('failed after %.1fs', (i + j) / 10.0) return False
def _is_alive(self): if not os.path.exists(self._pid_path): return False pid = int(open(self._pid_path, 'r').read()) return utils.check_pid(pid)