def main(): wait_xxnet_exit() update_environment() time.sleep(2) xlog.info("setup start run new launcher") run_new_start_script()
def run(last_run_version): if config.get(["modules", "launcher", "auto_start"], 0): import autorun autorun.enable() if os.path.isdir(os.path.join(top_path, 'launcher')): shutil.rmtree(os.path.join( top_path, 'launcher')) # launcher is for auto-update from 2.X if older_or_equal(last_run_version, '3.0.4'): xlog.info("migrating to 3.x.x") for filename in os.listdir(top_path): filepath = os.path.join(top_path, filename) if os.path.isfile(filepath): if sys.platform != 'win32' and filename == 'start': st = os.stat(filepath) os.chmod(filepath, st.st_mode | stat.S_IEXEC) if filename in [ 'start.sh', 'start.command', 'start.lnk', 'LICENSE.txt', 'download.md', 'version.txt', 'xxnet', 'xxnet.bat', 'xxnet.vbs' ]: os.remove(filepath) else: if filename in [ 'goagent', 'python27', 'gae_proxy', 'php_proxy', 'x_tunnel', 'python3', 'Python3', 'lib', 'SwitchySharp' ]: shutil.rmtree(filepath)
def req_update_handler(self): req = urlparse.urlparse(self.path).query reqs = urlparse.parse_qs(req, keep_blank_values=True) data = '' if reqs['cmd'] == ['get_info']: data = update_from_github.update_info if data == '' or data[0] != '{': data = '{"type":"%s"}' % data elif reqs['cmd'] == ['set_info']: update_from_github.update_info = reqs['info'][0] data = '{"res":"success"}' elif reqs['cmd'] == ['start_check']: update_from_github.init_update_info(reqs['check_update'][0]) update.check_update() data = '{"res":"success"}' elif reqs['cmd'] == ['get_progress']: data = json.dumps(update_from_github.progress) elif reqs['cmd'] == ['get_new_version']: current_version = update_from_github.current_version() github_versions = update_from_github.get_github_versions() data = '{"res":"success", "test_version":"%s", "stable_version":"%s", "current_version":"%s"}' % ( github_versions[0][1], github_versions[1][1], current_version) xlog.info("%s", data) elif reqs['cmd'] == ['update_version']: version = reqs['version'][0] update_from_github.start_update_version(version) data = '{"res":"success"}' self.send_response('text/html', data)
def windowWillClose_(self, notification): executeResult = subprocess.check_output( ['networksetup', '-listallnetworkservices']) services = executeResult.split('\n') services = filter(lambda service: service and service.find( '*') == -1 and getProxyState(service) != 'disable', services) # Remove disabled services and empty lines if len(services) > 0: try: map(helperDisableAutoProxy, services) map(helperDisableGlobalProxy, services) except: disableAutoProxyCommand = ';'.join( map(getDisableAutoProxyCommand, services)) disableGlobalProxyCommand = ';'.join( map(getDisableGlobalProxyCommand, services)) executeCommand = 'do shell script "%s;%s" with administrator privileges' % ( disableAutoProxyCommand, disableGlobalProxyCommand) xlog.info("try disable proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) module_init.stop_all() os._exit(0) AppKit.NSApp.terminate_(self)
def check_update(): try: update_rule = config.get(["update", "check_update"], "stable") if update_rule == "dont-check": return check_push_update() if update_rule != "stable" and update_rule != "test": return versions = update_from_github.get_github_versions() current_version = update_from_github.current_version() if update_rule == "test": if LooseVersion(current_version) < LooseVersion(versions[0][1]): xlog.info("update to test version %s", versions[0][1]) update_from_github.update_version(versions[0][1]) elif update_rule == "stable": if LooseVersion(current_version) < LooseVersion(versions[1][1]): xlog.info("update to stable version %s", versions[1][1]) update_from_github.update_version(versions[1][1]) except IOError as e: xlog.warn("check update fail:%r", e) except Exception as e: xlog.exception("check_update fail:%r", e)
def main(): # change path to launcher global __file__ __file__ = os.path.abspath(__file__) if os.path.islink(__file__): __file__ = getattr(os, 'readlink', lambda x: x)(__file__) os.chdir(os.path.dirname(os.path.abspath(__file__))) xlog.info("start XX-Net %s", update_from_github.current_version()) web_control.confirm_xxnet_exit() setup_win_python.check_setup() module_init.start_all_auto() web_control.start() if has_desktop and config.get(["modules", "launcher", "popup_webui"], 1) == 1: host_port = config.get(["modules", "launcher", "control_port"], 8085) import webbrowser webbrowser.open("http://127.0.0.1:%s/" % host_port) update.start() if config.get(["modules", "launcher", "show_systray"], 1): sys_tray.serve_forever() else: while True: time.sleep(100) module_init.stop_all() sys.exit()
def download_overwrite_new_version(xxnet_version): xxnet_url = 'https://codeload.github.com/XX-net/XX-Net/zip/%s' % xxnet_version xxnet_zip_file = os.path.join(download_path, "XX-Net-%s.zip" % xxnet_version) xxnet_unzip_path = os.path.join(download_path, "XX-Net-%s" % xxnet_version) if not download_file(xxnet_url, xxnet_zip_file): raise "download xxnet zip fail:" % download_path with zipfile.ZipFile(xxnet_zip_file, "r") as dz: dz.extractall(download_path) dz.close() if config.get(["update", "uuid"], '') != 'test': for root, subdirs, files in os.walk(xxnet_unzip_path): #print "root:", root relate_path = root[len(xxnet_unzip_path)+1:] for subdir in subdirs: target_path = os.path.join(root_path, relate_path, subdir) if not os.path.isdir(target_path): xlog.info("mkdir %s", target_path) os.mkdir(target_path) for filename in files: src_file = os.path.join(root, filename) dst_file = os.path.join(root_path, relate_path, filename) if not os.path.isfile(dst_file) or sha1_file(src_file) != sha1_file(dst_file): shutil.copy(src_file, dst_file) xlog.info("copy %s => %s", src_file, dst_file) os.remove(xxnet_zip_file) shutil.rmtree(xxnet_unzip_path, ignore_errors=True)
def download_overwrite_new_version(xxnet_version): xxnet_url = 'https://codeload.github.com/XX-net/XX-Net/zip/%s' % xxnet_version xxnet_zip_file = os.path.join(download_path, "XX-Net-%s.zip" % xxnet_version) xxnet_unzip_path = os.path.join(download_path, "XX-Net-%s" % xxnet_version) if not download_file(xxnet_url, xxnet_zip_file): raise "download xxnet zip fail:" % download_path with zipfile.ZipFile(xxnet_zip_file, "r") as dz: dz.extractall(download_path) dz.close() if config.get(["update", "uuid"], '') != 'test': for root, subdirs, files in os.walk(xxnet_unzip_path): #print "root:", root relate_path = root[len(xxnet_unzip_path) + 1:] for subdir in subdirs: target_path = os.path.join(root_path, relate_path, subdir) if not os.path.isdir(target_path): xlog.info("mkdir %s", target_path) os.mkdir(target_path) for filename in files: src_file = os.path.join(root, filename) dst_file = os.path.join(root_path, relate_path, filename) if not os.path.isfile(dst_file) or sha1_file( src_file) != sha1_file(dst_file): shutil.copy(src_file, dst_file) xlog.info("copy %s => %s", src_file, dst_file) os.remove(xxnet_zip_file) shutil.rmtree(xxnet_unzip_path, ignore_errors=True)
def stop(module): try: if module not in proc_handler: xlog.error("module %s not running", module) return if os.path.isfile(os.path.join(root_path, module, "__init__.py")): _start = proc_handler[module]["imp"].start xlog.debug("start to terminate %s module", module) _start.client.terminate() xlog.debug("module %s stopping", module) while _start.client.ready: time.sleep(0.1) else: proc_handler[module]["proc"].terminate() # Sends SIGTERM proc_handler[module]["proc"].wait() del proc_handler[module] xlog.info("module %s stopped", module) except Exception as e: xlog.exception("stop module %s fail:%s", module, e) return "Except:%s" % e return "stop success."
def get_uuid(): if need_new_uuid(): generate_new_uuid() xx_net_uuid = config.get(["update", "uuid"]) xlog.info("get uuid:%s", xx_net_uuid) return xx_net_uuid
def run(last_run_version): if config.get(["modules", "launcher", "auto_start"], 0): import autorun autorun.enable() if os.path.isdir(os.path.join(top_path, 'launcher')): shutil.rmtree(os.path.join( top_path, 'launcher')) # launcher is for auto-update from 2.X if older_or_equal(last_run_version, '3.0.4'): xlog.info("migrating to 3.x.x") for filename in os.listdir(top_path): filepath = os.path.join(top_path, filename) if os.path.isfile(filepath): if sys.platform != 'win32' and filename == 'start': st = os.stat(filepath) os.chmod(filepath, st.st_mode | stat.S_IEXEC) if not filename.startswith('.') and filename not in [ 'README.md', 'start', 'start.bat', 'start.vbs' ]: os.remove(filepath) else: if not filename.startswith('.') and filename not in [ 'code', 'data' ]: shutil.rmtree(filepath)
def enableAutoProxy_(self, _): cmd1 = "networksetup -setautoproxyurl Ethernet \\\"http://127.0.0.1:8086/proxy.pac\\\"" cmd2 = "networksetup -setautoproxyurl \\\"Thunderbolt Ethernet\\\" \\\"http://127.0.0.1:8086/proxy.pac\\\"" cmd3 = "networksetup -setautoproxyurl Wi-Fi \\\"http://127.0.0.1:8086/proxy.pac\\\"" exec_command = "%s;%s;%s" % (cmd1, cmd2, cmd3) admin_command = """osascript -e 'do shell script "%s" with administrator privileges' """ % exec_command cmd = admin_command.encode('utf-8') xlog.info("try enable proxy:%s", cmd) os.system(cmd)
def disableProxy_(self, _): disableProxyCommand = self.getDisableProxyCommand() rootCommand = """osascript -e 'do shell script "%s" with administrator privileges' """ % disableProxyCommand executeCommand = rootCommand.encode('utf-8') xlog.info("try disable proxy:%s", executeCommand) os.system(executeCommand) self.updateStatusBarMenu() self.updateConfig('disable')
def add(name, cmd): file_content = plist_template % cmd xlog.info("create file:%s", plist_file_path) if not os.path.isdir(launch_path): os.mkdir(launch_path, 0755) with open(plist_file_path, "w") as f: f.write(file_content)
def update_version(version): global update_progress try: download_overwrite_new_version(version) progress["update_status"] = "Restarting" xlog.info("update try restart xxnet") restart_xxnet() except Exception as e: xlog.warn("update version %s fail:%r", version, e)
def enableGlobalProxy_(self, _): disableAutoProxyCommand = self.getDisableAutoProxyCommand(currentService) enableGlobalProxyCommand = self.getEnableGlobalProxyCommand(currentService) rootCommand = """osascript -e 'do shell script "%s;%s" with administrator privileges' """ % (disableAutoProxyCommand, enableGlobalProxyCommand) executeCommand = rootCommand.encode('utf-8') xlog.info("try enable global proxy:%s", executeCommand) os.system(executeCommand) self.updateStatusBarMenu() self.updateConfig('gae')
def disableProxy_(self, _): cmd1 = "networksetup -setwebproxystate Ethernet off" cmd2 = "networksetup -setwebproxystate Wi-Fi off" cmd3 = "networksetup -setsecurewebproxystate Ethernet off" cmd4 = "networksetup -setsecurewebproxystate Wi-Fi off" exec_command = "%s;%s;%s;%s" % (cmd1, cmd2, cmd3, cmd4) admin_command = """osascript -e 'do shell script "%s" with administrator privileges' """ % exec_command cmd = admin_command.encode('utf-8') xlog.info("try disable proxy:%s", cmd) os.system(cmd)
def stop(): global process, server if process == 0: return xlog.info("begin to exit web control") server.shutdown() server.server_close() process.join() xlog.info("launcher web control exited.") process = 0
def check_new_machine(): current_path = os.path.dirname(os.path.abspath(__file__)) if current_path != config.get(["update", "last_path"], ""): config.set(["update", "last_path"], current_path) config.save() if sys.platform == "win32" and platform.release() == "XP": notify_install_tcpz_for_winXp() xlog.info("generate desktop shortcut") create_desktop_shortcut()
def disableProxy_(self, _): try: helperDisableAutoProxy(currentService) helperDisableGlobalProxy(currentService) except: disableAutoProxyCommand = getDisableAutoProxyCommand(currentService) disableGlobalProxyCommand = getDisableGlobalProxyCommand(currentService) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, disableGlobalProxyCommand) xlog.info("try disable proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) self.updateStatusBarMenu()
def start_all_auto(): for module in config.config["modules"]: if module == "launcher": continue if not os.path.isdir(os.path.join(root_path, module)): continue if "auto_start" in config.config['modules'][module] and config.config['modules'][module]["auto_start"]: start_time = time.time() start(module) # web_control.confirm_module_ready(config.get(["modules", module, "control_port"], 0)) finished_time = time.time() xlog.info("start %s time cost:%d ms", module, (finished_time - start_time) * 1000)
def enableGlobalProxy_(self, _): cmd1 = "networksetup -setwebproxy Ethernet 127.0.0.1 8087" cmd2 = "networksetup -setwebproxy \\\"Thunderbolt Ethernet\\\" 127.0.0.1 8087" cmd3 = "networksetup -setwebproxy Wi-Fi 127.0.0.1 8087" cmd4 = "networksetup -setsecurewebproxy Ethernet 127.0.0.1 8087" cmd5 = "networksetup -setsecurewebproxy \\\"Thunderbolt Ethernet\\\" 127.0.0.1 8087" cmd6 = "networksetup -setsecurewebproxy Wi-Fi 127.0.0.1 8087" exec_command = "%s;%s;%s;%s;%s;%s" % (cmd1, cmd2, cmd3, cmd4, cmd5, cmd6) admin_command = """osascript -e 'do shell script "%s" with administrator privileges' """ % exec_command cmd = admin_command.encode('utf-8') xlog.info("try enable proxy:%s", cmd) os.system(cmd)
def setupHelper(): try: with open(os.devnull) as devnull: subprocess.check_call(helper_path, stderr=devnull) except: cpCommand = "cp \\\"%s\\\" \\\"%s\\\"" % (os.path.join(current_path, 'mac_helper'), helper_path) chmodCommand = "chmod 4777 \\\"%s\\\"" % helper_path chownCommand = "chown root \\\"%s\\\"" % helper_path rootCommand = """osascript -e 'do shell script "%s;%s;%s" with administrator privileges' """ % (cpCommand, chmodCommand, chownCommand) executeCommand = rootCommand.encode('utf-8') xlog.info("try setup helper:%s", executeCommand) os.system(executeCommand)
def setupHelper(): try: with open(os.devnull) as devnull: subprocess.check_call(helper_path, stderr=devnull) except: rmCommand = "rm \\\"%s\\\"" % helper_path cpCommand = "cp \\\"%s\\\" \\\"%s\\\"" % (os.path.join(current_path, 'mac_helper'), helper_path) chmodCommand = "chmod 4755 \\\"%s\\\"" % helper_path chownCommand = "chown root \\\"%s\\\"" % helper_path executeCommand = 'do shell script "%s;%s;%s;%s" with administrator privileges' % (rmCommand, cpCommand, chmodCommand, chownCommand) xlog.info("try setup helper:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand])
def disableProxy_(self, _): try: helperDisableAutoProxy(currentService) helperDisableGlobalProxy(currentService) except: disableAutoProxyCommand = getDisableAutoProxyCommand(currentService) disableGlobalProxyCommand = getDisableGlobalProxyCommand(currentService) rootCommand = """osascript -e 'do shell script "%s;%s" with administrator privileges' """ % (disableAutoProxyCommand, disableGlobalProxyCommand) executeCommand = rootCommand.encode('utf-8') xlog.info("try disable proxy:%s", executeCommand) os.system(executeCommand) self.updateStatusBarMenu()
def download_file(url, file): try: xlog.info("download %s to %s", url, file) req = opener.open(url) CHUNK = 16 * 1024 with open(file, 'wb') as fp: while True: chunk = req.read(CHUNK) if not chunk: break fp.write(chunk) return True except: xlog.info("download %s to %s fail", url, file) return False
def enableGlobalProxy_(self, _): try: helperDisableAutoProxy(currentService) helperEnableGlobalProxy(currentService) except: disableAutoProxyCommand = getDisableAutoProxyCommand(currentService) enableGlobalProxyCommand = getEnableGlobalProxyCommand(currentService) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, enableGlobalProxyCommand) xlog.info("try enable global proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) config.set(["modules", "launcher", "proxy"], "gae") config.save() self.updateStatusBarMenu()
def setupHelper(): try: with open(os.devnull) as devnull: subprocess.check_call(helper_path, stderr=devnull) except: cpCommand = "cp \\\"%s\\\" \\\"%s\\\"" % (os.path.join( current_path, 'mac_helper'), helper_path) chmodCommand = "chmod 4777 \\\"%s\\\"" % helper_path chownCommand = "chown root \\\"%s\\\"" % helper_path rootCommand = """osascript -e 'do shell script "%s;%s;%s" with administrator privileges' """ % ( cpCommand, chmodCommand, chownCommand) executeCommand = rootCommand.encode('utf-8') xlog.info("try setup helper:%s", executeCommand) os.system(executeCommand)
def enableAutoProxy_(self, _): try: helperDisableGlobalProxy(currentService) helperEnableAutoProxy(currentService) except: disableGlobalProxyCommand = getDisableGlobalProxyCommand( currentService) enableAutoProxyCommand = getEnableAutoProxyCommand(currentService) rootCommand = """osascript -e 'do shell script "%s;%s" with administrator privileges' """ % ( disableGlobalProxyCommand, enableAutoProxyCommand) executeCommand = rootCommand.encode('utf-8') xlog.info("try enable auto proxy:%s", executeCommand) os.system(executeCommand) self.updateStatusBarMenu()
def req_update_handler(self): req = urlparse.urlparse(self.path).query reqs = urlparse.parse_qs(req, keep_blank_values=True) data = '' if reqs['cmd'] == ['get_progress']: data = json.dumps(update_from_github.progress) elif reqs['cmd'] == ['get_new_version']: current_version = update_from_github.current_version() github_versions = update_from_github.get_github_versions() data = '{"res":"success", "test_version":"%s", "stable_version":"%s", "current_version":"%s"}' % (github_versions[0][1], github_versions[1][1], current_version) xlog.info("%s", data) elif reqs['cmd'] == ['update_version']: version = reqs['version'][0] update_from_github.start_update_version(version) data = '{"res":"success"}' self.send_response('text/html', data)
def download_file(url, filename): if url not in progress: progress[url] = {} progress[url]["status"] = "downloading" progress[url]["size"] = 1 progress[url]["downloaded"] = 0 else: if progress[url]["status"] == "downloading": xlog.warn("url in downloading, %s", url) return False for i in range(0, 2): try: xlog.info("download %s to %s, retry:%d", url, filename, i) opener = get_opener(i) req = opener.open(url, timeout=30) progress[url]["size"] = int(req.headers.get('content-length') or 0) chunk_len = 65536 downloaded = 0 with open(filename, 'wb') as fp: while True: chunk = req.read(chunk_len) if not chunk: break fp.write(chunk) downloaded += len(chunk) progress[url]["downloaded"] = downloaded if downloaded != progress[url]["size"]: xlog.warn("download size:%d, need size:%d, download fail.", downloaded, progress[url]["size"]) continue else: progress[url]["status"] = "finished" return True except (urllib2.URLError, ssl.SSLError) as e: xlog.warn("download %s to %s URL fail:%r", url, filename, e) continue except Exception as e: xlog.exception("download %s to %s fail:%r", url, filename, e) continue progress[url]["status"] = "failed" return False
def run(last_run_version): if config.get(["modules", "launcher", "auto_start"], 0): import autorun autorun.enable() if older_or_equal(last_run_version, '3.0.4'): xlog.info("migrating to 3.0.5") for filename in os.listdir(top_path): filepath = os.path.join(top_path, filename) if os.path.isfile(filepath): if sys.platform != 'win32' and filename == 'xxnet': st = os.stat(filepath) os.chmod(filepath, st.st_mode | stat.S_IEXEC) if not filename.startswith('.') and filename not in ['README.md', 'xxnet', 'xxnet.bat', 'xxnet.vbs']: os.remove(filepath) else: if not filename.startswith('.') and filename not in ['code', 'data']: shutil.rmtree(filepath)
def download_file(url, file): if url not in download_progress: download_progress[url] = {} download_progress[url]["status"] = "downloading" else: if download_progress[url]["status"] == "downloading": xlog.warn("url in downloading, %s", url) return False for i in range(0, 2): try: xlog.info("download %s to %s, retry:%d", url, file, i) opener = get_opener(i) req = opener.open(url) download_progress[url]["size"] = int( req.headers.get('content-length') or 0) CHUNK = 16 * 1024 downloaded = 0 with open(file, 'wb') as fp: while True: chunk = req.read(CHUNK) if not chunk: break fp.write(chunk) downloaded += len(chunk) download_progress[url]["downloaded"] = downloaded if downloaded != download_progress[url]["size"]: xlog.warn("download size:%d, need size:%d, download fail.", downloaded, download_progress[url]["size"]) continue else: download_progress[url]["status"] = "finished" return True except urllib2.URLError as e: xlog.warn("download %s to %s URL fail:%r", url, file, e) continue except Exception as e: xlog.exception("download %s to %s fail:%r", url, file, e) continue download_progress[url]["status"] = "failed" return False
def start(module): if not os.path.isdir(os.path.join(root_path, module)): return try: if module not in config.config["modules"]: xlog.error("module not exist %s", module) raise if module in proc_handler: xlog.error("module %s is running", module) return "module is running" if module not in proc_handler: proc_handler[module] = {} if os.path.isfile(os.path.join(root_path, module, "__init__.py")): if "imp" not in proc_handler[module]: proc_handler[module]["imp"] = __import__( module, globals(), locals(), ['local', 'start'], -1) _start = proc_handler[module]["imp"].start p = threading.Thread(target=_start.main) p.daemon = True p.start() proc_handler[module]["proc"] = p while not _start.client.ready: time.sleep(0.1) else: script_path = os.path.join(root_path, module, 'start.py') if not os.path.isfile(script_path): xlog.warn("start module script not exist:%s", script_path) return "fail" proc_handler[module]["proc"] = subprocess.Popen( [sys.executable, script_path], shell=False) xlog.info("module %s started", module) except Exception as e: xlog.exception("start module %s fail:%s", module, e) raise return "start success."
def windowWillClose_(self, notification): listNetworkServicesCommand = 'networksetup -listallnetworkservices' executeResult = subprocess.check_output(listNetworkServicesCommand, shell=True) services = executeResult.split('\n') services = filter(lambda service : service and service.find('*') == -1 and self.getProxyState(service) != 'disable', services) # Remove disabled services and empty lines if len(services) > 0: disableAutoProxyCommand = ';'.join(map(self.getDisableAutoProxyCommand, services)) disableGlobalProxyCommand = ';'.join(map(self.getDisableGlobalProxyCommand, services)) rootCommand = """osascript -e 'do shell script "%s;%s" with administrator privileges' """ % (disableAutoProxyCommand, disableGlobalProxyCommand) executeCommand = rootCommand.encode('utf-8') xlog.info("try disable proxy:%s", executeCommand) os.system(executeCommand) self.updateConfig('disable') module_init.stop_all() os._exit(0) NSApp.terminate_(self)
def start(): global process, server # should use config.yaml to bing ip allow_remote = config.get(["modules", "launcher", "allow_remote_connect"], 0) host_port = config.get(["modules", "launcher", "control_port"], 8085) if allow_remote: host_addr = "0.0.0.0" else: host_addr = "127.0.0.1" xlog.info("begin to start web control") server = simple_http_server.HTTPServer((host_addr, host_port), Http_Handler) process = threading.Thread(target=server.serve_forever) process.setDaemon(True) process.start() xlog.info("launcher web control started.")
def start(module): if not os.path.isdir(os.path.join(root_path, module)): return try: if module not in config.config["modules"]: xlog.error("module not exist %s", module) raise if module in proc_handler: xlog.error("module %s is running", module) return "module is running" if module not in proc_handler: proc_handler[module] = {} if os.path.isfile(os.path.join(root_path, module, "__init__.py")): if "imp" not in proc_handler[module]: proc_handler[module]["imp"] = __import__(module, globals(), locals(), ['local', 'start'], -1) _start = proc_handler[module]["imp"].start p = threading.Thread(target=_start.main) p.daemon = True p.start() proc_handler[module]["proc"] = p while not _start.client.ready: time.sleep(0.1) else: script_path = os.path.join(root_path, module, 'start.py') if not os.path.isfile(script_path): xlog.warn("start module script not exist:%s", script_path) return "fail" proc_handler[module]["proc"] = subprocess.Popen([sys.executable, script_path], shell=False) xlog.info("module %s started", module) except Exception as e: xlog.exception("start module %s fail:%s", module, e) raise return "start success."
def download_file(url, file): if url not in download_progress: download_progress[url] = {} download_progress[url]["status"] = "downloading" else: if download_progress[url]["status"] == "downloading": xlog.warn("url in downloading, %s", url) return False for i in range(0, 2): try: xlog.info("download %s to %s, retry:%d", url, file, i) opener = get_opener(i) req = opener.open(url) download_progress[url]["size"] = int(req.headers.get('content-length') or 0) CHUNK = 16 * 1024 downloaded = 0 with open(file, 'wb') as fp: while True: chunk = req.read(CHUNK) if not chunk: break fp.write(chunk) downloaded += len(chunk) download_progress[url]["downloaded"] = downloaded if downloaded != download_progress[url]["size"]: xlog.warn("download size:%d, need size:%d, download fail.", downloaded, download_progress[url]["size"]) continue else: download_progress[url]["status"] = "finished" return True except urllib2.URLError as e: xlog.warn("download %s to %s URL fail:%r", url, file, e) continue except Exception as e: xlog.exception("download %s to %s fail:%r", url, file, e) continue download_progress[url]["status"] = "failed" return False
def windowWillClose_(self, notification): executeResult = subprocess.check_output(['networksetup', '-listallnetworkservices']) services = executeResult.split('\n') services = filter(lambda service : service and service.find('*') == -1 and getProxyState(service) != 'disable', services) # Remove disabled services and empty lines if len(services) > 0: try: map(helperDisableAutoProxy, services) map(helperDisableGlobalProxy, services) except: disableAutoProxyCommand = ';'.join(map(getDisableAutoProxyCommand, services)) disableGlobalProxyCommand = ';'.join(map(getDisableGlobalProxyCommand, services)) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, disableGlobalProxyCommand) xlog.info("try disable proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) module_init.stop_all() os._exit(0) AppKit.NSApp.terminate_(self)
def install_xxnet_files(): def sha1_file(filename): import hashlib BLOCKSIZE = 65536 hasher = hashlib.sha1() try: with open(filename, 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) return hasher.hexdigest() except: return False pass for root, subdirs, files in os.walk(xxnet_unzip_path): # print("root:", root) relate_path = root[len(xxnet_unzip_path) + 1:] for subdir in subdirs: target_path = os.path.join(root_path, relate_path, subdir) if not os.path.isdir(target_path): xlog.info("mkdir %s", target_path) os.mkdir(target_path) for filename in files: if relate_path == os.path.join( "data", "gae_proxy") and filename == "config.ini": continue if relate_path == os.path.join( "data", "launcher") and filename == "config.yaml": continue src_file = os.path.join(root, filename) dst_file = os.path.join(root_path, relate_path, filename) if not os.path.isfile( dst_file) or sha1_file(src_file) != sha1_file(dst_file): shutil.copy(src_file, dst_file) xlog.info("copy %s => %s", src_file, dst_file)