Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dashboard #83

Merged
merged 8 commits into from
Sep 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
![logo](https://raw.githubusercontent.com/SelfhostedPro/Yacht/vue/readme_media/Yacht_logo_1_dark.png "templates")

[![Docker Hub Pulls](https://img.shields.io/docker/pulls/selfhostedpro/yacht?color=%234518f5&label=Docker%20Pulls&logo=docker&logoColor=%23403d3d&style=for-the-badge)](https://hub.docker.com/r/selfhostedpro/yacht)
[![Docker Image Size](https://img.shields.io/docker/image-size/selfhostedpro/yacht/vue?color=%234518f5&label=Image%20Size&logo=docker&logoColor=%23403d3d&style=for-the-badge)](https://hub.docker.com/r/selfhostedpro/yacht)

## Yacht
Yacht is a container management UI with a focus on templates and 1-click deployments.

Expand Down
1 change: 1 addition & 0 deletions backend/api/actions/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from datetime import datetime
import docker


def get_running_apps():
apps_list = []
dclient = docker.from_env()
Expand Down
53 changes: 51 additions & 2 deletions backend/api/routers/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@
from ..auth import get_active_user, User
from ..utils import websocket_auth, calculate_blkio_bytes, calculate_cpu_percent, calculate_cpu_percent2, calculate_network_bytes, get_app_stats

import docker
import docker as sdocker
import aiodocker
from datetime import datetime
import urllib.request
import json
import asyncio

containers.Base.metadata.create_all(bind=engine)

Expand Down Expand Up @@ -114,4 +115,52 @@ async def stats(websocket: WebSocket, app_name: str):
except Exception as e:
return e
else:
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)

@router.websocket("/stats")
async def dashboard(websocket: WebSocket):
auth_success = await websocket_auth(websocket=websocket)
if auth_success:
await websocket.accept()
tasks = []
async with aiodocker.Docker() as docker:
containers = []
_containers = await docker.containers.list()
for _app in _containers:
if _app._container['State'] == 'running':
containers.append(_app)
for app in containers:
_name = app._container['Names'][0][1:]
container: DockerContainer = await docker.containers.get(_name)
stats = container.stats(stream=True)
tasks.append(process_container(_name, stats, websocket))
await asyncio.gather(*tasks)
else:
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)

async def process_container(name, stats, websocket):
cpu_total = 0.0
cpu_system = 0.0
cpu_percent = 0.0
async for line in stats:
mem_current = line["memory_stats"]["usage"]
mem_total = line["memory_stats"]["limit"]

try:
cpu_percent, cpu_system, cpu_total = await calculate_cpu_percent2(line, cpu_total, cpu_system)
except KeyError as e:
print("error while getting new CPU stats: %r, falling back")
cpu_percent = await calculate_cpu_percent(line)

full_stats = {
"name": name,
"time": line['read'],
"cpu_percent": cpu_percent,
"mem_current": mem_current,
"mem_total": line["memory_stats"]["limit"],
"mem_percent": (mem_current / mem_total) * 100.0,
}
try:
await websocket.send_text(json.dumps(full_stats))
except Exception as e:
pass
8 changes: 5 additions & 3 deletions backend/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
from typing import Dict, List, Optional

from jose import jwt
from fastapi import Cookie, Depends, WebSocket, status
from fastapi import Cookie, Depends, WebSocket, status, HTTPException
from fastapi.security import APIKeyCookie
from .auth import cookie_authentication
from .auth import user_db
from .settings import Settings
import aiodocker
import json
settings = Settings()


Expand Down Expand Up @@ -192,7 +194,6 @@ async def websocket_auth(
except:
return None


async def calculate_cpu_percent(d):
cpu_count = len(d["cpu_stats"]["cpu_usage"]["percpu_usage"])
cpu_percent = 0.0
Expand Down Expand Up @@ -275,10 +276,11 @@ async def get_app_stats(app_name):
cpu_percent = await calculate_cpu_percent(line)

full_stats = {
"name": line['name'],
"time": line['read'],
"cpu_percent": cpu_percent,
"mem_current": mem_current,
"mem_total": line["memory_stats"]["limit"],
"mem_percent": (mem_current / mem_total) * 100.0,
}
return json.dumps(full_stats)
yield json.dumps(full_stats)
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ export default {
this.readApp(appName);
this.readAppProcesses(appName);
this.closeLogs();
this.closeStats();
this.readAppLogs(appName);
this.readAppStats(appName);
this.closeStats();
},
readAppLogs(appName) {
console.log("Starting connection to Websocket");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ export default {
backgroundColor: "#41b883",
lineTension: 0,
pointRadius: 0,
data: this.transformStat(stat, time),
data: time.map((t,i) => {
return { x: t,y: stat[i] };
}),
},
],
};
Expand All @@ -82,21 +84,14 @@ export default {
backgroundColor: "#41b883",
lineTension: 0,
pointRadius: 0,
data: this.transformStat(stat, time),
data: time.map((t,i) => {
return { x: t,y: stat[i] };
}),
},
],
};
return datacollection;
},
transformStat(stat, time) {
let dataArray = [];
time.forEach((timeEntry, index) => {
let entry = stat[index];
let dataObject = { x: timeEntry, y: entry };
dataArray.push(dataObject);
});
return dataArray;
},
},
};
</script>
Expand Down
74 changes: 5 additions & 69 deletions frontend/src/components/charts/PercentBarChart.vue
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
<script>
import "chartjs-plugin-crosshair";
import { Line, mixins } from "vue-chartjs"; // We specify what type of chart we want from vue-chartjs and the mixins module
import { mixins, Bar } from "vue-chartjs"; // We specify what type of chart we want from vue-chartjs and the mixins module
const { reactiveProp } = mixins;
export default {
extends: Line, //We are extending the base chart class as mentioned above
extends: Bar, //We are extending the base chart class as mentioned above
mixins: [reactiveProp],
props: {
chartdata: {
Expand All @@ -14,41 +13,10 @@ export default {
data() {
return {
options: {
//Chart.js options
responsive: true,
animation: {
duration: 0,
},
responsiveAnimationDuration: 0,
plugins: {
crosshair: {
line: {
color: "#454D55",
width: 1,
},
sync: {
enabled: false,
group: 1,
suppressTooltips: false,
},
zoom: {
enabled: false,
},
},
},
tooltips: {
mode: "index",
intersect: false,
callbacks: {
label: function(tooltipItems) {
return tooltipItems.yLabel + "%";
},
},
},
hover: {
mode: "index",
intersect: true,
animationDuration: 0,
},
scales: {
yAxes: [
{
Expand All @@ -57,47 +25,15 @@ export default {
stepSize: 1,
min: 0,
max: 100,
maxTicksLimit: 10
},
gridLines: {
display: true,
maxTicksLimit: 5
},
},
],
xAxes: [
{
ticks: {
min: 1,
sampleSize: 5,
autoSkip: true,
autoSkipPadding: 15,
maxRotation: 0,
padding: 10,
},
type: "time",
time: {
unit: 'second'
},
displayFormats: {
second: 'h:mm:ss a'
},
gridLines: {
display: false,
},
distribution: 'series'
},
],
},
legend: {
display: true,
},
responsive: true,
maintainAspectRatio: false,
},
};
},
mounted() {
// this.chartData is created in the mixin
mounted() {
this.renderChart(this.chartData, this.options);
},
};
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/charts/PercentLineChart.vue
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export default {
autoSkip: true,
autoSkipPadding: 15,
maxRotation: 0,
maxTicksLimit: 8,
maxTicksLimit: 2,
padding: 10,
},
type: "time",
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ require("animate.css/animate.compat.css");

Vue.config.productionTip = false;

// Handle Token Refresh on 401
// Handle Token Refresh on 401 or 403
function createAxiosResponseInterceptor() {
const interceptor = axios.interceptors.response.use(
(response) => response,
(error) => {
if (error.response.status !== 401) {
if (error.response.status !== 401 || error.response.status !== 403) {
return Promise.reject(error);
}

Expand Down
Loading