├── .gitignore ├── README.md ├── alpaca ├── backend ├── .gitignore ├── app │ ├── __init__.py │ ├── handler │ │ ├── __init__.py │ │ ├── network.py │ │ └── system.py │ ├── lib │ │ ├── __init__.py │ │ ├── basic.py │ │ ├── const.py │ │ ├── logger.py │ │ ├── network.py │ │ ├── system.py │ │ └── util.py │ ├── main.py │ ├── make_app.py │ └── views │ │ ├── __init__.py │ │ ├── auth.py │ │ ├── basic.py │ │ ├── network.py │ │ └── system.py ├── config.py ├── gun.py ├── requirements.txt └── run.py ├── frontend ├── .babelrc ├── .editorconfig ├── .gitignore ├── build │ ├── build.js │ ├── check-versions.js │ ├── dev-client.js │ ├── dev-server.js │ ├── utils.js │ ├── vue-loader.conf.js │ ├── webpack.base.conf.js │ ├── webpack.dev.conf.js │ └── webpack.prod.conf.js ├── config │ ├── dev.env.js │ ├── index.js │ └── prod.env.js ├── index.html ├── package.json ├── src │ ├── App.vue │ ├── api.js │ ├── components │ │ ├── common │ │ │ ├── BarCharts.vue │ │ │ ├── Header.vue │ │ │ ├── Home.vue │ │ │ ├── KvPanel.vue │ │ │ ├── PieCharts.vue │ │ │ ├── SearchProcess.vue │ │ │ ├── Sidebar.vue │ │ │ └── TimeLineCharts.vue │ │ └── page │ │ │ ├── Basic.vue │ │ │ ├── Login.vue │ │ │ ├── Network.vue │ │ │ ├── Process.vue │ │ │ └── System.vue │ ├── config.js │ ├── main.js │ ├── router │ │ └── index.js │ └── service │ │ └── auth.js └── static │ ├── .gitkeep │ ├── css │ ├── color-dark.css │ └── main.css │ └── js │ └── .gitignore └── screenshot ├── basic.png ├── network.png ├── process.png └── system.png /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | 3 | .idea/ 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # alpaca 2 | 3 | > 一个基于`vue2.0` `python2.7` `flask`的简单linux dashboard, 用于收集、统计和展示linux操作系统信息,主要包括四个维度的信息: 4 | > 5 | > 1. 基本信息: ip,hostname,cpu配置信息,磁盘分区信息等; 6 | > 7 | > 2. 系统信息: 前load及变化趋势,cpu空闲率,cpu时间分布,内存使用率,内存使用分布,占用 8 | > cpu/内存比较多的进程, IO读写数量,以及耗费的时间等; 9 | > 10 | > 3. 网络信息: 各个网卡的进出流量统计和走势,网络连接的详情以及各状态统计; 11 | > 12 | > 4. 进程信息: 显示特定进程的详情,包括进程的内存使用情况,cpu使用情况,创建时间,状态, 13 | > IO情况,子进程列表,网络连接列表,打开的文件描述符列表,启动的线程列表等; 14 | 15 | ## 安装 16 | ### 环境要求 17 | linux操作系统;python2.7; node >= 4.0.0; npm>= 3.0.0 18 | ### 安装和启动 19 | > 1. 确保目标机器环境符合要求 20 | > 21 | > 2. 将代码clone到目标机器,进入代码文件目录,可以看到其中有以alpaca命名的管理脚本, 管理脚本提供了`build`(安装程序依赖包,打包前端的js,css文件等操作), `start`, `stop`,`restart`,`status`等功能,因此,代码刚clone到本地或者修改以后,需要重新build,然后再start. 22 | > 23 | 24 | 25 | git clone git@github.com:echoyuanliang/alpaca.git 26 | cd alpaca 27 | bash alpaca build 28 | bash alpaca start 29 | 30 | 31 | ### 相关配置 32 | 33 | * 程序使用gunicorn托管(也可以直接使用run.py启动),guncorn启动配置文件路径为`backend/gun.py`.默认配置如下,默认端口为`8080`,也是此处配置: 34 | 35 | 36 | # -*- coding: utf-8 -*- 37 | import multiprocessing 38 | 39 | bind = "0.0.0.0:8080" 40 | pidfile = 'var/gunicorn.pid' 41 | workers = multiprocessing.cpu_count() * 2 + 1 42 | 43 | worker_class = 'sync' 44 | backlog = 2048 45 | daemon = True 46 | loglevel = 'info' 47 | accesslog = 'logs/access.log' 48 | errorlog = 'logs/error.log' 49 | access_log_format = "%({X-Real-IP}i)s %(h)s %(l)s %(u)s %(t)s %(r)s %(s)s %(b)s %(f)s %(a)s" 50 | 51 | 52 | * 应用程序配置文件路径为`backend/config.py`, alpaca使用linux的用户(root除外),密码来管理登陆的用户,因此需要配置那些用户具有访问权限,配置项为`AUTH_USER`, 如果不配置或配置为空数组,则所有用户均有权限登录, 同时,alpaca仅对白名单ip授予访问权限,配置项为`AUTH_IP`,如果不配置或配置项为空数组,则所有ip均有权限登录。 53 | 54 | 55 | ## 技术栈 56 | `python` `flask` `ecmascript6` `vue2.0` 57 | 58 | ## 截图 59 | **基本信息页面** 60 | 61 | ![basic.png](https://github.com/echoyuanliang/alpaca/blob/master/screenshot/basic.png) 62 | 63 | 64 | **系统信息页面** 65 | 66 | ![system.png](https://github.com/echoyuanliang/alpaca/blob/master/screenshot/system.png) 67 | 68 | 69 | **网络信息页面** 70 | 71 | 72 | ![network.png](https://github.com/echoyuanliang/alpaca/blob/master/screenshot/network.png) 73 | 74 | 75 | **进程信息页面** 76 | 77 | 78 | ![process.png](https://github.com/echoyuanliang/alpaca/blob/master/screenshot/process.png) 79 | 80 | -------------------------------------------------------------------------------- /alpaca: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | 4 | # service name 5 | service_name="alpaca" 6 | 7 | 8 | exec="venv/bin/python venv/bin/gunicorn -c gun.py app.main:app" 9 | work_dir=`pwd` 10 | backend=${work_dir}/"backend" 11 | frontend=${work_dir}/"frontend" 12 | backend_static=${backend}/"app/static" 13 | backend_templates=${backend}/"app/templates/" 14 | 15 | RETVAL=0 16 | 17 | Red='\033[0;31m' 18 | Color_Off='\033[0m' 19 | Green='\033[0;32m' 20 | 21 | 22 | do_status() { 23 | num=`ps aux|grep "${exec}"|grep -v "grep"|wc -l` 24 | if [ $num -ne 0 ];then 25 | # startup time 26 | last_pid=`ps aux|grep "${exec}"|grep -v "grep"|awk '{print $2}'|tail -n 1` 27 | pro_list=`ps aux|grep "${exec}"|grep -v "grep"|awk '{print $2}'|sed ':a;N;$!ba;s#\n#,#g'` 28 | start_time=`ps -p ${last_pid} -o lstart|grep -v 'STARTED'` 29 | t_count=`ps xH|grep ${last_pid}|grep -v grep|wc -l` 30 | p_count=`ps aux|grep "${exec}"|grep -v "grep"|awk '{print $2}'|wc -l` 31 | printf "${Green} status: running${Color_Off}\n" 32 | printf "${Green} process count: ${p_count}${Color_Off}\n" 33 | printf "${Green}threads/process: ${t_count}${Color_Off}\n" 34 | printf "${Green} process list: ${pro_list}${Color_Off}\n" 35 | printf "${Green} uptime: ${start_time}${Color_Off}\n" 36 | 37 | else 38 | printf "${Green} status: stopped${Color_Off}\n" 39 | fi 40 | 41 | return $? 42 | } 43 | 44 | status() { 45 | do_status 46 | exit $? 47 | } 48 | 49 | 50 | do_start() { 51 | cd ${backend} 52 | num=`ps aux|grep "${exec}"|grep -v "grep"|wc -l` 53 | if [ $num -ne 0 ];then 54 | printf "${Red}${service_name} is running, Skipped try to start again.${Color_Off}\n" 55 | return 0 56 | fi 57 | $exec 58 | if [ $? -ne 0 ]; then 59 | printf "${Red}start ${service_name} occurred errors.${Color_Off}\n" 60 | return 1 61 | fi 62 | printf "${Green}start ${service_name} successfully.${Color_Off}\n" 63 | sleep 2 64 | do_status 65 | return $? 66 | } 67 | 68 | start() { 69 | do_start 70 | exit $? 71 | } 72 | 73 | build_back() { 74 | cd ${backend} 75 | virtualenv --no-site-packages venv --python=python2.7 76 | venv/bin/pip install -r requirements.txt 77 | 78 | rm -rf ${backend_static} 79 | rm -rf ${backend_templates} && mkdir ${backend_templates} 80 | 81 | if [ ! -d logs ];then 82 | mkdir logs 83 | fi 84 | 85 | if [ ! -d var ];then 86 | mkdir var 87 | fi 88 | 89 | if [ ! -d instance ];then 90 | mkdir instance 91 | fi 92 | 93 | if [ ! -f instance/config.py ];then 94 | touch instance/config.py 95 | fi 96 | 97 | return $? 98 | } 99 | 100 | build_front() { 101 | cd ${frontend} 102 | npm install && npm run build 103 | cp ${frontend}/"dist/index.html" ${backend_templates} 104 | cp -r ${frontend}/"dist/static/" ${backend_static} 105 | } 106 | 107 | build() { 108 | build_back 109 | build_front 110 | exit $? 111 | } 112 | 113 | do_stop() { 114 | num=`ps aux|grep "${exec}"|grep -v "grep"|wc -l` 115 | if [ $num -ne 0 ];then 116 | searching_pid=`ps aux|grep "${exec}"|grep -v "grep"|awk '{print $2}'` 117 | for p in $searching_pid 118 | do 119 | kill -9 $p 120 | done 121 | else 122 | printf "${Red}${service_name} is not running.${Color_Off}\n" 123 | return 0 124 | fi 125 | 126 | printf "${Green}shutdown ${service_name} successfully.${Color_Off}\n" 127 | return $? 128 | } 129 | 130 | stop() { 131 | do_stop 132 | exit $? 133 | } 134 | 135 | 136 | restart() { 137 | num=`ps aux|grep "${exec}"|grep -v "grep"|wc -l` 138 | if [ $num -eq 0 ];then 139 | printf "${Red}${service_name} is not running, Trying to start.${Color_Off}\n" 140 | do_start 141 | exit $? 142 | else 143 | do_stop 144 | if [ $? -ne 0 ];then 145 | printf "${Red} stop ${service_name} occurred errors.${Color_Off}\n" 146 | exit 1 147 | else 148 | do_start 149 | exit $? 150 | fi 151 | fi 152 | } 153 | 154 | 155 | case "$1" in 156 | start) 157 | start 158 | ;; 159 | stop) 160 | stop 161 | ;; 162 | restart) 163 | restart 164 | ;; 165 | build) 166 | build 167 | ;; 168 | status) 169 | status 170 | ;; 171 | *) 172 | printf "${Red}Usage: service ${service_name} {start|stop|restart|status|build}.${Color_Off}\n" 173 | RETVAL=1 174 | esac 175 | exit $RETVAL 176 | -------------------------------------------------------------------------------- /backend/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | 3 | .idea/ 4 | venv/ 5 | logs/ 6 | var/ 7 | *.pyc 8 | app/static 9 | app/templates 10 | instance/ -------------------------------------------------------------------------------- /backend/app/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | -------------------------------------------------------------------------------- /backend/app/handler/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from system import system_handler 3 | from network import net_handler 4 | -------------------------------------------------------------------------------- /backend/app/handler/network.py: -------------------------------------------------------------------------------- 1 | import time 2 | from threading import Thread, Lock 3 | from copy import deepcopy 4 | from app.lib.network import get_iface_status, get_connections 5 | 6 | 7 | class NetHandler(Thread): 8 | 9 | def __init__(self, interval=10): 10 | Thread.__init__(self) 11 | self.net_cache = [{}, {}] 12 | self.connections = {} 13 | self.lock = Lock() 14 | self.interval = interval 15 | 16 | def run(self): 17 | from app.main import app 18 | 19 | while True: 20 | with app.app_context(): 21 | try: 22 | net = get_iface_status() 23 | self._set_net_async(net) 24 | self._set_connections() 25 | time.sleep(self.interval) 26 | except Exception as e: 27 | app.logger.exception(str(e)) 28 | 29 | def _set_net(self, net): 30 | self.net_cache[1] = self.net_cache[0] 31 | self.net_cache[0] = net 32 | 33 | def _set_net_async(self, net): 34 | with self.lock: 35 | self._set_net(net) 36 | 37 | def _set_connections(self): 38 | connections = get_connections() 39 | with self.lock: 40 | self.connections = connections 41 | 42 | @staticmethod 43 | def _sub_iface_status(left_iface, right_iface): 44 | res = {} 45 | for key, value in left_iface.items(): 46 | res[key] = left_iface[key] - right_iface[key] 47 | 48 | return res 49 | 50 | def _compute_sub(self, iface_status): 51 | now_status, previous_status = iface_status 52 | if not now_status or not previous_status: 53 | tmp_status = get_iface_status() 54 | self._set_net_async(tmp_status) 55 | return [] 56 | 57 | iface_list = [] 58 | for iface, cur_status in now_status.items(): 59 | prev_status = previous_status[iface] 60 | res_status = self._sub_iface_status(cur_status, prev_status) 61 | res_status['iface'] = iface 62 | iface_list.append(res_status) 63 | 64 | return iface_list 65 | 66 | def get_iface_status(self): 67 | with self.lock: 68 | iface_status = deepcopy(self.net_cache) 69 | 70 | return self._compute_sub(iface_status) 71 | 72 | def get_connections(self): 73 | with self.lock: 74 | connections = deepcopy(self.connections) 75 | return connections 76 | 77 | def get_network_info(self): 78 | with self.lock: 79 | iface_status = deepcopy(self.net_cache) 80 | connections = deepcopy(self.connections) 81 | 82 | return { 83 | 'connections': connections, 84 | 'iface_status': self._compute_sub(iface_status) 85 | } 86 | 87 | net_handler = NetHandler() 88 | net_handler.start() 89 | -------------------------------------------------------------------------------- /backend/app/handler/system.py: -------------------------------------------------------------------------------- 1 | import time 2 | from threading import Thread, Lock 3 | from copy import deepcopy 4 | from app.lib import system 5 | 6 | 7 | class SystemHandler(Thread): 8 | def __init__(self, interval=10): 9 | Thread.__init__(self) 10 | self.system_info = {} 11 | self.cpu_stat = [{}, {}] 12 | self.io_counters = [{}, {}] 13 | self.lock = Lock() 14 | self.interval = interval 15 | 16 | def run(self): 17 | while True: 18 | self._set_system() 19 | time.sleep(self.interval) 20 | 21 | def _set_system(self): 22 | from app.main import app 23 | with app.app_context(): 24 | try: 25 | cpu_stat = system.get_cpu_stat() 26 | io_counters = system.get_io_counters() 27 | 28 | system_info = { 29 | 'loadavg': system.get_loadavg(), 30 | 'intensive_processes': system.get_intensive_processes(), 31 | # 'pstree': system.get_pstree(), 32 | 'mem_info': system.get_mem_info() 33 | } 34 | 35 | with self.lock: 36 | self._set_stat(cpu_stat) 37 | self._set_io(io_counters) 38 | system_info['cpu_stat'] = self._compute_last_stat(self.cpu_stat) 39 | system_info['io_counters'] = self._compute_io_counters(self.io_counters) 40 | self.system_info = system_info 41 | except Exception as e: 42 | app.logger.exception(str(e)) 43 | 44 | def get_system(self): 45 | with self.lock: 46 | tmp_info = self.system_info 47 | 48 | return tmp_info 49 | 50 | def _set_stat(self, stat): 51 | self.cpu_stat[1] = self.cpu_stat[0] 52 | self.cpu_stat[0] = stat 53 | 54 | def _set_io(self, io): 55 | self.io_counters[1] = self.io_counters[0] 56 | self.io_counters[0] = io 57 | 58 | def _set_io_sync(self, io): 59 | with self.lock: 60 | self._set_io(io) 61 | 62 | def _set_stat_sync(self, stat): 63 | with self.lock: 64 | self._set_stat(stat) 65 | 66 | @staticmethod 67 | def _sub_stat(left_stat, right_stat): 68 | total = float(left_stat['total'] - right_stat['total']) 69 | 70 | def compute_attr_percent(attr): 71 | return round((left_stat[attr] - right_stat[attr]) * 100 / total, 2) 72 | 73 | stat = { 74 | 'total': round(total, 2), 75 | 'nice': compute_attr_percent('nice'), 76 | 'system': compute_attr_percent('system'), 77 | 'user': compute_attr_percent('user'), 78 | 'idle': compute_attr_percent('idle'), 79 | 'iowait': compute_attr_percent('iowait'), 80 | 'irq': compute_attr_percent('irq'), 81 | 'steal': compute_attr_percent('steal'), 82 | 'guest': compute_attr_percent('guest'), 83 | 'soft_irq': compute_attr_percent('soft_irq') 84 | } 85 | 86 | return stat 87 | 88 | @staticmethod 89 | def _sub_io(left_io, right_io): 90 | res = {} 91 | for key, value in left_io.items(): 92 | res[key] = left_io[key] - right_io[key] 93 | 94 | res['avg_read_time'] = round(res['read_time'] / float(res['read_count']), 2) if res['read_count'] else 0 95 | res['avg_write_time'] = round(res['write_time'] / float(res['write_count']), 2) if res['write_count'] else 0 96 | res['avg_read_bytes'] = round(res['read_bytes'] / float(res['read_count']), 2) if res['read_count'] else 0 97 | res['avg_write_bytes'] = round(res['write_bytes'] / float(res['write_count']), 2) if res['write_count'] else 0 98 | return res 99 | 100 | def _compute_last_stat(self, cpu_stat): 101 | now_stat, previous_stat = cpu_stat 102 | if not now_stat or not previous_stat: 103 | return {} 104 | 105 | stat = {} 106 | for key, val in now_stat.items(): 107 | if key != 'cpus': 108 | stat[key] = val 109 | else: 110 | stat['cpus'] = [] 111 | for cpu, item in now_stat['cpus'].items(): 112 | cur_cpu = self._sub_stat(item, previous_stat['cpus'][cpu]) 113 | cur_cpu['name'] = cpu 114 | stat['cpus'].append(cur_cpu) 115 | return stat 116 | 117 | def _compute_io_counters(self, io_counters): 118 | now_io, previous_io = io_counters 119 | if not now_io or not previous_io: 120 | return {} 121 | 122 | return self._sub_io(now_io, previous_io) 123 | 124 | def get_last_io(self): 125 | with self.lock: 126 | io_counters = deepcopy(self.io_counters) 127 | 128 | return self._compute_last_stat(io_counters) 129 | 130 | def get_last_stat(self): 131 | with self.lock: 132 | cpu_stat = deepcopy(self.cpu_stat) 133 | 134 | return self._compute_last_stat(cpu_stat) 135 | 136 | 137 | system_handler = SystemHandler() 138 | system_handler.start() 139 | -------------------------------------------------------------------------------- /backend/app/lib/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | -------------------------------------------------------------------------------- /backend/app/lib/basic.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | import datetime 9 | import platform 10 | import socket 11 | import subprocess 12 | import psutil 13 | from uptime import uptime 14 | from app.lib.util import bytes2human 15 | 16 | 17 | def _seconds2human(seconds): 18 | m,s = divmod(seconds, 60) 19 | h,m = divmod(m, 60) 20 | d,h = divmod(h, 24) 21 | 22 | time_str = '{0}days, {1}hours, {2}minutes, {3}seconds'.format(int(d), int(h), int(m), int(s)) 23 | return time_str 24 | 25 | 26 | def get_general(): 27 | return { 28 | 'hostname': socket.gethostname(), 29 | 'os_name': platform.system(), 30 | 'os_version': platform.release(), 31 | 'server_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 32 | 'sys_up': _seconds2human(uptime()) 33 | } 34 | 35 | 36 | def get_disk_info(): 37 | disk_info = [] 38 | 39 | partitions = psutil.disk_partitions(all=False) 40 | for partition in partitions: 41 | disk_usage = psutil.disk_usage(partition.mountpoint) 42 | disk_item = { 43 | 'device': partition.device, 44 | 'mountpoint': partition.mountpoint, 45 | 'fstype': partition.fstype, 46 | 'total': bytes2human(disk_usage.total), 47 | 'used': bytes2human(disk_usage.used), 48 | 'free': bytes2human(disk_usage.free), 49 | 'percent': disk_usage.percent 50 | } 51 | 52 | disk_info.append(disk_item) 53 | return disk_info 54 | 55 | 56 | def get_cpu_info(): 57 | cmd = '/usr/bin/lscpu' 58 | out = subprocess.check_output(cmd, shell=True) 59 | cpu_info = dict() 60 | public_keys = ['Architecture', 'Byte Order', 'CPU MHz', 'CPU(s)'] 61 | public_pattern = 'cache' 62 | 63 | for line in out.splitlines(): 64 | k, v = [item.strip() for item in line.split(':')] 65 | if k in public_keys or k.find(public_pattern) != -1: 66 | k = k.replace(' ', '_').replace('(', '').replace(')', '').lower() 67 | cpu_info[k] = v 68 | return cpu_info 69 | 70 | 71 | def get_net_info(): 72 | if_addrs = psutil.net_if_addrs() 73 | net_info = list() 74 | for interface, addrs in if_addrs.items(): 75 | for addr in addrs: 76 | if addr.family == socket.AF_INET: 77 | net_info.append({ 78 | 'interface': interface, 79 | 'address': addr.address, 80 | 'netmask': addr.netmask 81 | }) 82 | 83 | return net_info 84 | -------------------------------------------------------------------------------- /backend/app/lib/const.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | import socket 9 | 10 | SOCK_TYPE = { 11 | socket.SOCK_STREAM: 'tcp', 12 | socket.SOCK_DGRAM: 'udp', 13 | socket.SOCK_RAW: 'raw', 14 | socket.SOCK_RDM: 'rdm', 15 | socket.SOCK_SEQPACKET: 'seqpkg' 16 | } 17 | -------------------------------------------------------------------------------- /backend/app/lib/logger.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | import socket 9 | import logging 10 | from flask import request 11 | from logging.handlers import RotatingFileHandler 12 | 13 | 14 | class CustomFormatter(logging.Formatter): 15 | 16 | def format(self, record): 17 | try: 18 | setattr(record, 'url', request.path) 19 | except RuntimeError: 20 | setattr(record, 'url', 'Null') 21 | setattr(record, 'hostname', socket.gethostname()) 22 | return logging.Formatter.format(self, record) 23 | 24 | 25 | class AppLogger: 26 | def __init__(self, app): 27 | self.app = app 28 | 29 | @staticmethod 30 | def get_file_handler(handler_config): 31 | format_strings = [ 32 | '%(asctime)s', 33 | '%(levelname)s', 34 | '%(hostname)s', 35 | '[URL:%(url)s]', 36 | '[%(filename)s:%(lineno)d]', 37 | '%(message)s' 38 | ] 39 | 40 | file_format = CustomFormatter(' '.join(format_strings)) 41 | file_handle = RotatingFileHandler(filename=handler_config.get('LOG_PATH', 'app.log'), mode='a', 42 | maxBytes=handler_config.get('MAX_BYTES', 1024 * 1024 * 100), 43 | backupCount=handler_config.get('BACKUP_COUNT', 7)) 44 | file_handle.setFormatter(file_format) 45 | file_handle.setLevel(handler_config.get('LOG_LEVEL', 'ERROR')) 46 | return file_handle 47 | 48 | def init_handlers(self): 49 | for handle_name, handler_config in self.app.config['LOG_HANDLERS'].items(): 50 | fn_name = 'get_{0}_handler'.format(handle_name.lower()) 51 | handler = getattr(self, fn_name)(handler_config) 52 | self.app.logger.addHandler(handler) 53 | -------------------------------------------------------------------------------- /backend/app/lib/network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | import subprocess 9 | 10 | 11 | def get_connections(): 12 | conn_cmd = 'netstat -natp' 13 | conn_out = subprocess.check_output(conn_cmd, shell=True) 14 | conn_lines = conn_out.splitlines()[2:] 15 | count = len(conn_lines) 16 | conns = {'conns': list(), 'count': count} 17 | for line in conn_lines: 18 | items = [item.strip() for item in line.split(' ') if item.strip()] 19 | conns['conns'].append({ 20 | 'status': items[5], 21 | 'recv_q': int(items[1]), 22 | 'send_q': int(items[2]), 23 | 'l_addr': items[3], 24 | 'r_addr': items[4], 25 | 'pid': items[6].split('/')[0] 26 | }) 27 | 28 | return conns 29 | 30 | 31 | def get_iface_status(): 32 | iface_files = '/proc/net/dev' 33 | iface_info = dict() 34 | with open(iface_files, 'r') as ifp: 35 | lines = ifp.readlines()[2:] 36 | for line in lines: 37 | items = [item.strip() for item in line.split(' ') if item.strip()] 38 | 39 | iface_info[items[0][:-1]] = { 40 | 'receive_bytes': int(items[1]), 41 | 'receive_packets': int(items[2]), 42 | 'send_bytes': int(items[9]), 43 | 'send_packets': int(items[10]) 44 | } 45 | 46 | return iface_info 47 | -------------------------------------------------------------------------------- /backend/app/lib/system.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | import psutil 9 | import datetime 10 | import socket 11 | from app.lib.util import obj2dict 12 | from app.lib.const import SOCK_TYPE 13 | 14 | M = 1024 * 1024 15 | 16 | 17 | def get_loadavg(): 18 | load_file = '/proc/loadavg' 19 | 20 | with open(load_file, 'r') as lfp: 21 | line = lfp.readline() 22 | items = [item.strip() for item in line.split(' ') if item.strip()] 23 | return { 24 | '1min': float(items[0]) * 100, 25 | '3min': float(items[1]) * 100, 26 | '5min': float(items[2]) * 100 27 | } 28 | 29 | 30 | def _parse_cpu_fields(fields): 31 | field_list = [int(field) for field in fields] 32 | total = sum(field_list) 33 | return { 34 | 'total': total, 35 | 'user': field_list[1], 36 | 'nice': field_list[2], 37 | 'system': field_list[2], 38 | 'idle': field_list[3], 39 | 'busy': 100 - field_list[3], 40 | 'iowait': field_list[4], 41 | 'irq': field_list[5], 42 | 'soft_irq': field_list[6], 43 | 'steal': field_list[7], 44 | 'guest': field_list[8] 45 | } 46 | 47 | 48 | def get_cpu_stat(): 49 | cpu_stat_file = '/proc/stat' 50 | 51 | cpu_stat = dict(cpus=dict()) 52 | with open(cpu_stat_file, 'r') as cfp: 53 | for line in cfp.xreadlines(): 54 | fields = [field.strip() for field in line.split(' ') if field.strip()] 55 | if len(fields) < 2: 56 | continue 57 | 58 | field_name = fields[0] 59 | if field_name.startswith('cpu'): 60 | cpu_stat['cpus'][field_name] = _parse_cpu_fields(fields[1:]) 61 | elif field_name in ['ctxt', 'processes', 'procs_running', 'procs_blocked']: 62 | cpu_stat[field_name] = int(fields[1]) 63 | 64 | return cpu_stat 65 | 66 | 67 | def _proc2simple(proc): 68 | 69 | with proc.oneshot(): 70 | return { 71 | 'pid': proc.pid, 72 | 'name': proc.name(), 73 | 'username': proc.username(), 74 | 'create_time': datetime.datetime.fromtimestamp(proc.create_time()).strftime("%Y-%m-%d %H:%M:%S"), 75 | 'cpu_percent': round(proc.cpu_percent(), 2), 76 | 'memory_percent': round(proc.memory_percent(), 2), 77 | 'status': proc.status() 78 | } 79 | 80 | 81 | def get_intensive_processes(): 82 | procs = map(_proc2simple, psutil.process_iter()) 83 | cpu_intensive = sorted(procs, cmp=lambda x, y: x['cpu_percent'] < y['cpu_percent'], reverse=True)[0: 10] 84 | mem_intensive = sorted(procs, cmp=lambda x, y: x['memory_percent'] < y['memory_percent'], reverse=True)[0:10] 85 | 86 | return { 87 | 'cpu_intensive': cpu_intensive, 88 | 'mem_intensive': mem_intensive 89 | } 90 | 91 | 92 | def get_simple_process(pids): 93 | simple_process = [] 94 | for process in psutil.process_iter(): 95 | if pids and process.pid not in pids: 96 | continue 97 | 98 | simple_process.append(_proc2simple(process)) 99 | 100 | return simple_process 101 | 102 | 103 | def get_children(nodes_dict, parent): 104 | 105 | nodes = nodes_dict[parent] 106 | children = list() 107 | 108 | for child in nodes: 109 | children.append({ 110 | 'process': child, 111 | 'children': get_children(nodes_dict, child) 112 | }) 113 | 114 | return children 115 | 116 | 117 | def transfer_nodes2tree(nodes_dict, child_nodes): 118 | 119 | tree = list() 120 | for parent, cur_children in nodes_dict.items(): 121 | if parent not in child_nodes: # first level 122 | tree.append({ 123 | 'process': parent, 124 | 'children': get_children(nodes_dict, parent) 125 | }) 126 | return tree 127 | 128 | 129 | def conn2json(conn): 130 | laddr = map(str, conn.laddr) 131 | raddr = map(str, conn.raddr) 132 | return { 133 | 'fd': conn.fd, 134 | 'laddr': ':'.join(laddr), 135 | 'raddr': ':'.join(raddr), 136 | 'status': conn.status, 137 | 'type': SOCK_TYPE.get(socket.SOCK_STREAM, 'raw') 138 | } 139 | 140 | 141 | def get_pstree(): 142 | 143 | nodes_dict = dict() 144 | child_nodes = [] 145 | for process in psutil.process_iter(): 146 | cur_child_nodes = ['{0}-{1}'.format(child.pid, child.name()) for child in process.children()] 147 | nodes_dict['{0}-{1}'.format(process.pid, process.name())] = cur_child_nodes 148 | child_nodes.extend(cur_child_nodes) 149 | 150 | return transfer_nodes2tree(nodes_dict, child_nodes) 151 | 152 | 153 | def children_processor(children): 154 | return [{'pid': child.pid, 155 | 'name': child.name(), 156 | 'status': child.status(), 157 | 'create_time': datetime.datetime.fromtimestamp( 158 | child.create_time()).strftime("%Y-%m-%d %H:%M:%S")} for child in children] 159 | 160 | 161 | def get_process_detail(pid): 162 | for process in psutil.process_iter(): 163 | if process.pid == pid: 164 | cur_process = process 165 | break 166 | else: 167 | raise Exception('No such process: {0}'.format(pid)) 168 | 169 | override = { 170 | type(cur_process): { 171 | 'children': children_processor, 172 | 'parent': lambda p: {'pid': p.pid, 'name': p.name()} if p else None, 173 | 'cmdline': lambda lines: ' '.join(lines), 174 | 'connections': lambda conns: map(conn2json, conns), 175 | 'create_time': lambda timestamp: datetime.datetime.fromtimestamp( 176 | timestamp).strftime("%Y-%m-%d %H:%M:%S") 177 | } 178 | } 179 | 180 | ignore = { 181 | type(cur_process): ['kill', 'oneshot', 'environ', 'send_signal', 'suspend', 182 | 'as_dict', 'uids', 'gids', 'terminal', 'is_running', 183 | 'ionice', 'rlimit', 'memory_info_ex', 'memory_info', 184 | 'resume', 'terminate', 'wait', 'memory_maps'] 185 | } 186 | 187 | return obj2dict(cur_process, methods=True, 188 | override=override, ignore=ignore) 189 | 190 | 191 | def search_process(q): 192 | process_list = [] 193 | for process in psutil.process_iter(): 194 | name = process.name() 195 | cmdline = ''.join(process.cmdline()) 196 | if name != '' and name.find(q) != -1: 197 | idx = name.find(q) 198 | process_list.append('{0}-{1}'.format(process.pid, name)) 199 | elif cmdline != '' and cmdline.find(q) != -1: 200 | idx = cmdline.find(q) 201 | process_list.append('{0}-{1}'.format(process.pid, cmdline[idx:])) 202 | elif str(process.pid).find(q) != -1: 203 | process_list.append('{0}-{1}'.format(process.pid, name)) 204 | 205 | return process_list 206 | 207 | 208 | def get_mem_info(): 209 | memory = psutil.virtual_memory() 210 | return { 211 | 'total': round(memory.total / M, 2), 212 | 'available': round(memory.available / M, 2), 213 | 'active': round(memory.active / M , 2), 214 | 'free': round(memory.free / M, 2), 215 | 'buffers': round(memory.buffers / M, 2), 216 | 'cached': round(memory.cached / M, 2), 217 | 'percent': round(memory.percent, 2) 218 | } 219 | 220 | 221 | def get_io_counters(): 222 | io_counters = psutil.disk_io_counters() 223 | 224 | return { 225 | 'read_count': io_counters.read_count, 226 | 'read_bytes': io_counters.read_bytes, 227 | 'write_count': io_counters.write_count, 228 | 'write_bytes': io_counters.write_bytes, 229 | 'read_time': io_counters.read_time, 230 | 'write_time': io_counters.write_time, 231 | } 232 | -------------------------------------------------------------------------------- /backend/app/lib/util.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | import numbers 9 | import datetime 10 | 11 | 12 | def bytes2human(bytes, suffix='B'): 13 | for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: 14 | if abs(bytes) < 1024: 15 | return '%3.2f%s%s' %(bytes, unit, suffix) 16 | 17 | bytes /= 1024.0 18 | 19 | return "%.1f%s%s" % (bytes, 'Yi', suffix) 20 | 21 | 22 | def _obj2dict(obj, methods, override, ignore): 23 | res = dict() 24 | my_ignore = ignore.get(type(obj), []) if ignore else [] 25 | my_override = override.get(type(obj), {}) if override else {} 26 | 27 | for key in dir(obj): 28 | if key.startswith('_'): 29 | continue 30 | if key in my_ignore: 31 | continue 32 | 33 | try: 34 | if callable(getattr(obj, key)) and methods: 35 | val = getattr(obj, key)() 36 | else: 37 | val = getattr(obj, key) 38 | except Exception: 39 | continue 40 | 41 | if key in my_override: 42 | res[key] = my_override[key](val) 43 | else: 44 | res[key] = obj2dict(val, methods, override, ignore) 45 | 46 | return res 47 | 48 | 49 | def obj2dict(obj, methods=False, override=None, ignore=None): 50 | simple_types = (basestring, numbers.Number) 51 | if obj is None: 52 | return None 53 | if isinstance(obj, simple_types): 54 | return obj 55 | elif isinstance(obj, (datetime.date, datetime.datetime)): 56 | return obj.strftime("%Y-%m-%d %H:%M:%S") 57 | elif isinstance(obj, dict): 58 | for key, val in obj.items(): 59 | obj[key] = obj2dict(val, methods, override, ignore) 60 | return obj 61 | elif type(obj) in (list, tuple): 62 | item_list = [] 63 | for item in obj: 64 | item_list.append(obj2dict(item, methods, override, ignore)) 65 | return item_list 66 | else: 67 | return _obj2dict(obj, methods, override, ignore) 68 | 69 | -------------------------------------------------------------------------------- /backend/app/main.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | from flask import Flask, render_template, make_response, jsonify 9 | from app.make_app import MakeApp 10 | 11 | app = Flask(__name__, instance_relative_config=True) 12 | 13 | with app.app_context(): 14 | make = MakeApp(app) 15 | make.init_all() 16 | 17 | 18 | @app.errorhandler(404) 19 | def page_not_found(e): 20 | return make_response(jsonify(msg=str(e), code=404), 404) 21 | 22 | 23 | @app.errorhandler(401) 24 | def unauthorized_visit(e): 25 | return make_response(jsonify(msg=str(e), code=401), 401) 26 | 27 | 28 | @app.errorhandler(500) 29 | def unauthorized_visit(e): 30 | return make_response(jsonify(msg=str(e), code=500), 500) 31 | 32 | 33 | @app.route('/', methods=['GET']) 34 | def index(): 35 | return render_template('index.html') 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /backend/app/make_app.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | from flask import request, session, abort 9 | from app.lib.logger import AppLogger 10 | 11 | 12 | class MakeApp: 13 | def __init__(self, app): 14 | self.app = app 15 | 16 | def init_all(self): 17 | self.init_config() 18 | self.init_log() 19 | self.init_before() 20 | self.init_modules() 21 | 22 | def init_config(self): 23 | self.app.config.from_object('config') 24 | self.app.config.from_pyfile('config.py') 25 | 26 | def init_log(self): 27 | AppLogger(self.app).init_handlers() 28 | 29 | def init_before(self): 30 | @self.app.before_request 31 | def before_request(): 32 | ip_list = request.headers.getlist("X-Forwarded-For") 33 | session['remote_address'] = ip_list[0].split(',')[0] if ip_list else request.remote_addr 34 | if self.app.config['AUTH_IP'] and session['remote_address'] not in self.app.config['AUTH_IP']: 35 | abort(401) 36 | if not session.get('login') and request.path.startswith('/api'): 37 | abort(401) 38 | 39 | def init_modules(self): 40 | from app.views import * 41 | 42 | modules = ( 43 | (basic_bp, '/api/basic'), 44 | (network_bp, '/api/network'), 45 | (system_bp, '/api/system') 46 | ) 47 | 48 | for module, url_prefix in modules: 49 | self.app.register_blueprint(module, url_prefix=url_prefix) 50 | -------------------------------------------------------------------------------- /backend/app/views/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | from app.views.basic import * 9 | from app.views.system import * 10 | from app.views.network import * 11 | from app.views.auth import * 12 | -------------------------------------------------------------------------------- /backend/app/views/auth.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | import time 9 | from flask import request, session, make_response, jsonify, abort 10 | from simplepam import authenticate 11 | from app.main import app 12 | 13 | 14 | @app.route('/login', methods=['POST']) 15 | def login(): 16 | params = request.json 17 | auth_users = app.config.get('AUTH_USER', []) 18 | try: 19 | username = str(params.get('username', '').strip()) 20 | password = str(params.get('password', '').strip()) 21 | 22 | if auth_users and username not in auth_users: 23 | abort(401, msg='user {0} has no privilege login'.format(username)) 24 | 25 | if username and password: 26 | auth = authenticate(username, password, service='login', encoding='utf-8', resetcred=True) 27 | if auth: 28 | app.logger.info('user {0} login from {1}'.format(username, session['remote_address'])) 29 | session['login'] = '{0}-{1}'.format(username, time.time()) 30 | return make_response(jsonify(code=200, data={'user': username, 'code': 200}), 200) 31 | else: 32 | abort(401, msg='username and password is required') 33 | except Exception as e: 34 | abort(401, msg=str(e)) 35 | 36 | abort(401, msg='auth failed') 37 | -------------------------------------------------------------------------------- /backend/app/views/basic.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | from flask import make_response, jsonify, Blueprint 9 | from app.lib import basic 10 | 11 | basic_bp = Blueprint('basic', __name__) 12 | 13 | 14 | @basic_bp.route('/', methods=['GET']) 15 | def basic_info(): 16 | basic_item = { 17 | 'general': basic.get_general(), 18 | 'cpu': basic.get_cpu_info(), 19 | 'disk': basic.get_disk_info(), 20 | 'net': basic.get_net_info() 21 | } 22 | return make_response(jsonify(code=200, data=basic_item), 200) 23 | 24 | 25 | @basic_bp.route('/general', methods=['GET']) 26 | def basic_general(): 27 | return make_response(jsonify(code=200, data=basic.get_general())) 28 | 29 | 30 | @basic_bp.route('/cpu', methods=['GET']) 31 | def basic_cpu(): 32 | return make_response(jsonify(code=200, data=basic.get_cpu_info())) 33 | 34 | 35 | @basic_bp.route('/disk', methods=['GET']) 36 | def basic_net(): 37 | return make_response(jsonify(code=200, data=basic.get_net_info())) 38 | -------------------------------------------------------------------------------- /backend/app/views/network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | from flask import make_response, jsonify, Blueprint 9 | from app.handler import net_handler 10 | 11 | network_bp = Blueprint('network_bp', __name__) 12 | 13 | 14 | @network_bp.route('/') 15 | def network_info(): 16 | data = net_handler.get_network_info() 17 | return make_response(jsonify(data=data, code=200), 200) 18 | 19 | 20 | @network_bp.route('/conn/') 21 | def network_conns(): 22 | data = net_handler.get_network_info() 23 | return make_response(jsonify(data=data.get('connections', {}), code=200), 200) 24 | 25 | 26 | @network_bp.route('/iface') 27 | def network_iface(): 28 | data = net_handler.get_network_info() 29 | return make_response(jsonify(data=data.get('iface_status', []), code=200), 200) 30 | -------------------------------------------------------------------------------- /backend/app/views/system.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | from flask import make_response, jsonify, Blueprint, request 9 | from app.lib import system 10 | from app.handler import system_handler 11 | system_bp = Blueprint('system_bp', __name__) 12 | 13 | 14 | @system_bp.route('/') 15 | def system_info(): 16 | data = system_handler.get_system() 17 | return make_response(jsonify(code=200, data=data), 200) 18 | 19 | 20 | @system_bp.route('/load') 21 | def system_load(): 22 | data = system_handler.get_system() 23 | return make_response(jsonify(code=200, data=data.get('loadavg', {})), 200) 24 | 25 | 26 | @system_bp.route('/cpu_stat') 27 | def system_cpu_stat(): 28 | data = system_handler.get_system() 29 | return make_response(jsonify(code=200, data=data.get('cpu_stat', {})), 200) 30 | 31 | 32 | @system_bp.route('/processes') 33 | def system_intensive_processes(): 34 | data = system_handler.get_system() 35 | return make_response(jsonify(code=200, data=data.get('intensive_processes', {})), 200) 36 | 37 | 38 | @system_bp.route('/io_counters') 39 | def system_io_counters(): 40 | data = system_handler.get_system() 41 | return make_response(jsonify(code=200, data=data.get('io_counters', {})), 200) 42 | 43 | 44 | @system_bp.route('/mem') 45 | def system_mem_info(): 46 | data = system_handler.get_system() 47 | return make_response(jsonify(code=200, data=data.get('mem_info', {}))) 48 | 49 | 50 | @system_bp.route('/process/') 51 | def system_process_detail(pid): 52 | return make_response(jsonify(code=200, data=system.get_process_detail(pid))) 53 | 54 | 55 | @system_bp.route('/process_search') 56 | def system_process_search(): 57 | q = request.values.get('q', '') 58 | return make_response(jsonify(code=200, data=system.search_process(q))) 59 | 60 | 61 | @system_bp.route('/process_simple') 62 | def system_process_simple(): 63 | pids = request.values.get('pids', []) 64 | return make_response(jsonify(code=200, data=system.get_simple_process(pids))) 65 | -------------------------------------------------------------------------------- /backend/config.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | DEBUG = False 9 | 10 | HOST = '0.0.0.0' 11 | PORT = '1993' 12 | SECRET_KEY = 'qwertyuiopasdfghjklzxcvbnm' 13 | LOG_HANDLERS = { 14 | 'FILE': { 15 | 'LOG_PATH': 'logs/app.log', 16 | 'LOG_LEVEL': 'DEBUG' if DEBUG else 'WARNING', 17 | 'MAX_BYTES': 1024 * 1024 * 100, 18 | 'BACKUP_COUNT': 7 19 | } 20 | } 21 | 22 | AUTH_USER = [] 23 | AUTH_IP = [] 24 | -------------------------------------------------------------------------------- /backend/gun.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import multiprocessing 3 | 4 | bind = "0.0.0.0:8080" 5 | pidfile = 'var/gunicorn.pid' 6 | workers = multiprocessing.cpu_count() * 2 + 1 7 | 8 | worker_class = 'sync' 9 | backlog = 2048 10 | daemon = True 11 | loglevel = 'info' 12 | accesslog = 'logs/access.log' 13 | errorlog = 'logs/error.log' 14 | access_log_format = "%({X-Real-IP}i)s %(h)s %(l)s %(u)s %(t)s %(r)s %(s)s %(b)s %(f)s %(a)s" 15 | -------------------------------------------------------------------------------- /backend/requirements.txt: -------------------------------------------------------------------------------- 1 | appdirs==1.4.3 2 | click==6.7 3 | Flask==0.12.1 4 | Flask-Script==2.0.5 5 | gunicorn==19.7.1 6 | itsdangerous==0.24 7 | Jinja2==2.9.6 8 | MarkupSafe==1.0 9 | packaging==16.8 10 | psutil==5.2.2 11 | pyparsing==2.2.0 12 | simplepam==0.1.5 13 | six==1.10.0 14 | uptime==3.0.1 15 | Werkzeug==0.12.1 16 | -------------------------------------------------------------------------------- /backend/run.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | __author__ = allen 5 | 6 | """ 7 | 8 | from flask_script import Manager, Server 9 | from flask_script.commands import ShowUrls, Clean 10 | 11 | from app.main import app 12 | 13 | manager = Manager(app) 14 | 15 | manager.add_command('clean', Clean()) 16 | manager.add_command('url', ShowUrls()) 17 | manager.add_command('server', Server(host=app.config.get('HOST', '0.0.0.0'), 18 | port=app.config.get('PORT', 8080))) 19 | 20 | if __name__ == '__main__': 21 | manager.run() 22 | -------------------------------------------------------------------------------- /frontend/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["es2015", { "modules": false }], 4 | "stage-2" 5 | ], 6 | "plugins": ["transform-runtime"], 7 | "comments": false, 8 | "env": { 9 | "test": { 10 | "plugins": [ "istanbul" ] 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /frontend/.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 4 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | 3 | node_modules/ 4 | *.log 5 | dist/ 6 | -------------------------------------------------------------------------------- /frontend/build/build.js: -------------------------------------------------------------------------------- 1 | // https://github.com/shelljs/shelljs 2 | require('./check-versions')() 3 | 4 | process.env.NODE_ENV = 'production' 5 | 6 | var ora = require('ora') 7 | var path = require('path') 8 | var chalk = require('chalk') 9 | var shell = require('shelljs') 10 | var webpack = require('webpack') 11 | var config = require('../config') 12 | var webpackConfig = require('./webpack.prod.conf') 13 | 14 | var spinner = ora('building for production...') 15 | spinner.start() 16 | 17 | var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory) 18 | shell.rm('-rf', assetsPath) 19 | shell.mkdir('-p', assetsPath) 20 | shell.config.silent = true 21 | shell.cp('-R', 'static/*', assetsPath) 22 | shell.config.silent = false 23 | 24 | webpack(webpackConfig, function (err, stats) { 25 | spinner.stop() 26 | if (err) throw err 27 | process.stdout.write(stats.toString({ 28 | colors: true, 29 | modules: false, 30 | children: false, 31 | chunks: false, 32 | chunkModules: false 33 | }) + '\n\n') 34 | 35 | console.log(chalk.cyan(' Build complete.\n')) 36 | console.log(chalk.yellow( 37 | ' Tip: built files are meant to be served over an HTTP server.\n' + 38 | ' Opening index.html over file:// won\'t work.\n' 39 | )) 40 | }) 41 | -------------------------------------------------------------------------------- /frontend/build/check-versions.js: -------------------------------------------------------------------------------- 1 | var chalk = require('chalk') 2 | var semver = require('semver') 3 | var packageConfig = require('../package.json') 4 | 5 | function exec (cmd) { 6 | return require('child_process').execSync(cmd).toString().trim() 7 | } 8 | 9 | var versionRequirements = [ 10 | { 11 | name: 'node', 12 | currentVersion: semver.clean(process.version), 13 | versionRequirement: packageConfig.engines.node 14 | }, 15 | { 16 | name: 'npm', 17 | currentVersion: exec('npm --version'), 18 | versionRequirement: packageConfig.engines.npm 19 | } 20 | ] 21 | 22 | module.exports = function () { 23 | var warnings = [] 24 | for (var i = 0; i < versionRequirements.length; i++) { 25 | var mod = versionRequirements[i] 26 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 27 | warnings.push(mod.name + ': ' + 28 | chalk.red(mod.currentVersion) + ' should be ' + 29 | chalk.green(mod.versionRequirement) 30 | ) 31 | } 32 | } 33 | 34 | if (warnings.length) { 35 | console.log('') 36 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 37 | console.log() 38 | for (var i = 0; i < warnings.length; i++) { 39 | var warning = warnings[i] 40 | console.log(' ' + warning) 41 | } 42 | console.log() 43 | process.exit(1) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /frontend/build/dev-client.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | require('eventsource-polyfill') 3 | var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') 4 | 5 | hotClient.subscribe(function (event) { 6 | if (event.action === 'reload') { 7 | window.location.reload() 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /frontend/build/dev-server.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | var config = require('../config') 4 | if (!process.env.NODE_ENV) { 5 | process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) 6 | } 7 | 8 | var opn = require('opn') 9 | var path = require('path') 10 | var express = require('express') 11 | var webpack = require('webpack') 12 | var proxyMiddleware = require('http-proxy-middleware') 13 | var webpackConfig = require('./webpack.dev.conf') 14 | 15 | // default port where dev server listens for incoming traffic 16 | var port = process.env.PORT || config.dev.port 17 | // automatically open browser, if not set will be false 18 | var autoOpenBrowser = !!config.dev.autoOpenBrowser 19 | // Define HTTP proxies to your custom API backend 20 | // https://github.com/chimurai/http-proxy-middleware 21 | var proxyTable = config.dev.proxyTable 22 | 23 | var app = express() 24 | var compiler = webpack(webpackConfig) 25 | 26 | var devMiddleware = require('webpack-dev-middleware')(compiler, { 27 | publicPath: webpackConfig.output.publicPath, 28 | quiet: true 29 | }) 30 | 31 | var hotMiddleware = require('webpack-hot-middleware')(compiler, { 32 | log: () => {} 33 | }) 34 | // force page reload when html-webpack-plugin template changes 35 | compiler.plugin('compilation', function (compilation) { 36 | compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { 37 | hotMiddleware.publish({ action: 'reload' }) 38 | cb() 39 | }) 40 | }) 41 | 42 | // proxy api requests 43 | Object.keys(proxyTable).forEach(function (context) { 44 | var options = proxyTable[context] 45 | if (typeof options === 'string') { 46 | options = { target: options } 47 | } 48 | app.use(proxyMiddleware(options.filter || context, options)) 49 | }) 50 | 51 | // handle fallback for HTML5 history API 52 | app.use(require('connect-history-api-fallback')()) 53 | 54 | // serve webpack bundle output 55 | app.use(devMiddleware) 56 | 57 | // enable hot-reload and state-preserving 58 | // compilation error display 59 | app.use(hotMiddleware) 60 | 61 | // serve pure static assets 62 | var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) 63 | app.use(staticPath, express.static('./static')) 64 | 65 | var uri = 'http://localhost:' + port 66 | 67 | devMiddleware.waitUntilValid(function () { 68 | console.log('> Listening at ' + uri + '\n') 69 | }) 70 | 71 | module.exports = app.listen(port, function (err) { 72 | if (err) { 73 | console.log(err) 74 | return 75 | } 76 | 77 | // when env is testing, don't need open it 78 | if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { 79 | opn(uri) 80 | } 81 | }) 82 | -------------------------------------------------------------------------------- /frontend/build/utils.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var config = require('../config') 3 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 4 | 5 | exports.assetsPath = function (_path) { 6 | var assetsSubDirectory = process.env.NODE_ENV === 'production' 7 | ? config.build.assetsSubDirectory 8 | : config.dev.assetsSubDirectory 9 | return path.posix.join(assetsSubDirectory, _path) 10 | } 11 | 12 | exports.cssLoaders = function (options) { 13 | options = options || {} 14 | // generate loader string to be used with extract text plugin 15 | function generateLoaders (loaders) { 16 | var sourceLoader = loaders.map(function (loader) { 17 | var extraParamChar 18 | if (/\?/.test(loader)) { 19 | loader = loader.replace(/\?/, '-loader?') 20 | extraParamChar = '&' 21 | } else { 22 | loader = loader + '-loader' 23 | extraParamChar = '?' 24 | } 25 | return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '') 26 | }).join('!') 27 | 28 | // Extract CSS when that option is specified 29 | // (which is the case during production build) 30 | if (options.extract) { 31 | return ExtractTextPlugin.extract({ 32 | use: sourceLoader, 33 | fallback: 'vue-style-loader' 34 | }) 35 | } else { 36 | return ['vue-style-loader', sourceLoader].join('!') 37 | } 38 | } 39 | 40 | // http://vuejs.github.io/vue-loader/en/configurations/extract-css.html 41 | return { 42 | css: generateLoaders(['css']), 43 | postcss: generateLoaders(['css']), 44 | less: generateLoaders(['css', 'less']), 45 | sass: generateLoaders(['css', 'sass?indentedSyntax']), 46 | scss: generateLoaders(['css', 'sass']), 47 | stylus: generateLoaders(['css', 'stylus']), 48 | styl: generateLoaders(['css', 'stylus']) 49 | } 50 | } 51 | 52 | // Generate loaders for standalone style files (outside of .vue) 53 | exports.styleLoaders = function (options) { 54 | var output = [] 55 | var loaders = exports.cssLoaders(options) 56 | for (var extension in loaders) { 57 | var loader = loaders[extension] 58 | output.push({ 59 | test: new RegExp('\\.' + extension + '$'), 60 | loader: loader 61 | }) 62 | } 63 | return output 64 | } 65 | -------------------------------------------------------------------------------- /frontend/build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils'); 2 | var config = require('../config'); 3 | var isProduction = process.env.NODE_ENV === 'production'; 4 | 5 | module.exports = { 6 | loaders: utils.cssLoaders({ 7 | sourceMap: isProduction 8 | ? config.build.productionSourceMap 9 | : config.dev.cssSourceMap, 10 | extract: isProduction 11 | }), 12 | postcss: [ 13 | require('autoprefixer')({ 14 | browsers: ['last 2 versions'] 15 | }) 16 | ] 17 | }; 18 | -------------------------------------------------------------------------------- /frontend/build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var utils = require('./utils') 3 | var webpack = require('webpack') 4 | var config = require('../config') 5 | var vueLoaderConfig = require('./vue-loader.conf') 6 | 7 | function resolve (dir) { 8 | return path.join(__dirname, '..', dir) 9 | } 10 | 11 | module.exports = { 12 | entry: { 13 | app: ['babel-polyfill','./src/main.js'] 14 | }, 15 | output: { 16 | path: config.build.assetsRoot, 17 | filename: '[name].js', 18 | publicPath: process.env.NODE_ENV === 'production' 19 | ? config.build.assetsPublicPath 20 | : config.dev.assetsPublicPath 21 | }, 22 | resolve: { 23 | extensions: ['.js', '.vue', '.json'], 24 | modules: [ 25 | resolve('src'), 26 | resolve('node_modules') 27 | ], 28 | alias: { 29 | 'vue$': 'vue/dist/vue.common.js', 30 | 'src': resolve('src'), 31 | 'assets': resolve('src/assets'), 32 | 'components': resolve('src/components') 33 | } 34 | }, 35 | module: { 36 | rules: [ 37 | { 38 | test: /\.vue$/, 39 | loader: 'vue-loader' 40 | }, 41 | { 42 | test: /\.js$/, 43 | loader: 'babel-loader', 44 | include: [resolve('src'), resolve('test')] 45 | }, 46 | { 47 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 48 | loader: 'url-loader', 49 | query: { 50 | limit: 10000, 51 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 52 | } 53 | }, 54 | { 55 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 56 | loader: 'url-loader', 57 | query: { 58 | limit: 10000, 59 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 60 | } 61 | } 62 | ] 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /frontend/build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var webpack = require('webpack') 3 | var config = require('../config') 4 | var merge = require('webpack-merge') 5 | var baseWebpackConfig = require('./webpack.base.conf') 6 | var HtmlWebpackPlugin = require('html-webpack-plugin') 7 | var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 8 | 9 | // add hot-reload related code to entry chunks 10 | Object.keys(baseWebpackConfig.entry).forEach(function (name) { 11 | baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) 12 | }) 13 | 14 | module.exports = merge(baseWebpackConfig, { 15 | module: { 16 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) 17 | }, 18 | // cheap-module-eval-source-map is faster for development 19 | devtool: '#cheap-module-eval-source-map', 20 | plugins: [ 21 | new webpack.DefinePlugin({ 22 | 'process.env': config.dev.env 23 | }), 24 | // https://github.com/glenjamin/webpack-hot-middleware#installation--usage 25 | new webpack.HotModuleReplacementPlugin(), 26 | new webpack.NoEmitOnErrorsPlugin(), 27 | // https://github.com/ampedandwired/html-webpack-plugin 28 | new HtmlWebpackPlugin({ 29 | filename: 'index.html', 30 | template: 'index.html', 31 | inject: true 32 | }), 33 | new FriendlyErrorsPlugin() 34 | ] 35 | }) 36 | -------------------------------------------------------------------------------- /frontend/build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var utils = require('./utils') 3 | var webpack = require('webpack') 4 | var config = require('../config') 5 | var merge = require('webpack-merge') 6 | var baseWebpackConfig = require('./webpack.base.conf') 7 | var HtmlWebpackPlugin = require('html-webpack-plugin') 8 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 9 | var env = config.build.env 10 | 11 | var webpackConfig = merge(baseWebpackConfig, { 12 | module: { 13 | rules: utils.styleLoaders({ 14 | sourceMap: config.build.productionSourceMap, 15 | extract: true 16 | }) 17 | }, 18 | devtool: config.build.productionSourceMap ? '#source-map' : false, 19 | output: { 20 | path: config.build.assetsRoot, 21 | filename: utils.assetsPath('js/[name].[chunkhash].js'), 22 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 23 | }, 24 | plugins: [ 25 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 26 | new webpack.DefinePlugin({ 27 | 'process.env': env 28 | }), 29 | new webpack.optimize.UglifyJsPlugin({ 30 | compress: { 31 | warnings: false 32 | }, 33 | sourceMap: true 34 | }), 35 | // extract css into its own file 36 | new ExtractTextPlugin({ 37 | filename: utils.assetsPath('css/[name].[contenthash].css') 38 | }), 39 | // generate dist index.html with correct asset hash for caching. 40 | // you can customize output by editing /index.html 41 | // see https://github.com/ampedandwired/html-webpack-plugin 42 | new HtmlWebpackPlugin({ 43 | filename: config.build.index, 44 | template: 'index.html', 45 | inject: true, 46 | minify: { 47 | removeComments: true, 48 | collapseWhitespace: true, 49 | removeAttributeQuotes: true 50 | // more options: 51 | // https://github.com/kangax/html-minifier#options-quick-reference 52 | }, 53 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin 54 | chunksSortMode: 'dependency' 55 | }), 56 | // split vendor js into its own file 57 | new webpack.optimize.CommonsChunkPlugin({ 58 | name: 'vendor', 59 | minChunks: function (module, count) { 60 | // any required modules inside node_modules are extracted to vendor 61 | return ( 62 | module.resource && 63 | /\.js$/.test(module.resource) && 64 | module.resource.indexOf( 65 | path.join(__dirname, '../node_modules') 66 | ) === 0 67 | ) 68 | } 69 | }), 70 | // extract webpack runtime and module manifest to its own file in order to 71 | // prevent vendor hash from being updated whenever app bundle is updated 72 | new webpack.optimize.CommonsChunkPlugin({ 73 | name: 'manifest', 74 | chunks: ['vendor'] 75 | }) 76 | ] 77 | }) 78 | 79 | if (config.build.productionGzip) { 80 | var CompressionWebpackPlugin = require('compression-webpack-plugin') 81 | 82 | webpackConfig.plugins.push( 83 | new CompressionWebpackPlugin({ 84 | asset: '[path].gz[query]', 85 | algorithm: 'gzip', 86 | test: new RegExp( 87 | '\\.(' + 88 | config.build.productionGzipExtensions.join('|') + 89 | ')$' 90 | ), 91 | threshold: 10240, 92 | minRatio: 0.8 93 | }) 94 | ) 95 | } 96 | 97 | if (config.build.bundleAnalyzerReport) { 98 | var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 99 | webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 100 | } 101 | 102 | module.exports = webpackConfig; 103 | -------------------------------------------------------------------------------- /frontend/config/dev.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var prodEnv = require('./prod.env') 3 | 4 | module.exports = merge(prodEnv, { 5 | NODE_ENV: '"development"' 6 | }); 7 | 8 | -------------------------------------------------------------------------------- /frontend/config/index.js: -------------------------------------------------------------------------------- 1 | // see http://vuejs-templates.github.io/webpack for documentation. 2 | var path = require('path') 3 | module.exports = { 4 | build: { 5 | env: require('./prod.env'), 6 | index: path.resolve(__dirname, '../dist/index.html'), 7 | assetsRoot: path.resolve(__dirname, '../dist'), 8 | assetsSubDirectory: 'static', 9 | assetsPublicPath: '/', 10 | productionSourceMap: false, 11 | productionGzip: false, 12 | useDll: true, 13 | productionGzipExtensions: ['js', 'css'], 14 | bundleAnalyzerReport: process.env.npm_config_report 15 | }, 16 | dev: { 17 | env: require('./dev.env'), 18 | port: 8080, 19 | autoOpenBrowser: true, 20 | assetsSubDirectory: 'static', 21 | assetsPublicPath: '/', 22 | proxyTable: { 23 | '/':{ 24 | target:'http://allen01.tx:1993', 25 | changeOrigin:true, 26 | } 27 | }, 28 | cssSourceMap: true 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /frontend/config/prod.env.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | NODE_ENV: '"production"' 3 | } 4 | -------------------------------------------------------------------------------- /frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | alpaca 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "alpaca", 3 | "version": "1.0.0", 4 | "description": "简单的linux dashboard", 5 | "author": "echoyuanliang@gmail.com", 6 | "private": true, 7 | "scripts": { 8 | "dev": "node build/dev-server.js", 9 | "build": "node build/build.js" 10 | }, 11 | "dependencies": { 12 | "axios": "^0.15.3", 13 | "babel-polyfill": "^6.23.0", 14 | "element-ui": "^1.2.2", 15 | "vue": "^2.1.10", 16 | "vue-echarts-v3": "^1.0.3", 17 | "vue-logger": "^1.0.0", 18 | "vue-resource": "^1.3.1", 19 | "vue-router": "^2.2.0" 20 | }, 21 | "devDependencies": { 22 | "autoprefixer": "^6.7.2", 23 | "babel-core": "^6.22.1", 24 | "babel-loader": "^6.2.10", 25 | "babel-plugin-transform-runtime": "^6.22.0", 26 | "babel-preset-es2015": "^6.22.0", 27 | "babel-preset-stage-2": "^6.22.0", 28 | "babel-register": "^6.22.0", 29 | "chalk": "^1.1.3", 30 | "connect-history-api-fallback": "^1.3.0", 31 | "css-loader": "^0.26.1", 32 | "eventsource-polyfill": "^0.9.6", 33 | "express": "^4.14.1", 34 | "extract-text-webpack-plugin": "^2.0.0-rc.2", 35 | "file-loader": "^0.10.0", 36 | "friendly-errors-webpack-plugin": "^1.1.3", 37 | "function-bind": "^1.1.0", 38 | "html-webpack-plugin": "^2.28.0", 39 | "http-proxy-middleware": "^0.17.3", 40 | "opn": "^4.0.2", 41 | "ora": "^1.1.0", 42 | "semver": "^5.3.0", 43 | "shelljs": "^0.7.6", 44 | "url-loader": "^0.5.7", 45 | "vue-loader": "^10.3.0", 46 | "vue-style-loader": "^2.0.0", 47 | "vue-template-compiler": "^2.1.10", 48 | "webpack": "^2.2.1", 49 | "webpack-bundle-analyzer": "^2.2.1", 50 | "webpack-dev-middleware": "^1.10.0", 51 | "webpack-hot-middleware": "^2.16.1", 52 | "webpack-merge": "^2.6.1" 53 | }, 54 | "engines": { 55 | "node": ">= 4.0.0", 56 | "npm": ">= 3.0.0" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /frontend/src/App.vue: -------------------------------------------------------------------------------- 1 | 6 | 11 | -------------------------------------------------------------------------------- /frontend/src/api.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by zhangyuanliang on 2017/4/21. 3 | */ 4 | 5 | Vue = require('vue'); 6 | 7 | exports.login = Vue.resource('/login'); 8 | exports.basic = Vue.resource('/api/basic/'); 9 | exports.system = Vue.resource('/api/system/'); 10 | exports.network = Vue.resource('/api/network/'); 11 | exports.process = Vue.resource('/api/system/process/{pid}'); 12 | exports.iface_status = Vue.resource('/api/network/iface'); 13 | exports.search_process = Vue.resource('/api/system/process_search'); 14 | 15 | -------------------------------------------------------------------------------- /frontend/src/components/common/BarCharts.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 133 | -------------------------------------------------------------------------------- /frontend/src/components/common/Header.vue: -------------------------------------------------------------------------------- 1 | 32 | 33 | 39 | 69 | -------------------------------------------------------------------------------- /frontend/src/components/common/Home.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 18 | -------------------------------------------------------------------------------- /frontend/src/components/common/KvPanel.vue: -------------------------------------------------------------------------------- 1 | 27 | 28 | 56 | 57 | 77 | -------------------------------------------------------------------------------- /frontend/src/components/common/PieCharts.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 120 | -------------------------------------------------------------------------------- /frontend/src/components/common/SearchProcess.vue: -------------------------------------------------------------------------------- 1 | 18 | 19 | 26 | 27 | 64 | -------------------------------------------------------------------------------- /frontend/src/components/common/Sidebar.vue: -------------------------------------------------------------------------------- 1 | 14 | 15 | 26 | -------------------------------------------------------------------------------- /frontend/src/components/common/TimeLineCharts.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 176 | -------------------------------------------------------------------------------- /frontend/src/components/page/Basic.vue: -------------------------------------------------------------------------------- 1 | 103 | 104 | 142 | -------------------------------------------------------------------------------- /frontend/src/components/page/Login.vue: -------------------------------------------------------------------------------- 1 | 19 | 20 | 55 | 56 | 91 | -------------------------------------------------------------------------------- /frontend/src/components/page/Network.vue: -------------------------------------------------------------------------------- 1 | 93 | 94 | 277 | -------------------------------------------------------------------------------- /frontend/src/components/page/Process.vue: -------------------------------------------------------------------------------- 1 | 239 | 240 | 476 | -------------------------------------------------------------------------------- /frontend/src/components/page/System.vue: -------------------------------------------------------------------------------- 1 | 211 | 212 | 410 | -------------------------------------------------------------------------------- /frontend/src/config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | SYSTEM_IDLE: 6000, 3 | NET_IDLE: 6000, 4 | PROCESS_IDLE: 6000 5 | } 6 | -------------------------------------------------------------------------------- /frontend/src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | import App from './App'; 3 | import router from './router'; 4 | import VueResource from 'vue-resource' 5 | import ElementUI from 'element-ui'; 6 | import 'element-ui/lib/theme-default/index.css'; 7 | 8 | import "babel-polyfill"; 9 | import Resource from 'vue-resource'; 10 | import VueLogger from 'vue-logger'; 11 | 12 | 13 | Vue.use(Resource); 14 | Vue.use(ElementUI); 15 | Vue.use(VueResource); 16 | Vue.use(VueLogger); 17 | 18 | global.api = require('./api.js'); 19 | 20 | new Vue({ 21 | el: '#app', 22 | router, 23 | render: h => h(App) 24 | }).$mount('#app'); 25 | 26 | -------------------------------------------------------------------------------- /frontend/src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | import Router from 'vue-router'; 3 | import Auth from '../service/auth'; 4 | 5 | Vue.use(Router); 6 | 7 | const router = new Router({ 8 | routes: [ 9 | { 10 | path: '/', 11 | redirect: '/home' 12 | }, 13 | { 14 | path: '/home', 15 | component: resolve => require(['../components/common/Home.vue'], resolve), 16 | meta: { 17 | needAuth: true 18 | }, 19 | 20 | children:[ 21 | { 22 | path: '', 23 | component: resolve => require(['../components/page/Basic.vue'], resolve), 24 | meta: { 25 | needAuth: true 26 | } 27 | }, 28 | 29 | { 30 | path: '/system', 31 | meta: { 32 | needAuth: true 33 | }, 34 | component: resolve => require(['../components/page/System.vue'], resolve) 35 | }, 36 | 37 | { 38 | path: '/network', 39 | meta: { 40 | needAuth: true 41 | }, 42 | component: resolve => require(['../components/page/Network.vue'], resolve) 43 | 44 | }, 45 | 46 | { 47 | path: '/process/:pid', 48 | name: 'process', 49 | meta: { 50 | needAuth: true 51 | }, 52 | component: resolve => require(['../components/page/Process.vue'], resolve) 53 | } 54 | ] 55 | }, 56 | { 57 | path: '/login', 58 | component: resolve => require(['../components/page/Login.vue'], resolve), 59 | meta: { 60 | needAuth: false 61 | } 62 | } 63 | ] 64 | }); 65 | 66 | router.beforeEach((to, from, next) => { 67 | if (Auth.authenticated() || ! to.meta.needAuth) { 68 | next(); 69 | }else{ 70 | next({ 71 | path: '/login', 72 | query: {redirect: to.fullPath} 73 | }); 74 | } 75 | }); 76 | 77 | export default router; 78 | 79 | -------------------------------------------------------------------------------- /frontend/src/service/auth.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by zhangyuanliang on 2017/4/21. 3 | */ 4 | 5 | export default { 6 | login: function(context, creds, redirect) { 7 | return context.$http.post('/login', creds).then( (response) => { 8 | let data = response.data.data; 9 | localStorage.setItem('user', data.user); 10 | if(redirect){ 11 | context.$router.push(redirect); 12 | } 13 | }).catch((errors) => { 14 | context.$notify.error({ 15 | title: 'Login Failed', 16 | message: 'Unauthorized ip address or invalid username/password' 17 | }); 18 | console.error(errors); 19 | }); 20 | }, 21 | 22 | deleteAllCookies: function() { 23 | var cookies = document.cookie.split(";"); 24 | 25 | for (var i = 0; i < cookies.length; i++) { 26 | var cookie = cookies[i]; 27 | var eqPos = cookie.indexOf("="); 28 | var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; 29 | document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; 30 | } 31 | }, 32 | 33 | logout: function (context) { 34 | localStorage.removeItem('user'); 35 | this.deleteAllCookies(); 36 | context.$router.push('/login'); 37 | }, 38 | 39 | user: function () { 40 | return localStorage.getItem('user'); 41 | }, 42 | 43 | authenticated: function () { 44 | let user = localStorage.getItem('user'); 45 | if(user === undefined || user == null || user=='undefined'){ 46 | return false; 47 | } 48 | return true; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /frontend/static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/echoyuanliang/alpaca/e30e8398e31f8084b5c6934a5475b93ca9c16042/frontend/static/.gitkeep -------------------------------------------------------------------------------- /frontend/static/css/color-dark.css: -------------------------------------------------------------------------------- 1 | .header{ 2 | background-color: #242f42; 3 | } 4 | .login-wrap{ 5 | background: #324157; 6 | } 7 | .plugins-tips{ 8 | background: #eef1f6; 9 | } 10 | .plugins-tips a{ 11 | color: #20a0ff; 12 | } 13 | .el-upload--text em { 14 | color: #20a0ff; 15 | } 16 | .pure-button{ 17 | background: #20a0ff; 18 | } -------------------------------------------------------------------------------- /frontend/static/css/main.css: -------------------------------------------------------------------------------- 1 | *{margin:0;padding:0;} 2 | html,body,#app,.wrapper{ 3 | width:100%; 4 | height:100%; 5 | overflow: scroll; 6 | } 7 | body{ 8 | font-family:"Helvetica Neue",Helvetica, "microsoft yahei", arial, STHeiTi, sans-serif; 9 | } 10 | a{text-decoration: none} 11 | 12 | div.charts .vue-echarts{ 13 | height: 300px; 14 | } 15 | 16 | div.charts{ 17 | background-color: #EEF1F6; 18 | border: 2px solid #EEF1ea; 19 | -webkit-border-radius: 2px; 20 | -moz-border-radius: 2px; 21 | border-radius: 2px; 22 | } 23 | 24 | .row-section{ 25 | margin: 15px 2px; 26 | } 27 | 28 | .el-table th{ 29 | padding: 0 0; 30 | } 31 | 32 | .el-table th > .cell{ 33 | padding: 0 0; 34 | } 35 | 36 | .el-table td{ 37 | padding: 0 0; 38 | } 39 | 40 | .el-table td > .cell{ 41 | padding: 0 0; 42 | } 43 | 44 | .title-tag span.el-tag{ 45 | font-size: 18px; 46 | font-weight: bold; 47 | } 48 | 49 | div.process-detail{ 50 | font-size: 14px; 51 | color: #20a0ff; 52 | } 53 | -------------------------------------------------------------------------------- /frontend/static/js/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /screenshot/basic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/echoyuanliang/alpaca/e30e8398e31f8084b5c6934a5475b93ca9c16042/screenshot/basic.png -------------------------------------------------------------------------------- /screenshot/network.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/echoyuanliang/alpaca/e30e8398e31f8084b5c6934a5475b93ca9c16042/screenshot/network.png -------------------------------------------------------------------------------- /screenshot/process.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/echoyuanliang/alpaca/e30e8398e31f8084b5c6934a5475b93ca9c16042/screenshot/process.png -------------------------------------------------------------------------------- /screenshot/system.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/echoyuanliang/alpaca/e30e8398e31f8084b5c6934a5475b93ca9c16042/screenshot/system.png --------------------------------------------------------------------------------