Esempio n. 1
0
    def init(self):
        if not tp_cfg().common.check_host_alive:
            return True

        icmp_protocol = socket.getprotobyname('icmp')
        try:
            self._socket_ping = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                              icmp_protocol)
        except PermissionError:
            print('To use PING to check host state, must run as root.')
            log.e('To use PING to check host state, must run as root.\n')
            return False

        # 加载所有主机IP
        hosts = host.get_all_hosts_for_check_state()
        for h in hosts:
            if h['router_ip'] != '':
                self.add_host(h['router_ip'], HostAlive.METHOD_PING)
            else:
                self.add_host(h['ip'], HostAlive.METHOD_PING)

        self._thread_recv_ping_result = threading.Thread(
            target=self._thread_func_recv_ping_result)
        self._thread_recv_ping_result.start()

        tp_cron().add_job('host_check_alive',
                          self._check_alive,
                          first_interval_seconds=10,
                          interval_seconds=HostAlive.PING_INTERVAL)

        # for test:
        # tp_cron().add_job('host_show_alive', self._show_alive, first_interval_seconds=20, interval_seconds=HostAlive.PING_INTERVAL)

        return True
Esempio n. 2
0
 def init(self):
     self.update_default_expire()
     tp_cron().add_job('session_expire',
                       self._check_expire,
                       first_interval_seconds=None,
                       interval_seconds=60)
     return True
Esempio n. 3
0
    def init(self):
        t = tp_utc_timestamp_ms() - 10 * 60 * 1000
        cnt = int((10 * 60 + self._INTERVAL - 1) / self._INTERVAL)
        for i in range(cnt):
            val = {
                't': t,
                'cpu': {
                    'u': 0,
                    's': 0
                },
                'mem': {
                    'u': 0,
                    't': 100
                },
                'disk': {
                    'r': 0,
                    'w': 0
                },
                'net': {
                    'r': 0,
                    's': 0
                }
            }
            self._sys_stats.append(val)
            t += self._INTERVAL * 1000

        psutil.cpu_times_percent()
        net = psutil.net_io_counters(pernic=False)
        self._net_recv = net.bytes_recv
        self._net_sent = net.bytes_sent
        disk = psutil.disk_io_counters(perdisk=False)
        self._disk_read = disk.read_bytes
        self._disk_write = disk.write_bytes

        err, c = stats.get_basic_stats()
        if TPE_OK == err:
            self._counter_stats = c

        # 每 5秒 采集一次系统状态统计数据
        tp_cron().add_job('sys_status',
                          self._check_sys_stats,
                          first_interval_seconds=self._INTERVAL,
                          interval_seconds=self._INTERVAL)
        # 每 1小时 重新查询一次数据库,得到用户数/主机数/账号数/连接数,避免统计数量出现偏差
        tp_cron().add_job('query_counter',
                          self._query_counter,
                          first_interval_seconds=60 * 60,
                          interval_seconds=60 * 60)
        # 每 1分钟 检查一下临时锁定用户是否可以自动解锁了
        tp_cron().add_job('check_temp_locked_user',
                          self._check_temp_locked_user,
                          interval_seconds=60)

        tp_wss().register_get_sys_status_callback(self.get_sys_stats)
        tp_wss().register_get_stat_counter_callback(self.get_counter_stats)

        return True
Esempio n. 4
0
    def init(self):
        t = tp_utc_timestamp_ms() - 10 * 60 * 1000
        cnt = int((10 * 60 + self._INTERVAL - 1) / self._INTERVAL)
        for i in range(cnt):
            val = {
                't': t,
                'cpu': {'u': 0, 's': 0},
                'mem': {'u': 0, 't': 100},
                'disk': {'r': 0, 'w': 0},
                'net': {'r': 0, 's': 0}
            }
            self._sys_stats.append(val)
            t += self._INTERVAL * 1000

        psutil.cpu_times_percent()
        net = psutil.net_io_counters(pernic=False)
        self._net_recv = net.bytes_recv
        self._net_sent = net.bytes_sent
        disk = psutil.disk_io_counters(perdisk=False)
        self._disk_read = disk.read_bytes
        self._disk_write = disk.write_bytes

        err, c = stats.get_basic_stats()
        if TPE_OK == err:
            self._counter_stats = c

        # 每 5秒 采集一次系统状态统计数据
        tp_cron().add_job('sys_status', self._check_sys_stats, first_interval_seconds=self._INTERVAL, interval_seconds=self._INTERVAL)
        # 每 1小时 重新查询一次数据库,得到用户数/主机数/账号数/连接数,避免统计数量出现偏差
        tp_cron().add_job('query_counter', self._query_counter, first_interval_seconds=60 * 60, interval_seconds=60 * 60)
        # 每 1分钟 检查一下临时锁定用户是否可以自动解锁了
        tp_cron().add_job('check_temp_locked_user', self._check_temp_locked_user, interval_seconds=60)

        tp_wss().register_get_sys_status_callback(self.get_sys_stats)
        tp_wss().register_get_stat_counter_callback(self.get_counter_stats)

        return True
Esempio n. 5
0
    def _run_loop(self):
        ext_srv_cfg = tp_ext_srv_cfg()
        if not ext_srv_cfg.init():
            return 0

        log.i('Teleport Web Server starting ...\n')

        tp_cron().init()

        # 尝试通过CORE-JSON-RPC获取core服务的配置(主要是ssh/rdp/telnet的端口以及录像文件存放路径)
        self._get_core_server_config()

        _db = get_db()
        if not _db.init():
            log.e('can not initialize database interface.\n')
            return 0

        _db.connect()
        while not _db.connected:
            log.w('database not connected, retry after 5 seconds.\n')
            time.sleep(5)
            _db.connect()

        cfg = tp_cfg()

        _db.check_status()
        if _db.need_create or _db.need_upgrade:
            cfg.app_mode = APP_MODE_MAINTENANCE
            tp_cfg().update_sys(None)
        else:
            cfg.app_mode = APP_MODE_NORMAL
            _db.load_system_config()

        try:
            # 将运行时配置发送给核心服务
            req = {'method': 'set_config', 'param': {'noop_timeout': tp_cfg().sys.session.noop_timeout}}
            req_data = json.dumps(req)
            data = urllib.parse.quote(req_data).encode('utf-8')
            req = urllib.request.Request(url=cfg.common.core_server_rpc, data=data)
            rep = urllib.request.urlopen(req, timeout=3)
            body = rep.read().decode()
            x = json.loads(body)
            if 'code' not in x or x['code'] != 0:
                print(x)
                log.e('connect core-server for set runtime-config failed.\n')
            else:
                log.d('set runtime-config for core-server succeeded.\n')
        except:
            log.w('can not connect to core-server to set runtime-config, maybe it not start yet, ignore.\n')

        if not tp_session().init():
            log.e('can not initialize session manager.\n')
            return 0

        if not tp_stats().init():
            log.e('can not initialize system status collector.\n')
            return 0

        if cfg.common.check_host_alive:
            if not tp_host_alive().init():
                log.e('can not initialize host state inspector.\n')
                return 0

        settings = {
            #
            'cookie_secret': '8946svdABGD345fg98uhIaefEBePIfegOIakjFH43oETzK',

            'login_url': '/auth/login',

            # 指定静态文件的路径,页面模板中可以用 {{ static_url('css/main.css') }} 的方式调用
            'static_path': cfg.static_path,

            # 指定模板文件的路径
            'template_path': cfg.template_path,

            # 防止跨站伪造请求,参见 http://old.sebug.net/paper/books/tornado/#_7
            'xsrf_cookies': False,

            'autoescape': 'xhtml_escape',

            # 'ui_modules': ui_modules,
            'debug': False,

            # 不开启模板和静态文件的缓存,这样一旦模板文件和静态文件变化,刷新浏览器即可看到更新。
            'compiled_template_cache': False,
            'static_hash_cache': False,
        }

        from app.controller import controllers, fix_controller
        fix_controller()
        _app = tornado.web.Application(controllers, **settings)

        server = tornado.httpserver.HTTPServer(_app, xheaders=True)
        # server = tornado.httpserver.HTTPServer(_app, xheaders=True, ssl_options={
        #     "certfile": os.path.join(cfg.data_path, 'cert', "server.pem"),
        #     "keyfile": os.path.join(cfg.data_path, 'cert', "server.key"),
        # })

        try:
            server.listen(cfg.common.port, address=cfg.common.ip)
            if cfg.common.ip == '0.0.0.0':
                log.i('works on [http://127.0.0.1:{}]\n'.format(cfg.common.port))
            else:
                log.i('works on [http://{}:{}]\n'.format(cfg.common.ip, cfg.common.port))
        except:
            log.e('can not listen on port {}:{}, make sure it not been used by another application.\n'.format(cfg.common.ip, cfg.common.port))
            return 0

        # 启动定时任务调度器
        tp_cron().start()

        try:
            tornado.ioloop.IOLoop.instance().start()
        except:
            log.e('\n')

        if tp_cfg().common.check_host_alive:
            tp_host_alive().stop()
        tp_cron().stop()
        return 0
Esempio n. 6
0
 def init(self):
     self.update_default_expire()
     tp_cron().add_job('session_expire', self._check_expire, first_interval_seconds=None, interval_seconds=60)
     return True
Esempio n. 7
0
    def run(self):
        log.i('\n')
        log.i('###############################################################\n')
        log.i('Load config file: {}\n'.format(self._cfg_file))
        log.i('Teleport Web Server starting ...\n')

        tp_cron().init()

        # 尝试通过CORE-JSON-RPC获取core服务的配置(主要是ssh/rdp/telnet的端口以及录像文件存放路径)
        self._get_core_server_config()

        _db = get_db()
        if not _db.init():
            log.e('can not initialize database interface.\n')
            return 0

        _db.connect()
        while not _db.connected:
            log.w('database not connected, retry after 5 seconds.\n')
            time.sleep(5)
            _db.connect()

        cfg = tp_cfg()

        _db.check_status()
        if _db.need_create or _db.need_upgrade:
            cfg.app_mode = APP_MODE_MAINTENANCE
            tp_cfg().update_sys(None)
        else:
            cfg.app_mode = APP_MODE_NORMAL
            _db.load_system_config()

        try:
            # 将运行时配置发送给核心服务
            req = {'method': 'set_config', 'param': {'noop_timeout': tp_cfg().sys.session.noop_timeout}}
            req_data = json.dumps(req)
            data = urllib.parse.quote(req_data).encode('utf-8')
            req = urllib.request.Request(url=cfg.common.core_server_rpc, data=data)
            rep = urllib.request.urlopen(req, timeout=3)
            body = rep.read().decode()
            x = json.loads(body)
            if 'code' not in x or x['code'] != 0:
                print(x)
                log.e('connect core-server for set runtime-config failed.\n')
            else:
                log.d('set runtime-config for core-server succeeded.\n')
        except:
            log.w('can not connect to core-server to set runtime-config, maybe it not start yet, ignore.\n')

        if not tp_session().init():
            log.e('can not initialize session manager.\n')
            return 0
        if not tp_stats().init():
            log.e('can not initialize system status collector.\n')
            return 0

        settings = {
            #
            'cookie_secret': '8946svdABGD345fg98uhIaefEBePIfegOIakjFH43oETzK',

            'login_url': '/auth/login',

            # 指定静态文件的路径,页面模板中可以用 {{ static_url('css/main.css') }} 的方式调用
            'static_path': cfg.static_path,

            # 指定模板文件的路径
            'template_path': cfg.template_path,

            # 防止跨站伪造请求,参见 http://old.sebug.net/paper/books/tornado/#_7
            'xsrf_cookies': False,

            'autoescape': 'xhtml_escape',

            # 'ui_modules': ui_modules,
            'debug': False,

            # 不开启模板和静态文件的缓存,这样一旦模板文件和静态文件变化,刷新浏览器即可看到更新。
            'compiled_template_cache': False,
            'static_hash_cache': False,
        }

        from app.controller import controllers, fix_controller
        fix_controller()
        _app = tornado.web.Application(controllers, **settings)

        server = tornado.httpserver.HTTPServer(_app, xheaders=True)
        # server = tornado.httpserver.HTTPServer(_app, ssl_options={
        #     "certfile": os.path.join(cfg.data_path, 'cert', "server.pem"),
        #     "keyfile": os.path.join(cfg.data_path, 'cert', "server.key"),
        # })

        try:
            server.listen(cfg.common.port, address=cfg.common.ip)
            if cfg.common.ip == '0.0.0.0':
                log.i('works on [http://127.0.0.1:{}]\n'.format(cfg.common.port))
            else:
                log.i('works on [http://{}:{}]\n'.format(cfg.common.ip, cfg.common.port))
        except:
            log.e('can not listen on port {}:{}, make sure it not been used by another application.\n'.format(cfg.common.ip, cfg.common.port))
            return 0

        # 启动定时任务调度器
        tp_cron().start()

        try:
            tornado.ioloop.IOLoop.instance().start()
        except:
            log.e('\n')

        tp_cron().stop()
        return 0