def nsHYmkenv(ns, **kw): env = globals() env["nsGet"] = nsGet env["nsSet"] = nsSet env["f"] = nsGet(ns, "/bin/f") env["stamp"] = nsGet(ns, "/bin/stamp") env["ns"] = ns return env
def nsHYInit(ns, *args, **kw): nsMkdir(ns, "/pbin") nsMkdir(ns, "/psbin") nsMkdir(ns, "/etc/hy.startup") nsSet(ns, "/sys/hylang.enabled", False) nsHyEval(ns, '(nsSet ns "/sys/hylang.enabled" True)') nsHyEval(ns, '(nsSet ns "/sys/hylang.enabled.stamp" ((f "stamp")))') nsInfo(ns, "Hy is enabled: {}".format(nsGet(ns, "/sys/hylang.enabled"))) nsGet(ns, "/dev/queue/open")("hy")
def nsEnvInit(ns, *args, **kw): f = lf(ns) nsMkdir(ns, "/sys/env") nsSet(ns, "/sys/env/id", str(uuid.uuid4())) nsMkdir(ns, "/sys/env/variables") nsMkdir(ns, "/sys/env/platform") nsEnvVars(ns) nsSet(ns, "/sys/env/platform/architecture", platform.architecture()[0]) nsSet(ns, "/sys/env/platform/machine", platform.machine()) nsSet(ns, "/sys/env/platform/node", platform.node()) nsSet(ns, "/sys/env/platform/platform", platform.platform()) nsSet(ns, "/sys/env/platform/python", platform.python_version().split('.')) nsSet(ns, "/sys/env/platform/system", platform.system()) nsSet(ns, "/sys/env/platform/uname", platform.uname()) nsSet(ns, "/sys/env/uid", os.getuid()) nsSet(ns, "/sys/env/user", getpass.getuser()) nsSet(ns, "/sys/env/home", str(Path.home())) nsSet(ns, "/sys/env/cwd", os.getcwd()) home_total, home_used, home_free = shutil.disk_usage( nsGet(ns, "/sys/env/home")) nsSet(ns, "/sys/env/home.disk.size", home_total) nsSet(ns, "/sys/env/home.disk.used", home_used) nsSet(ns, "/sys/env/home.disk.free", home_free) nsSet(ns, "/sys/env/home.disk.free.percent", (home_free / home_total) * 100) nsSet(ns, "/sys/env/bootTimestamp", time.time()) nsSet(ns, "/sys/env/pid", os.getpid()) nsSet(ns, "/sys/env/me", psutil.Process(os.getpid())) nsMkdir(ns, "/sys/env/proc") try: nsSet(ns, "/sys/env/ip.addr", socket.gethostbyname(socket.gethostname())) nsSet(ns, "/sys/env/ip.addr.list", socket.gethostbyname_ex(socket.gethostname())[2]) except socket.gaierror: nsSet(ns, "/sys/env/ip.addr", '127.0.0.1') nsSet(ns, "/sys/env/ip.addr.list", ['127.0.0.1']) if nsGet(ns, "/etc/flags/truename", False) is True: nsSet(ns, "/etc/hostname", nsGet(ns, "/sys/env/platform/node")) nsEnvLoadLocalBS(ns) for k in kw: _k = "/" + k[4:].replace("_", "/") if fnmatch.fnmatch(k, "__V_*") is True: _k = "/" + k[4:].replace("_", "/") nsSet(ns, _k, kw[k]) if k[0] == "/": nsSet(ns, k, kw[k]) elif fnmatch.fnmatch(k, "__F_*") is True: dir = os.path.dirname(_k) nsMkdir(ns, dir) I(ns, _k, kw[k]) elif fnmatch.fnmatch(k, "__C_*") is True: nsCfgLoad(ns, kw[k]) elif fnmatch.fnmatch(k, "__B_*") is True: nsCfgFSLoad(ns, kw[k]) else: pass
def nsConsole(ns, *msg, **kw): if nsGet(ns, "/etc/console") is False: return msg q = nsGet(ns, "/sys/console") for _m in msg: _m = str(_m) _msg = _m % kw _msg = nsTxt(ns, _msg) q.put_nowait(_msg) return msg
def nsEnvRemovePid(ns): daemonFile = "{}.daemon".format(nsGet(ns, "/sys/env/pidFile")) if os.path.exists(daemonFile) and os.path.isfile(daemonFile): return f = lf(ns) V = f("V") if nsGet(ns, "/etc/daemonize") is True: return nsconsole(ns, "Removing PID file") if os.path.exists(nsGet(ns, "/sys/env/pidFile")) and os.path.isfile( nsGet(ns, "/sys/env/pidFile")): os.remove(nsGet(ns, "/sys/env/pidFile"))
def nsLog(ns, lvl, msg, **kw): if nsGet(ns, "/etc/log") is False: return None out = { 'level': lvl, 'msg': msg % kw, 'id': str(uuid.uuid4()), 'stamp': time.time() } out['msg'] = nsTxt(ns, out['msg']) q = nsGet(ns, "/sys/log/messages") q.put_nowait(out) if lvl >= 4: nsGlobalError(ns, out) return out
def nsLogProcess(ns, entries=1): q = nsGet(ns, "/sys/log/messages") logs = nsLs(ns, "/sys/log/channels") c = 0 while True: if q.qsize() > 0: msg = q.get_nowait() c += 1 else: break for log in logs: logs[log](msg) if c >= entries: break gevent.sleep(nsGet(ns, "/etc/logInBatchDelay", 0))
def NS(*args, **kw): from corens.mod import nsImport ns = _NS() ns = nsDefaults(ns) ns = nsImport(ns, nsGet(ns, "/config/library")) cargs = kw.get('args', sys.argv[1:]) _f(ns, "/bin/args")(cargs) _f(ns, "/sbin/signalinit")(*args, **kw) _f(ns, "/sbin/envinit")(*args, **kw) _f(ns, "/sbin/loginit")(*args, **kw) for c in nsGet(ns, "/config/cfg.files"): _f(ns, "/bin/Cfg")(c) ns = nsImport(ns, nsGet(ns, "/config/user.library")) _f(ns, "/bin/gevent")(*args, **kw) _f(ns, "/sbin/network_init")(*args, **kw) _f(ns, "/sbin/vnsinit")(*args, **kw) _f(ns, "/sbin/hyinit")(*args, **kw) _f(ns, "/sbin/hy.startup")(*args, **kw) _f(ns, "/sbin/signalsetup")(*args, **kw) _f(ns, "/sbin/envsetup")() _f(ns, "/sbin/init")(*args, **kw) _f(ns, "/bin/cmd")(*args, **kw) if nsGet(ns, "/config/cmd.run") is False and nsGet( ns, "/etc/daemonize") is False: if nsGet(ns, "/etc/daemonize") is False: _f(ns, "/bin/main")(*args, **kw) elif nsGet(ns, "/etc/daemonize") is True: _f(ns, "/bin/daemon_main")(*args, **kw) else: pass return (ns, partial(_f, ns), partial(_F, ns))
def check_the_path(ns, path): if not os.path.exists(path) and not os.path.isdir(path): return False _stat = os.stat(path) if _stat.st_uid != nsGet(ns, "/sys/env/uid"): return False if stat.S_IMODE(os.lstat(path).st_mode) != 448: return False return True
def nsconsole(ns, *msg, **kw): if nsGet(ns, "/etc/console") is False: return msg for _m in msg: _m = str(_m) _msg = _m % kw _msg = nsTxt(ns, _msg) try: with indent(4, quote=colored.green("|")): puts(_msg) except ValueError: return
def nsConsoleProcess(ns, entries=1): q = nsGet(ns, "/sys/console") c = 0 while True: if q.qsize() > 0: msg = q.get_nowait() c += 1 else: break if isinstance(msg, str) is True: with indent(4, quote=colored.green("|")): puts(msg) elif isinstance(msg, dict) is True and "dir" not in msg: nsConsoleLogWrite(ns, msg) elif isinstance(msg, dict) is True and "dir" in msg: with indent(4, quote=colored.magenta(msg["dir"])): del msg["dir"] puts(json.dumps(msg)) else: with indent(4, quote=colored.cyan("|")): puts(str(msg)) if c >= entries: break gevent.sleep(nsGet(ns, "/etc/consoleInBatchDelay", 0))
def nsEnvLoadPid(ns): try: with open(nsGet(ns, "/sys/env/pidFile"), "r") as f: try: pid = int(f.read()) except ValueError: return None except FileNotFoundError: return None try: me = psutil.Process(pid) except psutil.NoSuchProcess: return None if me.is_running() is True: return pid return None
def nsConsoleLogWrite(ns, msg): if nsGet(ns, "/etc/logConsoleAsJSON", False) is True: print(json.dumps(msg)) return level_m = ["DBG", "INF", "WRN", "ERR", "CRT", "PNC"] level_c = [ colored.white, colored.green, colored.cyan, colored.yellow, colored.red, colored.magenta ] print( level_c[msg['level']](level_m[msg['level']]), colored.white( time.strftime("[%m/%d %H:%M:%S]", time.localtime(msg['stamp']))), colored.yellow(msg['msg'])) if msg['level'] == 5: nsConsole(ns, "DON'T PANIC !") return
def nsEnvSetup(ns): nsSchedulerIntervalJob(ns, 60, "/dev/proc", nsProcTick) for f in nsLs(ns, "/bin/atexit"): atexit.register(nsGet(ns, "/bin/atexit/{}".format(f)))
def nsLogSize(ns, entries=1): q = nsGet(ns, "/sys/log/messages") return q.qsize()
def nsLogDaemon(ns): while True: nsLogProcess(ns, nsGet(ns, "/etc/logBatchSize", 10)) gevent.sleep(nsGet(ns, "/etc/logAfterBatchDelay", 3))
def nsLogToConsole(ns, msg): if nsGet(ns, "/etc/console") is False: return q = nsGet(ns, "/sys/console") q.put_nowait(msg)
def nsEnvLoadLocalBS(ns): CNS_HOME = nsGet(ns, "/sys/env/variables/CORENS_HOME") CNS_NAME = nsGet(ns, "/sys/env/variables/CORENS_NAME") if CNS_NAME is None: CNS_NAME = nsGet(ns, "/etc/name") if CNS_HOME is None: _path = [ "{}/.{}".format(nsGet(ns, "/sys/env/cwd"), nsGet(ns, "/etc/name")), "{}/.{}".format(nsGet(ns, "/sys/env/home"), nsGet(ns, "/etc/name")) ] for p in _path: if check_the_path(ns, p) is True: CNS_HOME = p break if CNS_HOME is None: CNS_HOME = "{}/.{}".format(nsGet(ns, "/sys/env/home"), nsGet(ns, "/etc/name")) os.mkdir(CNS_HOME) os.chmod(CNS_HOME, 0o700) nsSet(ns, "/sys/env/apphome", CNS_HOME) cfg_path = nsGet(ns, "/config/cfg.path") cfg_path.append("osfs://{}".format(CNS_HOME)) if check_the_path(ns, "/etc/{}".format(CNS_NAME)) is True: cfg_path.append("osfs:///etc/{}".format(CNS_NAME)) nsSet(ns, "/config/cfg.path", cfg_path) nsSet(ns, "/sys/env/pidFile", "{}/{}.pid".format(CNS_HOME, CNS_NAME)) pidExists = False if os.path.exists(nsGet(ns, "/sys/env/pidFile")) and os.path.isfile( nsGet(ns, "/sys/env/pidFile")): pidExists = True if nsGet(ns, "/etc/singleCopy") is True and pidExists is True: nsConsole(ns, "Application $etc.name already running") nsGlobalError(ns, "Application {} already running.".format(CNS_NAME)) raise SystemExit nsSet(ns, "/sys/env/pidFileExists", pidExists) if nsGet(ns, "/etc/flags/daemonize", False): nsEnvMkPID(ns) for p in cfg_path: nsCfgAppendFs(ns, p)
def nsConsoleDaemon(ns): while True: nsConsoleProcess(ns, nsGet(ns, "/etc/consoleBatchSize", 10)) gevent.sleep(nsGet(ns, "/etc/consoleAfterBatchDelay", 3))
def nsConsoleSize(ns): q = nsGet(ns, "/sys/console") return q.qsize()
def nsEnvMkPID(ns): if nsEnvLoadPid(ns) is not None: return with open(nsGet(ns, "/sys/env/pidFile"), "w") as f: f.write(str(os.getpid()))
def nsConsolePush(ns, *msg): if nsGet(ns, "/etc/console") is False: return msg q = nsGet(ns, "/sys/console") for _m in msg: q.put_nowait(_m)