']
26 |
27 | };
--------------------------------------------------------------------------------
/src/client/electron/index.cts:
--------------------------------------------------------------------------------
1 | import { app, BrowserWindow } from 'electron';
2 |
3 |
4 | let mainWindow: BrowserWindow;
5 |
6 | function createMainWindow() {
7 | mainWindow = new BrowserWindow({
8 | width: 1300,
9 | height: 800,
10 | webPreferences: {
11 | webSecurity: false,
12 | sandbox: false,
13 | },
14 | show: false,
15 | });
16 |
17 |
18 | mainWindow.loadURL('http://localhost:8080'); //change to localhost:8080
19 | mainWindow.on('ready-to-show', () => mainWindow.show());
20 |
21 | }
22 |
23 |
24 | app.on('ready', createMainWindow);
25 |
26 | module.exports = {};
--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------
1 | import { Request, Response, NextFunction } from 'express';
2 | export type Job = {
3 | job: string
4 | role: Role
5 | };
6 |
7 | export type Role = 'Manager' | 'Daemon' | 'Worker' | 'Overall' | ''
8 |
9 | export type Target = {
10 | targets: string[],
11 | labels: Job
12 | };
13 |
14 | export type TargetsArray = Target[];
15 |
16 | export type JobArray = Job[];
17 |
18 | export type TargetIpArray = string[];
19 |
20 | export type ResponseObject = (req: Request, res: Response, next: NextFunction) => void;
21 |
22 | export type PanelObject = {
23 | title: string;
24 | expression: string;
25 | graphType: 'gauge' | 'line';
26 | role: Role;
27 | }
--------------------------------------------------------------------------------
/webpack.electron.config.cjs:
--------------------------------------------------------------------------------
1 | /* eslint-disable @typescript-eslint/no-var-requires */
2 | const path = require('path');
3 |
4 | module.exports = {
5 | resolve: {
6 | extensions: ['.tsx', '.ts', '.js', 'cjs']
7 | },
8 | devtool: 'inline-source-map',
9 | entry: './dist/client/electron/index.cjs',
10 | target: 'electron-main',
11 | module: {
12 | rules: [
13 | {
14 | test: /\.(js|ts|tsx|cjs)$/,
15 | exclude: /node_modules/,
16 | use: {
17 | loader: 'babel-loader'
18 | }
19 | }
20 | ]
21 | },
22 | output: {
23 | path: path.join(__dirname, '/dist'),
24 | filename: 'StormElectron.js'
25 | }
26 | };
--------------------------------------------------------------------------------
/src/client/index.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { createRoot } from 'react-dom/client';
3 | import App from './App.jsx';
4 | import { CssBaseline, ThemeProvider } from '@mui/material';
5 | import theme from './theme.jsx';
6 |
7 |
8 |
9 | createRoot(document.getElementById('root') as HTMLElement).render(
10 | // we took off strict mode so our components don't run use effect twice
11 | // can easily turn it back on by re wrapping app and it won't really break too much
12 | // take off when you actually care about checking true functionality
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | );
21 |
--------------------------------------------------------------------------------
/prometheus/prometheus.yml:
--------------------------------------------------------------------------------
1 | # my global config
2 | global:
3 | scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
4 | evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
5 | # scrape_timeout is set to the global default (10s).
6 |
7 | # Attach these labels to any time series or alerts when communicating with
8 | # external systems (federation, remote storage, Alertmanager).
9 | external_labels:
10 | monitor: 'codelab-monitor'
11 |
12 | # Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
13 | rule_files:
14 | # - "first.rules"
15 | # - "second.rules"
16 |
17 | # A scrape configuration containing exactly one endpoint to scrape:
18 | # Here it's Prometheus itself.
19 | scrape_configs:
20 | - job_name: 'file_sd_targets'
21 | file_sd_configs:
22 | - files:
23 | - 'targets.json'
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "parser": "@typescript-eslint/parser",
3 | "root": true,
4 | "ignorePatterns": ["**/test", "**/__tests__"],
5 | "env": {
6 | "node": true,
7 | "browser": true,
8 | "es2021": true
9 | },
10 | "plugins": ["react", "@typescript-eslint"],
11 | "extends": ["eslint:recommended", "plugin:react/recommended", "eslint:recommended", "plugin:@typescript-eslint/recommended"],
12 | "parserOptions": {
13 | "sourceType": "module",
14 | "ecmaFeatures": {
15 | "jsx": true
16 | }
17 | },
18 | "rules": {
19 | "indent": ["warn", 2],
20 | "no-unused-vars": ["off", { "vars": "local" }],
21 | "no-case-declarations": "off",
22 | "prefer-const": "warn",
23 | "quotes": ["warn", "single"],
24 | "react/prop-types": "off",
25 | "semi": ["warn", "always"],
26 | "space-infix-ops": "warn"
27 | },
28 | "settings": {
29 | "react": { "version": "detect"}
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/server/routes/metricApi.ts:
--------------------------------------------------------------------------------
1 | import express from 'express';
2 | import metricsController from '../controllers/metricsController.js';
3 |
4 | const router = express.Router();
5 |
6 | // Get request which gets the entire list of avaliable targets and return it
7 | router.get('/', metricsController.getListOfTargets, (req, res) => {
8 | return res.status(200).json({targets: res.locals.targets, jobs: res.locals.jobs});
9 | });
10 |
11 | // Post request which generate panel bodies based off of the info provided to it (to be used by the grafana controller)
12 | router.post('/genPanel', metricsController.generatePanelBody, (req, res) => {
13 | return res.status(200).json(res.locals.panels);
14 | });
15 |
16 | // Get request which grabs all the static panel body values from a file and returns it
17 | router.get('/genStaticPanels', metricsController.generateStaticPanels, (req, res) => {
18 | return res.status(200).json(res.locals.staticPanels);
19 | });
20 |
21 | export default router;
22 |
--------------------------------------------------------------------------------
/src/server/helperFunctions/manageFiles.ts:
--------------------------------------------------------------------------------
1 | import fs from 'fs';
2 |
3 | /**
4 | * Gets the grafana panel ID from a file and returns that object
5 | *
6 | * @return { {'panelId': number} } The panelId Object read from the file
7 | */
8 | export function getGrafID(){
9 | return JSON.parse(fs.readFileSync('./grafana/grafId.json', 'utf-8'));
10 | }
11 |
12 | /**
13 | * Increment the panelId value by 1 and write that back to the file returning the incremented object
14 | * @param { {'panelId': number} } id Optional parameter that represents an object with the current panelID
15 | *
16 | * @return { {'panelId': number} } The result of incrementing panelId by 1
17 | */
18 | export function incrementGrafID(id?: {'panelId' : number}): void {
19 | //Since the id parameter is optional if not provided method will automatically grab it
20 | const grafId = id || getGrafID();
21 |
22 | grafId.panelId += 1;
23 | fs.writeFileSync('./grafana/grafId.json', JSON.stringify(grafId));
24 |
25 | return grafId;
26 | }
--------------------------------------------------------------------------------
/src/client/theme.tsx:
--------------------------------------------------------------------------------
1 | import { createTheme } from '@mui/material/styles';
2 |
3 | declare module '@mui/material/styles' {
4 | interface BreakpointOverrides {
5 | xs: true; // removes the `xs` breakpoint
6 | sm: true;
7 | md: true;
8 | lg: true;
9 | xl: true;
10 | desktopfullhd: true;
11 | desktop2k: true;
12 | desktop4k: true;
13 | }
14 | }
15 |
16 | // A custom theme for this app
17 | const theme = createTheme({
18 | palette: {
19 | primary: {
20 | main: '#4C82FE',
21 | dark: '#121212',
22 | contrastText: '#959595',
23 | },
24 | secondary: {
25 | main: '#EF8354',
26 | light: '#f29b76',
27 | dark: '#e95818',
28 | contrastText: '#2D3142',
29 | },
30 | },
31 | spacing: 4,
32 | breakpoints: {
33 | values: {
34 | xs: 0,
35 | sm: 600,
36 | md: 900,
37 | lg: 1200,
38 | xl: 1536,
39 | desktopfullhd: 1920,
40 | desktop2k: 2560,
41 | desktop4k: 3840,
42 | },
43 | },
44 | typography: {
45 | // fontFamily: RobotoBold,
46 | },
47 |
48 |
49 |
50 |
51 | });
52 |
53 | export default theme;
54 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Docker Storm Team
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/client/pages/metrics.tsx:
--------------------------------------------------------------------------------
1 | import React, {useState, useEffect} from 'react';
2 | import {TextField, Container, Typography, Box, createStyles, Grid, Button } from '@mui/material';
3 |
4 |
5 | interface Props {
6 | dashId: string;
7 | grafUrl: string;
8 | }
9 | const Metrics = (props: Props) => {
10 | const [dash, setDash] = useState(props.dashId);
11 | const [grafUrl, setGrafUrl] = useState(props.grafUrl);
12 |
13 | useEffect(() => {
14 | setDash(props.dashId);
15 | setGrafUrl(props.grafUrl);
16 | },[dash, grafUrl]);
17 |
18 | return (
19 |
20 | Metrics
21 |
22 |
23 | {props.dashId && }
24 |
25 |
26 |
27 | );
28 | };
29 | export default Metrics;
--------------------------------------------------------------------------------
/src/server/routes/grafApi.ts:
--------------------------------------------------------------------------------
1 | import express from 'express';
2 | import grafanaController from '../controllers/grafanaController.js';
3 |
4 | const router = express.Router();
5 |
6 | // Get request that creates an EmptyDB (not used but left incase future iterations need this path)
7 | router.get('/', grafanaController.createDB, (req, res) => {
8 | return res.status(200).json('successful');
9 | });
10 |
11 | // Post request that will work on initalizing the dashboard if it does not already exist based off of the panels already in targets
12 | router.post('/init', grafanaController.createDB, grafanaController.getDashByUid, grafanaController.createPanel, grafanaController.updateDB, (req, res) => {
13 | return res.status(200).json({ApiKey: process.env.GRAFANA_DASHBOARD_ID});
14 | });
15 |
16 | // Patch request to update the dashboard with the provided panels
17 | router.patch('/', grafanaController.getDashByUid, grafanaController.createPanel, grafanaController.updateDB, (req, res) => {
18 | return res.status(200).json('successful');
19 | });
20 |
21 | // Post request which adds new targets to our targets file for prometheus to track
22 | router.post('/targetsAdd', grafanaController.addTarget, (req, res) => {
23 | return res.sendStatus(200);
24 | });
25 |
26 |
27 | export default router;
28 |
--------------------------------------------------------------------------------
/grafana/jsonTemplates/stateTemplate.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": 2,
3 | "type": "stat",
4 | "title": "Placeholder",
5 | "transformations": [
6 | {
7 | "id": "labelsToFields",
8 | "options": {
9 | "valueLabel": "state"
10 | }
11 | }
12 | ],
13 | "pluginVersion": "9.2.6",
14 | "fieldConfig": {
15 | "defaults": {
16 | "mappings": [],
17 | "thresholds": {
18 | "mode": "absolute",
19 | "steps": [
20 | {
21 | "color": "green",
22 | "value": null
23 | }
24 | ]
25 | },
26 | "color": {
27 | "mode": "thresholds"
28 | }
29 | },
30 | "overrides": []
31 | },
32 | "options": {
33 | "reduceOptions": {
34 | "values": false,
35 | "calcs": [
36 | "lastNotNull"
37 | ],
38 | "fields": ""
39 | },
40 | "orientation": "auto",
41 | "textMode": "auto",
42 | "colorMode": "value",
43 | "graphMode": "area",
44 | "justifyMode": "center"
45 | },
46 | "targets": [
47 | {
48 | "editorMode": "code",
49 | "expr": "expr",
50 | "hide": false,
51 | "legendFormat": "__auto",
52 | "range": true,
53 | "refId": "A"
54 | }
55 | ],
56 | "gridPos": {
57 | "h": 8,
58 | "w": 12,
59 | "x": 0,
60 | "y": 0
61 | }
62 | }
--------------------------------------------------------------------------------
/grafana/jsonTemplates/diskTemplate.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": 2,
3 | "gridPos": {
4 | "h": 8,
5 | "w": 12,
6 | "x": 0,
7 | "y": 0
8 | },
9 | "type": "stat",
10 | "title": "Placeholder",
11 | "transformations": [
12 | {
13 | "id": "labelsToFields",
14 | "options": {
15 | "valueLabel": "job"
16 | }
17 | }
18 | ],
19 | "pluginVersion": "9.2.6",
20 | "fieldConfig": {
21 | "defaults": {
22 | "mappings": [],
23 | "thresholds": {
24 | "mode": "absolute",
25 | "steps": [
26 | {
27 | "color": "green",
28 | "value": null
29 | }
30 | ]
31 | },
32 | "color": {
33 | "mode": "thresholds"
34 | },
35 | "unit": "decbytes"
36 | },
37 | "overrides": []
38 | },
39 | "options": {
40 | "reduceOptions": {
41 | "values": false,
42 | "calcs": [
43 | "lastNotNull"
44 | ],
45 | "fields": ""
46 | },
47 | "orientation": "auto",
48 | "textMode": "auto",
49 | "colorMode": "value",
50 | "graphMode": "area",
51 | "justifyMode": "auto"
52 | },
53 | "targets": [
54 | {
55 | "editorMode": "code",
56 | "expr": "placeholder",
57 | "hide": false,
58 | "legendFormat": "__auto",
59 | "range": true,
60 | "refId": "A"
61 | }
62 | ]
63 | }
--------------------------------------------------------------------------------
/grafana/jsonTemplates/statTemplate.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": 2,
3 | "gridPos": {
4 | "h": 8,
5 | "w": 12,
6 | "x": 0,
7 | "y": 0
8 | },
9 | "type": "stat",
10 | "title": "Placeholder",
11 | "transformations": [
12 | {
13 | "id": "labelsToFields",
14 | "options": {
15 | "valueLabel": "role"
16 | }
17 | }
18 | ],
19 | "pluginVersion": "9.2.6",
20 | "fieldConfig": {
21 | "defaults": {
22 | "mappings": [],
23 | "thresholds": {
24 | "mode": "absolute",
25 | "steps": [
26 | {
27 | "color": "green",
28 | "value": null
29 | }
30 | ]
31 | },
32 | "color": {
33 | "mode": "thresholds"
34 | }
35 | },
36 | "overrides": []
37 | },
38 | "options": {
39 | "reduceOptions": {
40 | "values": false,
41 | "calcs": [
42 | "lastNotNull"
43 | ],
44 | "fields": ""
45 | },
46 | "orientation": "auto",
47 | "textMode": "auto",
48 | "colorMode": "value",
49 | "graphMode": "area",
50 | "justifyMode": "center"
51 | },
52 | "targets": [
53 | {
54 | "editorMode": "code",
55 | "expr": "placeholder",
56 | "hide": false,
57 | "legendFormat": "__auto",
58 | "range": true,
59 | "refId": "A"
60 | }
61 | ]
62 | }
--------------------------------------------------------------------------------
/__test/client_test/Users.test.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import '@testing-library/jest-dom';
3 | import { render, screen, fireEvent } from '@testing-library/react';
4 | import Users from '../../dist/client/pages/users.jsx';
5 |
6 |
7 | describe('Users Page', () => {
8 |
9 | beforeEach(() => {
10 | render( );
11 | });
12 |
13 | it('should render an Add New User button', () => {
14 | const buttons = screen.getByRole('button');
15 | expect(buttons).toHaveTextContent('Add New User');
16 | });
17 |
18 | it('should handle a click when clicking Add New User', () => {
19 | const mockClick = jest.fn();
20 | const button = screen.getByText('Add New User');
21 | console.log(button);
22 | button.onclick = mockClick;
23 | fireEvent.click(button);
24 | expect(mockClick).toHaveBeenCalledTimes(1);
25 | });
26 |
27 | it('should have four input fields to add new user' , () => {
28 | const username = screen.getByPlaceholderText('Username');
29 | const role = screen.getByPlaceholderText('Role');
30 | const password = screen.getByPlaceholderText('Password');
31 | const confirm = screen.getByPlaceholderText('Confirm Password');
32 | expect(username);
33 | expect(role);
34 | expect(password);
35 | expect(confirm);
36 | });
37 |
38 | it('should render a list of all the users', () => {
39 | const list = screen.getByText('List of all users');
40 | expect(list).toBeInTheDocument();
41 | });
42 | });
43 |
44 |
45 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Docker Storm
2 |
3 | First of all, thank you for your time and for considering on contributing to make Docker Storm better.
4 |
5 | ## Reporting Bugs
6 |
7 | All code changes happen through Github Pull Requests and we actively welcome them. To submit your pull request, follow the steps below:
8 |
9 | ## Pull Requests
10 |
11 | 1. Fork and clone the repository.
12 | 2. Create your feature branch. (git checkout -b [my-new-feature])
13 | 3. Make sure to cover your code with tests and that your code is linted in accordance with our linting specifications (see coding style below).
14 | 4. Commit your changes locally (git commit -m 'Added some feature') and then push to your remote repository.
15 | 5. Submit a pull request to the _dev_ branch, including a description of the work done in your pull request.
16 |
17 | Note: Any contributions you make will be under the MIT Software License and your submissions are understood to be under the same that covers the project. Please reach out to the team if you have any questions.
18 |
19 | ## Issues
20 |
21 | We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue.
22 |
23 | ## Coding Style
24 |
25 | 2 spaces for indentation rather than tabs
26 | Please install eslint in order to use our premade .eslintrc.json file in order to ensure consistant linting
27 |
28 | ## License
29 |
30 | By contributing, you agree that your contributions will be licensed under Docker Storm's MIT License.
--------------------------------------------------------------------------------
/grafana/jsonTemplates/gaugeTemplate.json:
--------------------------------------------------------------------------------
1 | {
2 | "fieldConfig": {
3 | "defaults": {
4 | "color": {
5 | "mode": "thresholds"
6 | },
7 | "mappings": [],
8 | "max": 100,
9 | "min": 0,
10 | "thresholds": {
11 | "mode": "percentage",
12 | "steps": [
13 | {
14 | "color": "green",
15 | "value": null
16 | },
17 | {
18 | "color": "#EAB839",
19 | "value": 50
20 | },
21 | {
22 | "color": "red",
23 | "value": 80
24 | }
25 | ]
26 | },
27 | "unit": "percent"
28 | },
29 | "overrides": []
30 | },
31 | "gridPos": {
32 | "h": 9,
33 | "w": 12,
34 | "x": 0,
35 | "y": 0
36 | },
37 | "id": 2,
38 | "options": {
39 | "orientation": "auto",
40 | "reduceOptions": {
41 | "calcs": [
42 | "lastNotNull"
43 | ],
44 | "fields": "",
45 | "values": false
46 | },
47 | "showThresholdLabels": false,
48 | "showThresholdMarkers": true
49 | },
50 | "pluginVersion": "9.2.6",
51 | "targets": [
52 | {
53 | "editorMode": "code",
54 | "expr": "Placeholder",
55 | "legendFormat": "__auto",
56 | "range": true,
57 | "refId": "A"
58 | }
59 | ],
60 | "title": "Panel Title",
61 | "type": "gauge",
62 |
63 | "transformations": [
64 | {
65 | "id": "labelsToFields",
66 | "options": {
67 | "valueLabel": "job"
68 | }
69 | }
70 | ]
71 | }
--------------------------------------------------------------------------------
/src/server/server.ts:
--------------------------------------------------------------------------------
1 | import express, { NextFunction, Request, Response } from 'express';
2 | import cors from 'cors';
3 | import initRouter from './routes/initApi.js';
4 | import userRouter from './routes/userApi.js';
5 | import grafanaRouter from './routes/grafApi.js';
6 | import metricRouter from './routes/metricApi.js';
7 | import cookieParser from 'cookie-parser';
8 |
9 | const app = express();
10 |
11 | //Port constant
12 | const PORT = 3001;
13 |
14 | //Adding necessary parsing functions
15 | app.use(cors({ origin: true }));
16 | app.use(express.json());
17 | app.use(express.urlencoded({ extended: true }));
18 | app.use(cookieParser());
19 |
20 | //Having all routes be checked
21 | app.use('/user', userRouter);
22 | app.use('/init', initRouter);
23 | app.use('/graf', grafanaRouter);
24 | app.use('/metric', metricRouter);
25 |
26 | // Catch for invalid request
27 | app.use('/*', (req: Request, res: Response) => {
28 | return res.sendStatus(404);
29 | });
30 |
31 | // Global error catching
32 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
33 | app.use((err: Error, req: Request, res: Response, _next: NextFunction) => {
34 | const defaultErr = {
35 | log: `GLOBAL ERROR HANDLER: caught unknown middleware error${err.toString()}`,
36 | status: 500,
37 | message: { err: 'An error occurred' },
38 | };
39 | const errorObj = Object.assign({}, defaultErr, err);
40 | if (errorObj.log) console.log(errorObj);
41 | return res.status(errorObj.status).json(errorObj.message);
42 | });
43 |
44 | //Spin up backend on port
45 | app.listen(PORT, () => {
46 | console.log(`Listening on port: ${PORT}`);
47 | });
48 |
49 | export default app;
50 |
--------------------------------------------------------------------------------
/webpack.config.cjs:
--------------------------------------------------------------------------------
1 | /* eslint-disable @typescript-eslint/no-var-requires */
2 | const path = require('path');
3 | const HTMLWebpackPlugin = require('html-webpack-plugin');
4 |
5 | module.exports = {
6 | entry: './dist/client/index.jsx',
7 | //entry: './src/client/index.tsx',
8 |
9 | output: {
10 | path: path.join(__dirname, '/dist'),
11 | filename: 'bundle.js',
12 | publicPath: '/',
13 | },
14 |
15 | plugins: [
16 | new HTMLWebpackPlugin ({
17 | template: './src/client/index.html'
18 | })
19 | ],
20 |
21 | resolve: {
22 | extensions: ['.js', '.jsx'],
23 | },
24 |
25 | mode: process.env.NODE_ENV,
26 |
27 | module: {
28 | rules: [
29 | {
30 | test: /\.(js|jsx|cjs)$/,
31 | exclude: /node_modules/,
32 | use: {
33 | loader: 'babel-loader',
34 | options: {
35 | presets: ['@babel/preset-env', ['@babel/preset-react', {'runtime': 'automatic'}]]
36 | }
37 | }
38 | },
39 |
40 | {
41 | test: /\.s?css/,
42 | exclude: /node_modules/,
43 | use: ['style-loader', 'css-loader']
44 | },
45 | {
46 | test: /\.(jpe?g|png|gif|svg)$/i,
47 | use: [
48 | {
49 | loader: 'file-loader',
50 | options: {
51 | name: 'images/[name].[ext]'
52 | }
53 | },
54 |
55 | ],
56 | },
57 | ]
58 | },
59 |
60 | devServer: {
61 | static: {
62 | directory: path.join(__dirname, './dist'),
63 | publicPath: '/',
64 | },
65 | historyApiFallback: true,
66 | proxy: {
67 | '/': 'http://localhost:3001',
68 | }
69 | }
70 |
71 | };
72 |
--------------------------------------------------------------------------------
/__test/server_test/user.test.ts:
--------------------------------------------------------------------------------
1 | import { beforeAll } from '@jest/globals';
2 | import db from '../../src/server/models/dockerStormModel';
3 | import { describe, it } from '@jest/globals';
4 | import 'whatwg-fetch';
5 |
6 |
7 | const userOne = {
8 | username: 'TestUser',
9 | password: 'TestPassword',
10 | role: 'TestRole'
11 | };
12 |
13 | beforeAll( () => {
14 |
15 | const createTest = `CREATE TABLE IF NOT EXISTS users(
16 | "id" SERIAL NOT NULL,
17 | "username" text NOT NULL,
18 | "password" text NOT NULL,
19 | "role" text NOT NULL,
20 | PRIMARY KEY("id"),
21 | UNIQUE("username"))`;
22 |
23 | db.query(createTest, []);
24 |
25 | });
26 |
27 | describe('User Creation, Updating, and Deletion', () => {
28 |
29 | beforeEach( async() => {
30 | await fetch('http://localhost:8080/user/signup', {
31 | method: 'POST',
32 | headers: {
33 | 'content-type' : 'application/json'
34 | },
35 | body: JSON.stringify(userOne)
36 | })
37 | .then((data) => data.json())
38 | .then((result) => console.log(result));
39 | });
40 |
41 | afterEach(() => {
42 | fetch('http://localhost:8080/user/', {
43 | method: 'DELETE',
44 | headers: {'Content-type': 'application/json'},
45 | body: JSON.stringify({ username: 'TestUser'})
46 | })
47 | .then((data) => data.json())
48 | .then((result => console.log(result)));
49 | });
50 |
51 | it('should confirm the user was added to the database', () => {
52 | fetch('http://localhost:8080/user/all')
53 | .then((data) => data.json())
54 | .then((result) => {
55 | console.log(result);
56 | const arrayOfUsers : string[] = [];
57 | result.forEach((element: { username: string; }) => {
58 | arrayOfUsers.push(element.username);
59 | });
60 | expect(arrayOfUsers).toContain(userOne.username);
61 | });
62 | });
63 | });
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/grafana/staticPanels.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "title": "CPU Usage per Container",
4 | "expression": "sum(rate(container_cpu_usage_seconds_total{name=~'.+'}[1m])) by (name) * 100",
5 | "graphType": "containerPercent",
6 | "role" : "overall"
7 | },
8 |
9 | {
10 | "title": "Memory Usage Per Container",
11 | "expression": "sum(container_memory_rss{name=~'.+'}) by (name)",
12 | "graphType": "containerByte",
13 | "role" : "overall"
14 | },
15 |
16 | {
17 | "title": "Incoming Network Traffic per Container",
18 | "expression": "sum(rate(container_network_receive_bytes_total{name=~'.+'}[1m])) by (name)",
19 | "graphType": "containerByte",
20 | "role" : "overall"
21 | },
22 |
23 | {
24 | "title": "Outgoing Network Traffic per Container",
25 | "expression": "sum(rate(container_network_transmit_bytes_total{name=~'.+'}[1m])) by (name)",
26 | "graphType": "containerByte",
27 | "role" : "overall"
28 | },
29 |
30 | {
31 | "title": "Machine Ram Usage",
32 | "expression": "100 * (1 - ((avg_over_time(node_memory_MemFree_bytes[1m]) + avg_over_time(node_memory_Cached_bytes[1m]) + avg_over_time(node_memory_Buffers_bytes[1m])) / avg_over_time(node_memory_MemTotal_bytes[1m])))",
33 | "graphType": "line",
34 | "role" : "overall"
35 | },
36 |
37 | {
38 | "title": "Running Containers",
39 | "expression": "swarm_manager_tasks_total{state='running'}",
40 | "graphType": "stat",
41 | "role" : "overall"
42 | },
43 |
44 | {
45 | "title": "Node Status",
46 | "expression": "swarm_manager_nodes",
47 | "graphType": "state",
48 | "role" : "overall"
49 | },
50 |
51 | {
52 | "title": "Remaining Disk Space",
53 | "expression": "(node_filesystem_avail_bytes{mountpoint='/',fstype!='rootfs'})",
54 | "graphType": "disk",
55 | "role" : "overall"
56 | }
57 | ]
--------------------------------------------------------------------------------
/src/server/routes/userApi.ts:
--------------------------------------------------------------------------------
1 | import express from 'express';
2 |
3 | import userController from '../controllers/userController.js';
4 | import cookieController from '../controllers/cookieController.js';
5 | import initController from '../controllers/initController.js';
6 |
7 | const router = express.Router();
8 |
9 | // Get request to grab all users and return it
10 | router.get('/all', userController.getAllUsers, (req,res) => {
11 | return res.status(200).json(res.locals.allUsers);
12 | });
13 |
14 | // Post request to handle user verification setting cookie and logging the user in
15 | router.post('/login', userController.verifyUser, cookieController.setCookie, userController.checkEnv, (req, res) => {
16 | const obj = {
17 | grafUrl: res.locals.grafUrl,
18 | key: res.locals.apiKey
19 | };
20 |
21 | return res.status(200).json(obj);
22 | });
23 |
24 | // Post request which allows us to update our env file
25 | router.post('/env', initController.updateEnv, (req, res) => {
26 | return res.sendStatus(200);
27 | });
28 |
29 | // Post request which manages signing up specifically the admin user
30 | router.post('/signupAdmin', userController.encrypt, userController.createAdminUser, userController.createAdminUserInfo, (req, res) => {
31 | return res.status(200).json('successful');
32 | });
33 |
34 | // Post request which manages signing up a new user account and encrypting their password
35 | router.post('/signup', userController.encrypt, userController.createUser, (req, res) => {
36 | return res.status(200).json('successful');
37 | });
38 |
39 | // Patch request which will allow the user to change their password (old password must be verified first)
40 | router.patch('/', userController.verifyUser, userController.encrypt, userController.updateUser, (req, res) => {
41 | return res.status(200).json('successful');
42 | });
43 |
44 | // Delete request which manages deleting a user
45 | router.delete('/', userController.deleteUser, (req, res) => {
46 | return res.status(200).json('successful');
47 | });
48 |
49 | export default router;
50 |
--------------------------------------------------------------------------------
/grafana/jsonTemplates/lineTemplate.json:
--------------------------------------------------------------------------------
1 | {
2 | "fieldConfig": {
3 | "defaults": {
4 | "color": {
5 | "mode": "palette-classic"
6 | },
7 | "custom": {
8 | "axisCenteredZero": false,
9 | "axisColorMode": "series",
10 | "axisGridShow": true,
11 | "axisLabel": "Placeholder",
12 | "axisPlacement": "left",
13 | "barAlignment": 0,
14 | "drawStyle": "line",
15 | "fillOpacity": 0,
16 | "gradientMode": "none",
17 | "hideFrom": {
18 | "legend": false,
19 | "tooltip": false,
20 | "viz": false
21 | },
22 | "lineInterpolation": "linear",
23 | "lineWidth": 1,
24 | "pointSize": 5,
25 | "scaleDistribution": {
26 | "type": "linear"
27 | },
28 | "showPoints": "auto",
29 | "spanNulls": false,
30 | "stacking": {
31 | "group": "A",
32 | "mode": "none"
33 | },
34 | "thresholdsStyle": {
35 | "mode": "off"
36 | }
37 | },
38 | "mappings": [],
39 | "thresholds": {
40 | "mode": "absolute",
41 | "steps": [
42 | {
43 | "color": "green",
44 | "value": null
45 | }
46 | ]
47 | },
48 | "unit": "percent"
49 | },
50 | "overrides": []
51 | },
52 | "gridPos": {
53 | "h": 8,
54 | "w": 12,
55 | "x": 0,
56 | "y": 0
57 | },
58 | "id": 2,
59 | "interval": "5",
60 | "maxDataPoints": 900,
61 | "options": {
62 | "legend": {
63 | "calcs": [],
64 | "displayMode": "list",
65 | "placement": "bottom",
66 | "showLegend": true
67 | },
68 | "timezone": [
69 | "browser"
70 | ],
71 | "tooltip": {
72 | "mode": "single",
73 | "sort": "none"
74 | }
75 | },
76 | "targets": [
77 | {
78 | "editorMode": "code",
79 | "expr": "placeholder",
80 | "legendFormat": "__auto",
81 | "range": true,
82 | "refId": "A"
83 | }
84 | ],
85 | "title": "Placeholder",
86 | "transformations": [
87 | {
88 | "id": "labelsToFields",
89 | "options": {
90 | "valueLabel": "job"
91 | }
92 | }
93 | ],
94 | "type": "timeseries"
95 | }
--------------------------------------------------------------------------------
/grafana/jsonTemplates/containerPercentTemplate.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": 1,
3 | "gridPos": {
4 | "x": 0,
5 | "y": 0,
6 | "w": 24,
7 | "h": 8
8 | },
9 | "type": "graph",
10 | "title": "Placeholder",
11 | "thresholds": [],
12 | "links": [],
13 | "legend": {
14 | "alignAsTable": true,
15 | "avg": false,
16 | "current": true,
17 | "hideEmpty": false,
18 | "hideZero": true,
19 | "max": true,
20 | "min": true,
21 | "rightSide": true,
22 | "show": true,
23 | "total": false,
24 | "values": true
25 | },
26 | "aliasColors": {},
27 | "bars": false,
28 | "decimals": null,
29 | "fill": 5,
30 | "height": "270px",
31 | "lines": true,
32 | "linewidth": 1,
33 | "nullPointMode": "null as zero",
34 | "percentage": false,
35 | "pointradius": 5,
36 | "points": false,
37 | "renderer": "flot",
38 | "seriesOverrides": [],
39 | "stack": true,
40 | "steppedLine": false,
41 | "targets": [
42 | {
43 | "expr": "placeholder",
44 | "intervalFactor": 2,
45 | "legendFormat": "{{name}}",
46 | "refId": "A",
47 | "step": 2
48 | }
49 | ],
50 | "timeFrom": null,
51 | "timeShift": null,
52 | "tooltip": {
53 | "shared": true,
54 | "sort": 0,
55 | "value_type": "individual"
56 | },
57 | "xaxis": {
58 | "mode": "time",
59 | "name": null,
60 | "show": true,
61 | "values": [],
62 | "buckets": null
63 | },
64 | "yaxes": [
65 | {
66 | "format": "percent",
67 | "label": null,
68 | "logBase": 1,
69 | "max": null,
70 | "min": null,
71 | "show": true
72 | },
73 | {
74 | "format": "short",
75 | "label": null,
76 | "logBase": 1,
77 | "max": null,
78 | "min": null,
79 | "show": false
80 | }
81 | ],
82 | "options": {
83 | "alertThreshold": true
84 | },
85 | "pluginVersion": "9.2.6",
86 | "yaxis": {
87 | "align": false,
88 | "alignLevel": null
89 | },
90 | "fillGradient": 0,
91 | "dashes": false,
92 | "hiddenSeries": false,
93 | "dashLength": 10,
94 | "spaceLength": 10,
95 | "timeRegions": []
96 | }
--------------------------------------------------------------------------------
/grafana/jsonTemplates/containerByteTemplate.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": 5,
3 | "gridPos": {
4 | "x": 0,
5 | "y": 0,
6 | "w": 24,
7 | "h": 8
8 | },
9 | "type": "graph",
10 | "title": "Placeholder",
11 | "links": [],
12 | "legend": {
13 | "alignAsTable": true,
14 | "avg": false,
15 | "current": true,
16 | "hideZero": true,
17 | "max": true,
18 | "min": true,
19 | "rightSide": true,
20 | "show": true,
21 | "sort": "current",
22 | "sortDesc": true,
23 | "total": false,
24 | "values": true
25 | },
26 | "aliasColors": {},
27 | "bars": false,
28 | "fill": 3,
29 | "height": "270px",
30 | "lines": true,
31 | "linewidth": 2,
32 | "nullPointMode": "null as zero",
33 | "percentage": false,
34 | "pointradius": 5,
35 | "points": false,
36 | "renderer": "flot",
37 | "seriesOverrides": [],
38 | "stack": true,
39 | "steppedLine": false,
40 | "targets": [
41 | {
42 | "expr": "placeholder",
43 | "hide": false,
44 | "intervalFactor": 2,
45 | "legendFormat": "{{name}}",
46 | "metric": "container_memory_rss",
47 | "refId": "A",
48 | "step": 2
49 | }
50 | ],
51 | "timeFrom": null,
52 | "timeShift": null,
53 | "tooltip": {
54 | "shared": true,
55 | "sort": 0,
56 | "value_type": "individual"
57 | },
58 | "xaxis": {
59 | "mode": "time",
60 | "name": null,
61 | "show": true,
62 | "values": [],
63 | "buckets": null
64 | },
65 | "yaxes": [
66 | {
67 | "format": "bytes",
68 | "label": null,
69 | "logBase": 1,
70 | "max": null,
71 | "min": null,
72 | "show": true
73 | },
74 | {
75 | "format": "short",
76 | "label": null,
77 | "logBase": 1,
78 | "max": null,
79 | "min": null,
80 | "show": true
81 | }
82 | ],
83 | "options": {
84 | "alertThreshold": true
85 | },
86 | "pluginVersion": "9.2.6",
87 | "yaxis": {
88 | "align": false,
89 | "alignLevel": null
90 | },
91 | "fillGradient": 0,
92 | "dashes": false,
93 | "hiddenSeries": false,
94 | "dashLength": 10,
95 | "spaceLength": 10,
96 | "timeRegions": []
97 | }
--------------------------------------------------------------------------------
/dist/client/pages/initialSetup.jsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import { useNavigate } from 'react-router-dom';
3 | const InitialSetup = (props) => {
4 | const [currentApi, setCurrentApi] = useState(props.apiKey);
5 | const [currentGrafUrl, setCurrentGrafUrl] = useState(props.grafUrl);
6 | const [validInput, setValidInput] = useState(false);
7 | const navigate = useNavigate();
8 | useEffect(() => {
9 | if (props.apiKey && props.grafUrl)
10 | navigate('/app');
11 | }, []);
12 | const handleSubmit = () => {
13 | if (!currentApi || !currentGrafUrl) {
14 | setValidInput(true);
15 | return;
16 | }
17 | const body = {
18 | apiKey: currentApi,
19 | grafUrl: currentGrafUrl
20 | };
21 | props.setApiKey(currentApi);
22 | props.setGrafUrl(currentGrafUrl);
23 | fetch('/user/env', {
24 | method: 'POST',
25 | headers: {
26 | 'content-type': 'application/json'
27 | },
28 | body: JSON.stringify(body),
29 | }).then(() => {
30 | navigate('/app');
31 | });
32 | };
33 | const renderApiKey = () => {
34 | return (
35 | Please enter your Grafana Api Key
36 | setCurrentApi(input.target.value)} value={currentApi}/>
37 |
);
38 | };
39 | const renderGrafUrl = () => {
40 | return (
41 | Please enter your Grafana URL.
42 | Please enter in the form of http://localhost:XXXX/
43 | or http://[IP ADDRESS]/ or http://[URL]/ .
44 | Please do not add anything after the final / .
45 |
46 | setCurrentGrafUrl(input.target.value)} value={currentGrafUrl}/>
47 |
);
48 | };
49 | return ();
58 | };
59 | export default InitialSetup;
60 |
--------------------------------------------------------------------------------
/src/client/RenderViews.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Routes, Route, Link } from 'react-router-dom';
3 | import Settings from './pages/settings.jsx';
4 | import Metrics from './pages/metrics.jsx';
5 | import Users from './pages/users.jsx';
6 | import {Box} from '@mui/material';
7 | import logoWhite from '../../resources/media/logo-white.png';
8 | import { EqualizerOutlined, GroupOutlined, LogoutOutlined, SettingsOutlined } from '@mui/icons-material';
9 | import { Job, JobArray, Target, TargetIpArray, Role } from '../types.js';
10 |
11 |
12 | interface Props {
13 | dashId: string;
14 | targetsArr: Target[];
15 | setTargetsArr: React.Dispatch>;
16 | grafUrl: string;
17 | }
18 |
19 |
20 | const RenderViews = (props: Props) => {
21 |
22 | return (
23 | <>
24 |
25 |
26 |
27 |
28 |
29 |
30 | Metrics
31 |
32 |
33 |
34 |
36 |
37 | Settings
38 |
39 |
40 |
41 |
42 |
43 | Users
44 |
45 |
46 |
47 |
48 |
49 | Logout
50 |
51 |
52 |
53 |
54 |
55 | }/>
56 | }/>
57 | }/>
58 |
59 |
60 |
61 | >
62 | );
63 | };
64 |
65 | export default RenderViews;
--------------------------------------------------------------------------------
/src/client/pages/initialSetup.tsx:
--------------------------------------------------------------------------------
1 | import React, {useState, useEffect} from 'react';
2 | import { useNavigate } from 'react-router-dom';
3 |
4 | interface Props {
5 | setApiKey: (value: string) => void;
6 | setGrafUrl: (value: string) => void;
7 | grafUrl: string;
8 | apiKey: string;
9 |
10 | }
11 |
12 | const InitialSetup = (props: Props) => {
13 | const[currentApi, setCurrentApi] = useState(props.apiKey);
14 | const[currentGrafUrl, setCurrentGrafUrl] = useState(props.grafUrl);
15 | const[validInput, setValidInput] = useState(false);
16 | const navigate = useNavigate();
17 |
18 |
19 |
20 | useEffect(() => {
21 | if(props.apiKey && props.grafUrl) navigate('/app');
22 | }, []);
23 |
24 | const handleSubmit = () => {
25 | if(!currentApi || !currentGrafUrl) {
26 | setValidInput(true);
27 | return;
28 | }
29 |
30 | const body = {
31 | apiKey: currentApi,
32 | grafUrl: currentGrafUrl
33 | };
34 |
35 | props.setApiKey(currentApi);
36 | props.setGrafUrl(currentGrafUrl);
37 |
38 | fetch('/user/env', {
39 | method: 'POST',
40 | headers: {
41 | 'content-type': 'application/json'
42 | },
43 | body: JSON.stringify(body),
44 | }).then(() => {
45 | navigate('/app');
46 | });
47 | };
48 |
49 | const renderApiKey = () => {
50 | return (
51 |
52 | Please enter your Grafana Api Key
53 | setCurrentApi(input.target.value)}
56 | value={currentApi}/>
57 |
58 | );
59 | };
60 |
61 | const renderGrafUrl = () => {
62 | return (
63 |
64 | Please enter your Grafana URL.
65 | Please enter in the form of http://localhost:XXXX/
66 | or http://[IP ADDRESS]/ or http://[URL]/ .
67 | Please do not add anything after the final / .
68 |
69 | setCurrentGrafUrl(input.target.value)}
72 | value={currentGrafUrl}/>
73 |
74 | );
75 | };
76 |
77 | return(
78 |
87 | );
88 | };
89 |
90 | export default InitialSetup;
--------------------------------------------------------------------------------
/src/server/controllers/metricsController.ts:
--------------------------------------------------------------------------------
1 | import { Job, JobArray, Target, TargetIpArray, TargetsArray, ResponseObject, PanelObject, Role } from '../../types.js';
2 | import fs from 'fs';
3 |
4 | // Interface for controller
5 | interface MetricsController {
6 | getListOfTargets: ResponseObject;
7 | generatePanelBody: ResponseObject;
8 | generateStaticPanels: ResponseObject;
9 |
10 | }
11 |
12 | // Controller
13 | const metricsController: MetricsController = {
14 |
15 | /**
16 | * Method which will grab a list of targets from our targets.json and set it into res.locals
17 | */
18 | getListOfTargets(req, res, next) {
19 | const targets: TargetsArray = JSON.parse(fs.readFileSync('./prometheus/targets.json', 'utf-8'));
20 | const jobsArray : JobArray = [];
21 | const targetsArray: TargetIpArray = [];
22 |
23 | targets.forEach((target: Target) => {
24 | jobsArray.push(target.labels);
25 | targetsArray.push(target.targets[0]);
26 | });
27 |
28 | res.locals.jobs = jobsArray;
29 | res.locals.targets = targetsArray;
30 | return next();
31 | },
32 |
33 | /**
34 | * Method which will generate the panel body needed by the grafana controller given some values in a body
35 | * This method will iterate through each panelTitle and create a body object for it and push it back into the panels object
36 | */
37 | generatePanelBody(req, res, next){
38 | const {panelType, panelTitles, expr} = req.body;
39 |
40 | const panelObjects: PanelObject[] = [];
41 |
42 | panelTitles.forEach((job: Job) => {
43 | const title: string = job.job;
44 | const role: Role = job.role;
45 |
46 | if(role === 'Manager' || role === 'Worker'){
47 | const panelExpr = expr.replace(', job=}', `, job='${title}'}`);
48 | panelObjects.push(
49 | {
50 | title,
51 | expression: panelExpr,
52 | graphType: panelType,
53 | role
54 | }
55 | );
56 | }
57 | });
58 |
59 | res.locals.panels = {'panels': panelObjects};
60 |
61 | return next();
62 | },
63 |
64 | /**
65 | * This method works to read from the staticPanels.json which has all of the panel bodies avaliable within it and save it to res.locals
66 | */
67 | generateStaticPanels(req, res, next){
68 | console.log('In generateStaticPanels');
69 |
70 | const staticPanelsArray: PanelObject[] = JSON.parse(fs.readFileSync('./grafana/staticPanels.json', 'utf-8'));
71 | res.locals.staticPanels = staticPanelsArray;
72 | return next();
73 | },
74 | };
75 |
76 |
77 | export default metricsController;
--------------------------------------------------------------------------------
/src/server/controllers/initController.ts:
--------------------------------------------------------------------------------
1 | import db from '../models/dockerStormModel.js';
2 | import { ResponseObject } from '../../types.js';
3 | import fs from 'fs';
4 | import * as dotenv from 'dotenv';
5 | dotenv.config({override: true});
6 |
7 | // Interfaces needed for our controller
8 | interface InitController {
9 | initializeDatabase: ResponseObject;
10 | updateEnv: ResponseObject;
11 |
12 | }
13 |
14 | //Controller
15 | const initController: InitController = {
16 |
17 | /**
18 | * We will create the necessary tables if they do not already exist within our database
19 | */
20 | initializeDatabase: async (req, res, next) => {
21 | console.log('In init controller');
22 |
23 | const dbQuery = `CREATE TABLE IF NOT EXISTS users(
24 | "id" SERIAL NOT NULL,
25 | "username" text NOT NULL,
26 | "password" text NOT NULL,
27 | "role" text NOT NULL,
28 | PRIMARY KEY("id"),
29 | UNIQUE("username"));`;
30 |
31 | const dbQueryInfo = `
32 | CREATE TABLE IF NOT EXISTS users_info(
33 | "id" SERIAL NOT NULL,
34 | "username" text NOT NULL,
35 | "organization" text NOT NULL,
36 | "job_title" text NOT NULL,
37 | "email" text NOT NULL,
38 | PRIMARY KEY ("id"),
39 | CONSTRAINT "username" FOREIGN KEY ("username") REFERENCES users("username") ON DELETE CASCADE,
40 | UNIQUE ("username")
41 | );`;
42 |
43 | db.query(dbQuery, [])
44 | .then(() => {
45 | db.query(dbQueryInfo, [])
46 | .then(() => {return next();})
47 | .catch((err) => {
48 | return next({
49 | log: 'Error caught in initialize DB',
50 | status: 400,
51 | message: err,
52 | });
53 | });
54 | })
55 | .catch((err) => {
56 | return next({
57 | log: 'Error caught in initialize DB',
58 | status: 400,
59 | message: err,
60 | });
61 | });
62 | },
63 |
64 | /**
65 | * This method provides a way to update our GRAFANA_API_KEY along with GRAFANA_URL from within our application
66 | */
67 | updateEnv: (req, res, next) => {
68 | if(!process.env.GRAFANA_API_KEY) {
69 | const str = `\nGRAFANA_API_KEY = '${req.body.apiKey}'`;
70 | fs.appendFileSync('./.env', str, 'utf-8');
71 | }
72 | if(!process.env.GRAFANA_URL) {
73 | let s = req.body.grafUrl;
74 | if(s.at(-1) !== '/') s += '/';
75 | const str = `\nGRAFANA_URL = '${s}'`;
76 | fs.appendFileSync('./.env', str, 'utf-8');
77 | }
78 |
79 | dotenv.config({override: true});
80 |
81 | return next();
82 | }
83 | };
84 |
85 |
86 | export default initController;
--------------------------------------------------------------------------------
/__test/client_test/Settings.test.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import '@testing-library/jest-dom';
3 | import { render, fireEvent } from '@testing-library/react';
4 | import Settings from '../../dist/client/pages/Settings.jsx';
5 |
6 |
7 | describe('Settings Page', () => {
8 |
9 | it('should render submit target button and password update button', () => {
10 | const { getByTestId } = render( );
13 | const button = getByTestId('target-button');
14 | expect(button).toHaveTextContent('SUBMIT');
15 | });
16 |
17 | it('should render submit target button and password update button', () => {
18 | const { getByTestId } = render( );
21 | const button = getByTestId('pw-button');
22 | expect(button).toHaveTextContent('SUBMIT');
23 | });
24 |
25 | it('should handle a click when clicking Submit', () => {
26 | const mockClick = jest.fn();
27 | const { getByTestId } = render( );
30 | const button = getByTestId('pw-button');
31 | button.onclick = mockClick;
32 | fireEvent.click(button);
33 | expect(mockClick).toHaveBeenCalledTimes(1);
34 | });
35 |
36 | it('should handle a click when clicking Submit', () => {
37 | const mockClick = jest.fn();
38 | const { getByTestId } = render( );
41 | const button = getByTestId('target-button');
42 | button.onclick = mockClick;
43 | fireEvent.click(button);
44 | expect(mockClick).toHaveBeenCalledTimes(1);
45 | });
46 |
47 | it('should render 3 input fields for password updating', () => {
48 | const { getByPlaceholderText } = render( );
51 | const currPass = getByPlaceholderText('Current Password');
52 | const newPass = getByPlaceholderText('New Password');
53 | const confNewPass = getByPlaceholderText('Confirm New Password');
54 | expect(currPass);
55 | expect(newPass);
56 | expect(confNewPass);
57 | });
58 |
59 | it('should render 3 input fields for target updating', () => {
60 | const { getByPlaceholderText } = render( );
63 | const address = getByPlaceholderText('Ip Address');
64 | const ports = getByPlaceholderText('Port(s) by comma');
65 | const jobName = getByPlaceholderText('Job Name');
66 | expect(address);
67 | expect(ports);
68 | expect(jobName);
69 | });
70 |
71 | it('should contain a dropdown list', () => {
72 | const { getByTestId } = render( );
75 | const dropdown = getByTestId('target-list');
76 | expect(dropdown).toBeInTheDocument();
77 | });
78 | });
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "docker-storm",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "dist/client/electron/index.cjs",
6 | "type": "module",
7 | "scripts": {
8 | "dev": "concurrently \"tsc\" \"webpack-dev-server --mode development --open --hot\"",
9 | "start": "concurrently \"tsc\" \"NODE_ENV=development webpack-dev-server --open\" \"NODE_ENV=development nodemon dist/server/server.js\"",
10 | "build": "NODE_ENV=production webpack",
11 | "server": "NODE_ENV=production nodemon dist/server/server.js",
12 | "s:e": "NODE_ENV=development webpack --config webpack.electron.config.cjs --mode development && electron .",
13 | "test": "jest --config jest.config.cjs --verbose --coverage",
14 | "starttest": "concurrently \"tsc\" \"npm start\" \"npm test\"",
15 | "electron": "concurrently \"tsc\" \"npm start\" \"npm run s:e\""
16 | },
17 |
18 | "repository": {
19 | "type": "git",
20 | "url": "git+https://github.com/oslabs-beta/Docker-Storm.git"
21 | },
22 | "author": "",
23 | "license": "ISC",
24 | "bugs": {
25 | "url": "https://github.com/oslabs-beta/Docker-Storm/issues"
26 | },
27 | "homepage": "https://github.com/oslabs-beta/Docker-Storm#readme",
28 | "dependencies": {
29 | "@emotion/react": "^11.10.5",
30 | "@emotion/styled": "^11.10.5",
31 | "@mui/icons-material": "^5.10.16",
32 | "@mui/material": "^5.10.17",
33 | "bcryptjs": "^2.4.3",
34 | "cookie-parser": "^1.4.6",
35 | "dotenv": "^16.0.3",
36 | "electron": "^21.3.0",
37 | "esm": "^3.2.25",
38 | "express": "^4.18.2",
39 | "framer-motion": "^7.6.19",
40 | "node-fetch": "^3.3.0",
41 | "pg": "^8.8.0",
42 | "react": "^18.2.0",
43 | "react-dom": "^18.2.0",
44 | "react-router-dom": "^6.4.3"
45 | },
46 | "devDependencies": {
47 | "@babel/core": "^7.19.6",
48 | "@babel/preset-env": "^7.19.4",
49 | "@babel/preset-react": "^7.18.6",
50 | "@testing-library/jest-dom": "^5.16.5",
51 | "@testing-library/react": "^13.4.0",
52 | "@testing-library/user-event": "^14.4.3",
53 | "@types/bcryptjs": "^2.4.2",
54 | "@types/cookie-parser": "^1.4.3",
55 | "@types/cors": "^2.8.12",
56 | "@types/jest": "^29.2.3",
57 | "@types/jsdom-global": "^3.0.4",
58 | "@types/node": "^18.11.9",
59 | "@types/pg": "^8.6.5",
60 | "@types/react": "^18.0.25",
61 | "@types/react-dom": "^18.0.9",
62 | "@types/supertest": "^2.0.12",
63 | "@types/whatwg-fetch": "^0.0.33",
64 | "@typescript-eslint/eslint-plugin": "^5.44.0",
65 | "@typescript-eslint/parser": "^5.44.0",
66 | "babel-jest": "^29.3.1",
67 | "babel-loader": "^9.0.0",
68 | "concurrently": "^7.6.0",
69 | "cors": "^2.8.5",
70 | "css-loader": "^6.7.1",
71 | "electron": "^21.3.1",
72 | "eslint": "^8.28.0",
73 | "eslint-plugin-react": "^7.31.10",
74 | "file-loader": "^6.2.0",
75 | "html-webpack-plugin": "^5.5.0",
76 | "identity-obj-proxy": "^3.0.0",
77 | "jest": "^29.3.1",
78 | "jest-environment-jsdom": "^29.3.1",
79 | "jest-transform-stub": "^2.0.0",
80 | "jsdom": "^20.0.3",
81 | "jsdom-global": "^3.0.2",
82 | "nodemon": "^2.0.20",
83 | "style-loader": "^3.3.1",
84 | "supertest": "^6.3.1",
85 | "ts-jest": "^29.0.3",
86 | "ts-node": "^10.9.1",
87 | "typescript": "^4.9.3",
88 | "webpack": "^5.74.0",
89 | "webpack-cli": "^4.10.0",
90 | "webpack-dev-server": "^4.11.1",
91 | "whatwg-fetch": "^3.6.2"
92 | }
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/src/client/App.tsx:
--------------------------------------------------------------------------------
1 | import { HashRouter, Route, Routes } from 'react-router-dom';
2 | import Login from './pages/login.jsx';
3 | import { Job, Target} from '../types.js';
4 | import Signup from './pages/signup.jsx';
5 | import React, {useEffect, useState} from 'react';
6 | import RenderViews from './RenderViews.jsx';
7 | import InitialSetup from './pages/initialSetup.jsx';
8 | //import PgInit from './pages/pgInit.jsx';
9 | import 'whatwg-fetch';
10 |
11 |
12 | import '../../resources/styling/styles.css';
13 |
14 |
15 | const App: React.FC = (): JSX.Element => {
16 | const [apiKey, setApiKey] = useState('');
17 | const [grafUrl, setGrafUrl] = useState('');
18 | const [dashId, setDashId] = useState('');
19 | const [targetsArr, setTargetsArr] = useState([]);
20 | const [openSignup, setOpenSignup] = useState(false);
21 |
22 |
23 | async function intializeDashboard() {
24 | const jobsList = await fetch('/metric').then(data => {return data.json();});
25 | const arr = makeTargetArray(jobsList.jobs, jobsList.targets);
26 | setTargetsArr(arr);
27 |
28 | const panelList = await fetch('/metric/genPanel', {
29 | method: 'POST',
30 | headers: {
31 | 'content-type': 'application/json'
32 | },
33 | body: JSON.stringify({panelTitles: jobsList.jobs, panelType: 'gauge', expr: '100 - (avg(irate(node_cpu_seconds_total{mode=\'idle\', job=}[1m])) * 100)'}),
34 | })
35 | .then(data => {return data.json();});
36 |
37 | const staticPanels = await fetch('/metric/genStaticPanels').then(data => {return data.json();});
38 | panelList.panels.unshift(...staticPanels);
39 |
40 | fetch('/graf/init', {
41 |
42 | method: 'POST',
43 | headers: {
44 | 'content-type': 'application/json'
45 | },
46 | body: JSON.stringify(panelList),
47 | })
48 | .then((data) => data.json())
49 | .then((result) => {
50 | setDashId(result.ApiKey);
51 | });
52 | }
53 |
54 | const makeTargetArray = (jobs: Job[], ips: string[]) : Target[] => {
55 | const result: Target[] = [];
56 | for(let i = 0; i < jobs.length; i++) {
57 | const obj: Target = {
58 | targets: [ips[i]],
59 | labels: {
60 | job: jobs[i].job,
61 | role: jobs[i].role
62 | }
63 | };
64 | result.push(obj);
65 | }
66 | return result;
67 | };
68 |
69 | useEffect(() => {
70 | fetch('/init');
71 | console.log('useeffect ran');
72 | if(!apiKey || !grafUrl) return;
73 |
74 | intializeDashboard();
75 | }, [apiKey, grafUrl]);
76 |
77 |
78 | useEffect(() => {
79 | console.log('Init DB ran');
80 | fetch('/init');
81 | }, []);
82 |
83 | return (
84 |
85 |
86 |
87 | }/>
93 | }/>
99 | }/>
106 |
107 |
108 |
109 |
110 |
111 | );
112 | };
113 |
114 | export default App;
115 |
116 |
--------------------------------------------------------------------------------
/__test/client_test/App.test.tsx:
--------------------------------------------------------------------------------
1 | import 'whatwg-fetch';
2 | import * as React from 'react';
3 | import '@testing-library/jest-dom';
4 | import { MemoryRouter as Router } from 'react-router-dom';
5 | import { render, screen, fireEvent } from '@testing-library/react';
6 | import App from '../../dist/client/App.jsx';
7 | import RenderViews from '../../dist/client/RenderViews.jsx';
8 | import Metrics from '../../dist/client/pages/Metrics.jsx';
9 | import Settings from '../../dist/client/pages/Settings.jsx';
10 | import Users from '../../dist/client/pages/Users.jsx';
11 |
12 |
13 | describe('Initial Login View', () => {
14 |
15 | it('should have input fields for username and password', () => {
16 | render( );
17 | const username = screen.getByTestId('username-input');
18 | const password = screen.getByTestId('password-input');
19 | expect(username);
20 | expect(password);
21 | });
22 |
23 | it('should render Initial Login Page', () => {
24 | render( );
25 | const loginButton = screen.getByText('LOGIN');
26 | const signupButton = screen.getByText('SIGNUP');
27 | expect(loginButton).toBeInTheDocument();
28 | expect(signupButton).toBeInTheDocument();
29 | });
30 |
31 | it('should respond with click if Signup button is clicked', () => {
32 | render( );
33 | const mockClick = jest.fn();
34 | const button = screen.getByTestId('sign-up button');
35 | button.onclick = mockClick;
36 | fireEvent.click(button);
37 | expect(mockClick).toHaveBeenCalledTimes(1);
38 | });
39 |
40 | it('should respond with click if Login button is clicked', () => {
41 | render( );
42 | const mockClick = jest.fn();
43 | const button = screen.getByTestId('login button');
44 | button.onclick = mockClick;
45 | fireEvent.click(button);
46 | expect(mockClick).toHaveBeenCalledTimes(1);
47 | });
48 |
49 | it('should render Home page', () => {
50 | render(
51 |
52 |
55 | );
56 | const settings = screen.getByText('Settings');
57 | expect(settings).toBeInTheDocument();
58 | });
59 |
60 | it('should render Metrics page', () => {
61 | render(
62 |
63 |
64 | );
65 | const metrics = screen.getByText('Metrics');
66 | expect(metrics).toBeInTheDocument();
67 | });
68 |
69 | it('should render Settings page', () => {
70 | render(
71 |
72 |
75 | );
76 | const updatePassword = screen.getByText('UPDATE PASSWORD');
77 | expect(updatePassword).toBeInTheDocument();
78 | });
79 |
80 | it('should render Users page', () => {
81 | render(
82 |
83 |
84 | );
85 | const userList = screen.getByText('List of all users');
86 | expect(userList).toBeInTheDocument();
87 | });
88 | });
89 |
90 | describe('Logout Button', () => {
91 | it('should display login page', () => {
92 | render( );
93 | const loginButton = screen.getByText('LOGIN');
94 | const signupButton = screen.getByText('SIGNUP');
95 | expect(loginButton).toBeInTheDocument();
96 | expect(signupButton).toBeInTheDocument();
97 | });
98 |
99 |
100 | });
101 |
102 |
103 |
--------------------------------------------------------------------------------
/resources/styling/styles.css:
--------------------------------------------------------------------------------
1 | /* --------------------------------------------------- Font Imports --------------------------------------------------- */
2 |
3 | @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;400&family=Roboto:wght@100;400;500&display=swap');
4 | @import url('https://fonts.googleapis.com/css2?family=Mulish:wght@200;300;400;500&display=swap');
5 | /* --------------------------------------------------- Root / Global Classes --------------------------------------------------- */
6 |
7 |
8 |
9 | :root {
10 | --Nunito: 'Nunito', sans-serif;
11 | --Roboto: 'Roboto', sans-serif;
12 | --Mulish: 'Mulish', sans-serif;
13 | --light-blue: #4C82FE;
14 | --soft-black: #121212;
15 | --dark-grey: #959595;
16 | }
17 |
18 | .white-text {
19 | color: #ffffff;
20 | }
21 |
22 | .dark-text {
23 | color: var(--soft-black);
24 | }
25 |
26 | h1 {
27 | font-family: var(--Roboto);
28 | }
29 |
30 | h2 {
31 | font-family: var(--Roboto);
32 | }
33 |
34 | p {
35 | font-family: var(--Nunito)
36 | }
37 |
38 | h3 {
39 | color: #3a3a3a;
40 | }
41 |
42 | .centered {
43 | text-align: center;
44 | }
45 |
46 | body {
47 | margin: 0 0;
48 | }
49 |
50 | /* --------------------------------------------------- Signup Modal CSS --------------------------------------------------- */
51 |
52 |
53 |
54 | #login-big-div {
55 | display: flex;
56 | flex-direction: row;
57 | }
58 |
59 | .half-n-half {
60 | display: flex;
61 | height: 100vh;
62 | width: 50vw;
63 | justify-content: center;
64 | align-items: center;
65 | }
66 |
67 | #left-div {
68 | display: flex;
69 | flex-direction: column;
70 | }
71 |
72 |
73 | .error-p {
74 | color: #cf1515;
75 | font-size: 14px;
76 | }
77 |
78 |
79 | /* Right div CSS*/
80 |
81 | #right-div {
82 | background-color: #13507A;
83 | }
84 |
85 | #waves-div {
86 | height: 100vh;
87 | width: 50vw;
88 | background-position: bottom;
89 | background-repeat: no-repeat;
90 | background-size: 120% 80%;
91 | padding-bottom: 10px;
92 | display: flex;
93 | justify-content: center;
94 | align-items: center;
95 | }
96 |
97 | /* --------------------------------------------------- Signup Modal CSS --------------------------------------------------- */
98 |
99 |
100 | #signup-background-div {
101 | position: fixed;
102 | top: 0;
103 | left: 0;
104 | background: rgb(76,130,254, 0.8);
105 | width: 100vw;
106 | height: 100vh;
107 | display: flex;
108 | justify-content: center;
109 | align-items: center;
110 | }
111 |
112 |
113 | #signup-inner-div {
114 | width: 300px;
115 | background-color: #ffffff;
116 | display: flex;
117 | flex-direction: column;
118 | padding: 30px;
119 | border-radius: 25px;
120 | }
121 |
122 |
123 |
124 |
125 |
126 | /* --------------------------------------------------- RenderViews CSS --------------------------------------------------- */
127 |
128 |
129 | .navbar {
130 | position: sticky;
131 | top: 0;
132 | height: 100vh;
133 | width: 210px;
134 | background-color: #091931;
135 | font-family: var(--Nunito);
136 | }
137 |
138 |
139 | .navbar li {
140 | font-size: 18px;
141 | letter-spacing: 4px;
142 | height: 30px;
143 | margin-top: 20px;
144 | padding: 5px;
145 | text-decoration: none;
146 | list-style: none;
147 | }
148 |
149 |
150 | .navbar li a {
151 | text-decoration: none;
152 | color: #ffffff;
153 | font-family: var(--Mulish);
154 | }
155 |
156 | .navbar li:hover{
157 | border-left: #4C82FE 5px solid;
158 | padding-left: 15px;
159 | transition-duration: 0.4s;
160 | }
161 |
162 | #logout {
163 | position: absolute;
164 | bottom: 20px;
165 | }
166 |
167 | #navbar-logo {
168 | margin-top: 20px;
169 | margin-left: 20px;
170 | }
171 |
172 | svg {
173 | vertical-align: middle;
174 | }
175 |
176 |
177 |
178 | /* Logos */
179 |
180 | #login-logo-div img{
181 | width: 150px;
182 | }
183 |
184 |
185 | #navbar-logo {
186 | padding-top: 30px;
187 | padding-bottom: 20px;
188 | width: 95px;
189 | }
190 |
191 | #mac-img {
192 | width: 650px;
193 | }
--------------------------------------------------------------------------------
/__test/server_test/supertest.test.ts:
--------------------------------------------------------------------------------
1 | import request from 'supertest';
2 | import db from '../../src/server/models/dockerStormModel';
3 | const server = 'http://localhost:8080';
4 |
5 | interface User {
6 | username: string,
7 | password: string,
8 | role: string
9 | }
10 |
11 | const userOne: User = {
12 | username: 'TestUser',
13 | password: 'TestPassword',
14 | role: 'TestRole'
15 | };
16 |
17 | beforeAll(async () => {
18 | const createTest = `CREATE TABLE IF NOT EXISTS users(
19 | "id" SERIAL NOT NULL,
20 | "username" text NOT NULL,
21 | "password" text NOT NULL,
22 | "role" text NOT NULL,
23 | PRIMARY KEY("id"),
24 | UNIQUE("username"))`;
25 |
26 | await db.query(createTest, []);
27 | });
28 |
29 | afterAll(async() => {
30 | const deleteTest = 'DELETE FROM users WHERE username=$1';
31 | await db.query(deleteTest, [userOne.username]);
32 | });
33 |
34 |
35 | describe('Route Testing', () => {
36 |
37 | describe('Route Integration for Users', () => {
38 |
39 | describe('Upon Initiating App', () => {
40 | it('responds with 200 status and the login page', () => {
41 | return request(server)
42 | .get('/')
43 | .expect(200);
44 | });
45 | });
46 |
47 | describe('Upon Initiating App', () => {
48 | it('responds by creating a user with entered name and pw', () => {
49 | return request(server)
50 | .post('/user/signup')
51 | .send(userOne)
52 | .expect(200);
53 | });
54 | });
55 |
56 | describe('Upon Initiating App', () => {
57 | it('responds with error message if nothing is sent', () => {
58 | return request(server)
59 | .post('/user/login')
60 | .expect(400);
61 | });
62 | });
63 |
64 | describe('Upon Initiating App', () => {
65 | it('should post a request which allows us to update our env file', () => {
66 | return request(server)
67 | .post('/user/env')
68 | .expect(200);
69 | });
70 | });
71 |
72 | describe('Getting User List', () => {
73 | it('responds by providing user list', () => {
74 | return request(server)
75 | .get('/user/all')
76 | .expect(200);
77 | });
78 | });
79 |
80 | describe('Upon Deleting User', () => {
81 | it('responds by deleting the user', () => {
82 | return request(server)
83 | .delete('/user/')
84 | .send(userOne.username)
85 | .expect(200);
86 | });
87 | });
88 | });
89 |
90 |
91 | describe('Route Integration for Grafana', () => {
92 |
93 | //Get request that creates an EmptyDB - verify if user has Grafana installed
94 | xdescribe('Should create an Empty DB', () => {
95 | it('responds by adding targets', () => {
96 | return request(server)
97 | .get('/graf/')
98 | .expect(200);
99 | });
100 | });
101 |
102 | //Post request initalizing the dashboard not already existing - verify if user has Grafana installed
103 | xdescribe('Upon Initializing Grafana', () => {
104 | it('responds with 200 status and the metrics page', () => {
105 | return request(server)
106 | .post('/graf/init')
107 | .expect(200);
108 | });
109 | });
110 |
111 | describe('Should Add Targets', () => {
112 | it('responds by adding targets', () => {
113 | return request(server)
114 | .post('/graf/targetsAdd')
115 | .expect(200);
116 | });
117 | });
118 | });
119 |
120 |
121 | describe('Route Integration for Initializing DB', () => {
122 |
123 | describe('Should create an Empty DB', () => {
124 | it('responds by creating an Empty DB', () => {
125 | return request(server)
126 | .get('/init/')
127 | .expect(200);
128 | });
129 | });
130 | });
131 |
132 | describe('Route Integration for Metrics', () => {
133 |
134 | //verify if user has Grafana installed
135 | xdescribe('Should generate all targets', () => {
136 | it('responds by generating all targetsa', () => {
137 | return request(server)
138 | .get('/metric/')
139 | .expect(200);
140 | });
141 | });
142 |
143 | //verify if user has Grafana installed
144 | xdescribe('Should generate panel bodies', () => {
145 | it('responds by creating a panel', () => {
146 | return request(server)
147 | .post('/metric/genPanel')
148 | .expect(200);
149 | });
150 | });
151 |
152 | //verify if user has Grafana installed
153 | xdescribe('Should generate all static panels', () => {
154 | it('responds by creating static panels', () => {
155 | return request(server)
156 | .get('/metric/genStaticPanels')
157 | .expect(200);
158 | });
159 | });
160 | });
161 | });
--------------------------------------------------------------------------------
/src/client/pages/users.tsx:
--------------------------------------------------------------------------------
1 | import 'whatwg-fetch';
2 | import React, {useState, useEffect} from 'react';
3 | import { Box, Container, TableContainer, TextField, Button, Table, TableBody, TableCell, TableHead, TableRow, Paper } from '@mui/material';
4 | import theme from '../theme.jsx';
5 |
6 | interface User {
7 | username: string,
8 | role: string
9 | organization?: string,
10 | email?: string,
11 | job_title?: string,
12 | TableRow?: React.ElementType;
13 | }
14 |
15 | const styles = {
16 | buttonStyles: {
17 | marginTop: '10px',
18 | border: theme.palette.primary.main,
19 | borderStyle: 'solid',
20 | backgroundColor: theme.palette.primary.main,
21 | '&:hover': {
22 | backgroundColor: 'white',
23 | color: theme.palette.primary.main,
24 | },
25 | color: 'white'
26 | },
27 | gridStyles: {
28 | width: '50%',
29 | margin: '0px'
30 | },
31 | fields: {
32 | backgroundColor: '#ffffff',
33 | },
34 | tableHeader: {
35 | color: '#9FA2B4',
36 | }
37 | };
38 |
39 | const Users = () => {
40 | const [userList, setUserList] = useState([]);
41 | const [username, setUsername] = useState('');
42 | const [role, setRole] = useState('');
43 | const [password, setPassword] = useState('');
44 | const [confirmPassword, setConfirmPassword] = useState('');
45 | const [missingField, setMissingField] = useState(false);
46 | const [matchPassword, setMatchPassword] = useState(false);
47 | const [uniqueUser, setUniqueUser] = useState(false);
48 | const addUsersToArray = (arr: User[]) => {
49 | setUserList(arr);
50 | };
51 |
52 | const grabUsers = () => {
53 | window.fetch('/user/all')
54 | .then((data) => data.json())
55 | .then((result) => {
56 | addUsersToArray(result as User[]);
57 | });
58 | };
59 |
60 | const addNewUser = () => {
61 | setMissingField(false);
62 | setMatchPassword(false);
63 | setUniqueUser(false);
64 |
65 | if(!username || !role || !password || !confirmPassword) {
66 | setMissingField(true);
67 | return;
68 | }
69 |
70 | if(password !== confirmPassword) {
71 | setMatchPassword(true);
72 | return;
73 | }
74 |
75 | const body = {
76 | username: username,
77 | role: role,
78 | password: password,
79 | };
80 |
81 | fetch('/user/signup', {
82 | method: 'POST',
83 | headers: {
84 | 'content-type' : 'application/json'
85 | },
86 | body: JSON.stringify(body)
87 | }).then((response) => {
88 | if(response.status === 200) {
89 | const newUserList = [...userList];
90 | const newUser: User = {
91 | username: username,
92 | role: role,
93 | };
94 | newUserList.push(newUser);
95 | setUserList(newUserList);
96 | setUsername('');
97 | setRole('');
98 | setPassword('');
99 | setConfirmPassword('');
100 | setMissingField(false);
101 | setMatchPassword(false);
102 | setUniqueUser(false);
103 | } else {
104 | setUniqueUser(true);
105 | }
106 | });
107 | };
108 |
109 | useEffect(() => {
110 | grabUsers();
111 | },[]);
112 |
113 | const mappedList = userList.map(user => {
114 | const username = user.username;
115 | const role = user.role;
116 | const jobTitle = user.job_title;
117 | const organization = user.organization;
118 | const email = user.email;
119 |
120 | return (
121 |
122 | {username}
123 | {organization}
124 | {jobTitle}
125 | {email}
126 | {role}
127 |
128 | );});
129 |
130 |
131 | return (
132 | <>
133 |
134 |
135 | List of all users
136 |
137 |
138 |
139 |
140 | Username
141 | Organization
142 | Job Title
143 | Email
144 | Role
145 |
146 |
147 |
148 | {mappedList}
149 |
150 |
151 |
152 |
153 |
154 |
155 | e.preventDefault()} sx={{display:'flex', flexDirection: 'row', justifyContent:'space-between', alignContent: 'center'}}>
156 | setUsername(input.target.value)} style={styles.fields}/>
157 | setRole(input.target.value)} style={styles.fields}/>
158 | setPassword(input.target.value)} style={styles.fields}/>
159 | setConfirmPassword(input.target.value)} style={styles.fields}/>
160 | Add New User
161 | {missingField && Please fill out all fields before submitting
}
162 | {matchPassword && Passwords do not match
}
163 | {uniqueUser && Username already taken, please choose another username
}
164 |
165 |
166 |
167 | >
168 | );
169 | };
170 |
171 | export default Users;
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
2 | # Contributor Covenant Code of Conduct
3 |
4 | ## Our Pledge
5 |
6 | We as members, contributors, and leaders pledge to make participation in our
7 | community a harassment-free experience for everyone, regardless of age, body
8 | size, visible or invisible disability, ethnicity, sex characteristics, gender
9 | identity and expression, level of experience, education, socio-economic status,
10 | nationality, personal appearance, race, caste, color, religion, or sexual
11 | identity and orientation.
12 |
13 | We pledge to act and interact in ways that contribute to an open, welcoming,
14 | diverse, inclusive, and healthy community.
15 |
16 | ## Our Standards
17 |
18 | Examples of behavior that contributes to a positive environment for our
19 | community include:
20 |
21 | * Demonstrating empathy and kindness toward other people
22 | * Being respectful of differing opinions, viewpoints, and experiences
23 | * Giving and gracefully accepting constructive feedback
24 | * Accepting responsibility and apologizing to those affected by our mistakes,
25 | and learning from the experience
26 | * Focusing on what is best not just for us as individuals, but for the overall
27 | community
28 |
29 | Examples of unacceptable behavior include:
30 |
31 | * The use of sexualized language or imagery, and sexual attention or advances of
32 | any kind
33 | * Trolling, insulting or derogatory comments, and personal or political attacks
34 | * Public or private harassment
35 | * Publishing others' private information, such as a physical or email address,
36 | without their explicit permission
37 | * Other conduct which could reasonably be considered inappropriate in a
38 | professional setting
39 |
40 | ## Enforcement Responsibilities
41 |
42 | Community leaders are responsible for clarifying and enforcing our standards of
43 | acceptable behavior and will take appropriate and fair corrective action in
44 | response to any behavior that they deem inappropriate, threatening, offensive,
45 | or harmful.
46 |
47 | Community leaders have the right and responsibility to remove, edit, or reject
48 | comments, commits, code, wiki edits, issues, and other contributions that are
49 | not aligned to this Code of Conduct, and will communicate reasons for moderation
50 | decisions when appropriate.
51 |
52 | ## Scope
53 |
54 | This Code of Conduct applies within all community spaces, and also applies when
55 | an individual is officially representing the community in public spaces.
56 | Examples of representing our community include using an official e-mail address,
57 | posting via an official social media account, or acting as an appointed
58 | representative at an online or offline event.
59 |
60 | ## Enforcement
61 |
62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
63 | reported to the community leaders responsible for enforcement at
64 | [INSERT CONTACT METHOD].
65 | All complaints will be reviewed and investigated promptly and fairly.
66 |
67 | All community leaders are obligated to respect the privacy and security of the
68 | reporter of any incident.
69 |
70 | ## Enforcement Guidelines
71 |
72 | Community leaders will follow these Community Impact Guidelines in determining
73 | the consequences for any action they deem in violation of the Code of Conduct. If any violations take place please report them to DockerStorm@gmail.com Below will be all the terms of the Code of Conduct:
74 |
75 | ### 1. Correction
76 |
77 | **Community Impact**: Use of inappropriate language or other behavior deemed
78 | unprofessional or unwelcome in the community.
79 |
80 | **Consequence**: A private, written warning from community leaders, providing
81 | clarity around the nature of the violation and an explanation of why the
82 | behavior was inappropriate. A public apology may be requested.
83 |
84 | ### 2. Warning
85 |
86 | **Community Impact**: A violation through a single incident or series of
87 | actions.
88 |
89 | **Consequence**: A warning with consequences for continued behavior. No
90 | interaction with the people involved, including unsolicited interaction with
91 | those enforcing the Code of Conduct, for a specified period of time. This
92 | includes avoiding interactions in community spaces as well as external channels
93 | like social media. Violating these terms may lead to a temporary or permanent
94 | ban.
95 |
96 | ### 3. Temporary Ban
97 |
98 | **Community Impact**: A serious violation of community standards, including
99 | sustained inappropriate behavior.
100 |
101 | **Consequence**: A temporary ban from any sort of interaction or public
102 | communication with the community for a specified period of time. No public or
103 | private interaction with the people involved, including unsolicited interaction
104 | with those enforcing the Code of Conduct, is allowed during this period.
105 | Violating these terms may lead to a permanent ban.
106 |
107 | ### 4. Permanent Ban
108 |
109 | **Community Impact**: Demonstrating a pattern of violation of community
110 | standards, including sustained inappropriate behavior, harassment of an
111 | individual, or aggression toward or disparagement of classes of individuals.
112 |
113 | **Consequence**: A permanent ban from any sort of public interaction within the
114 | community.
115 |
116 | ## Attribution
117 |
118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119 | version 2.1, available at
120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121 |
122 | Community Impact Guidelines were inspired by
123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124 |
125 | For answers to common questions about this code of conduct, see the FAQ at
126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127 | [https://www.contributor-covenant.org/translations][translations].
128 |
129 | [homepage]: https://www.contributor-covenant.org
130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131 | [Mozilla CoC]: https://github.com/mozilla/diversity
132 | [FAQ]: https://www.contributor-covenant.org/faq
133 | [translations]: https://www.contributor-covenant.org/translations
134 |
--------------------------------------------------------------------------------
/src/client/pages/login.tsx:
--------------------------------------------------------------------------------
1 | import React, {useState} from 'react';
2 | import { useNavigate } from 'react-router-dom';
3 | import mac from '../../../resources/media/mac.png';
4 | import waves from '../../../resources/media/waves.png';
5 | import loginLogo from '../../../resources/media/login-logo.png';
6 | import {TextField, Container, Box, Grid, Button } from '@mui/material';
7 | import theme from '../theme.jsx';
8 | import Signup from './signup.jsx';
9 | import { DefaultDeserializer } from 'v8';
10 |
11 | interface Props {
12 | setApiKey: (arg: string) => void;
13 | setGrafUrl: (arg: string) => void;
14 | grafUrl: string;
15 | apiKey: string;
16 | }
17 |
18 | interface ResponseObject {
19 | grafUrl: string;
20 | key: string;
21 | }
22 |
23 | const Login = (props: Props) => {
24 | const [username, setUsername] = useState('');
25 | const [password, setPassword] = useState('');
26 | const [invalid, setInvalid] = useState(false);
27 | const [openSignup, setOpenSignup] = useState(false);
28 | const navigate = useNavigate();
29 |
30 | const setKeys = (apiKey: string, grafUrl: string) => {
31 | props.setGrafUrl(grafUrl);
32 | props.setApiKey(apiKey);
33 | };
34 |
35 | const confirmCredentials = async () => {
36 | const body = {
37 | username: username,
38 | password: password
39 | };
40 |
41 | const result = await fetch('/user/login', {
42 | method: 'POST',
43 | headers: {'Content-Type': 'application/json'},
44 | body: JSON.stringify(body),
45 | });
46 |
47 | if(result.status !== 200) {
48 | setInvalid(true);
49 | setUsername('');
50 | setPassword('');
51 | return;
52 | }
53 | const data: ResponseObject = await result.json();
54 |
55 | setKeys(data.key, data.grafUrl);
56 | if(data.key && data.grafUrl) {
57 | navigate('/app/metrics');
58 | } else {
59 | navigate('/setup');
60 | }
61 | };
62 |
63 | return (
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
75 | event.preventDefault()}
79 | >
80 |
86 |
91 | setUsername(input.target.value)}
99 | sx={{ width: 350 }}
100 | />
101 |
102 |
108 | setPassword(input.target.value)}
116 | sx={{ width: 350 }}
117 | />
118 |
119 |
120 |
125 | { setOpenSignup(true); }}>SIGNUP
129 |
130 |
131 |
132 |
137 | LOGIN
151 |
152 |
153 |
154 | {invalid && Invalid username/password please try again
}
155 |
156 |
157 |
158 |
159 | {openSignup &&
}
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 | );
175 | };
176 |
177 |
178 |
179 | export default Login;
--------------------------------------------------------------------------------
/src/server/controllers/grafanaController.ts:
--------------------------------------------------------------------------------
1 | import fs from 'fs';
2 | import fetch from 'node-fetch';
3 | import * as dotenv from 'dotenv';
4 | import * as manageID from '../helperFunctions/manageFiles.js';
5 | import { ResponseObject } from '../../types.js';
6 | dotenv.config({override: true});
7 |
8 | //Necessary Interfaces for each function
9 | interface GrafanaController {
10 | createDB: ResponseObject;
11 | updateDB: ResponseObject;
12 | getDashByUid: ResponseObject;
13 | createPanel: ResponseObject;
14 | addTarget: ResponseObject;
15 | }
16 |
17 | interface ResultObj {
18 | id?: number;
19 | slug?: string;
20 | status: string;
21 | uid?: string;
22 | url?: string;
23 | version?: number;
24 | message: string;
25 | }
26 |
27 | interface Panel {
28 | title: string;
29 | expression: string;
30 | graphType: string;
31 | }
32 |
33 | //Grab the grafID so the program can know which ID to assign a panel
34 | let grafID = manageID.getGrafID();
35 |
36 | //Controller
37 | const grafanaController: GrafanaController = {
38 |
39 | /**
40 | * This method will send a fetch request to the grafana HTTP API in order to create an empty dash
41 | * The empty dash will be created based off of paramaters that we send in through the dbTemplate.json file
42 | * We will also set the GRAFANA_DASHBOARD_ID so our application knows how to refrence the dashboard
43 | */
44 | createDB(req,res,next) {
45 | console.log('In createDB Controller');
46 |
47 | if(process.env.GRAFANA_DASHBOARD_ID) {
48 | return res.status(200).send({ApiKey: process.env.GRAFANA_DASHBOARD_ID});
49 | }
50 |
51 | const dash = fs.readFileSync('./grafana/jsonTemplates/dbTemplate.json', 'utf-8');
52 |
53 | fetch(`${process.env.GRAFANA_URL}api/dashboards/db/`, {
54 | method: 'POST',
55 | body: dash,
56 | headers: {
57 | 'Content-type': 'application/json',
58 | 'accept': 'application/json',
59 | 'authorization': `Bearer ${process.env.GRAFANA_API_KEY}`
60 | },
61 | }).then((data) => data.json())
62 | .then((result) => {return result as ResultObj;})
63 | .then((result) => {
64 | console.log(result);
65 | if(result.uid) {
66 | const str = `\nGRAFANA_DASHBOARD_ID = '${result.uid}'`;
67 | fs.appendFileSync('./.env', str, 'utf-8');
68 | return next();
69 | }
70 | return next();
71 | })
72 | .catch((err) => {
73 | return next(err);
74 | console.log(err);
75 | });
76 | },
77 |
78 | /**
79 | * This method will use our dashboard id from the env and the grafana HTTP API in order to grab the json of the entire grafana dashboard
80 | * From there we will go ahead and save it in res.locals.dashboard to be used further down the middleware
81 | */
82 | getDashByUid(req, res, next) {
83 | console.log('In getDashByUid Controller!');
84 | dotenv.config({override: true});
85 | fetch(`${process.env.GRAFANA_URL}api/dashboards/uid/${process.env.GRAFANA_DASHBOARD_ID}`, {
86 | method: 'GET',
87 | headers: {
88 | 'Content-type': 'application/json',
89 | 'accept': 'application/json',
90 | 'authorization': `Bearer ${process.env.GRAFANA_API_KEY}`
91 | },
92 | })
93 | .then((data) => data.json())
94 | .then((dashboard) => {
95 | res.locals.dashboard = dashboard;
96 | return next();
97 | });
98 | },
99 |
100 | /**
101 | * This method is responsible for creating actual panel json files which grafana can understand
102 | * We will read from the body the entire array of panels and loop through each panel object
103 | * From there we can generate a newPanel json from a template created using the graphType from the current panel
104 | * We can then set important values within our newPanel using each panel's object info
105 | * The newPanel is then pushed into a panelsArray
106 | * Finally that array is saved into res.locals.panels
107 | */
108 | createPanel(req, res, next){
109 | console.log('In createPanel');
110 | const {panels} = req.body;
111 | const panelsArray: Record[] = [];
112 | const panelPos = [0, 12];
113 |
114 |
115 | panels.forEach((panel: Panel, index: number) => {
116 | grafID = manageID.incrementGrafID(grafID);
117 | const newPanel = JSON.parse(fs.readFileSync(`./grafana/jsonTemplates/${panel.graphType}Template.json`, 'utf-8'));
118 | if(newPanel.gridPos.w === 12){
119 | newPanel.gridPos.x = panelPos[index % 2];
120 | }
121 | newPanel.title = panel.title;
122 | newPanel.targets[0].expr = panel.expression;
123 | newPanel.id = grafID.panelId;
124 | panelsArray.push(newPanel);
125 | });
126 |
127 |
128 | res.locals.panels = panelsArray;
129 | return next();
130 | },
131 |
132 | /**
133 | * This method works to update our actual dashboard with new panels
134 | * We will grab panels from res.locals and then push that into the dashboard in res.locals
135 | * These are grabbed from previous middleware
136 | * If the panels key does not already exist within our dashboard then we will first create it else just push
137 | * Once that is done we need to send a request to Grafana's HTTP API in order to save our changes
138 | */
139 | updateDB(req, res, next) {
140 | console.log('In updateDB!');
141 |
142 | const {panels} = res.locals;
143 |
144 | const body = res.locals.dashboard;
145 | if(!('panels' in body.dashboard)){
146 | body.dashboard['panels'] = [...panels];
147 | }
148 | else{
149 | body.dashboard['panels'].push(...panels);
150 | }
151 |
152 | fetch(`${process.env.GRAFANA_URL}api/dashboards/db/`, {
153 | method: 'POST',
154 | body: JSON.stringify(body),
155 | headers: {
156 | 'Content-type': 'application/json',
157 | 'accept': 'application/json',
158 | 'authorization': `Bearer ${process.env.GRAFANA_API_KEY}`
159 | },
160 | })
161 | .then((data) => data.json())
162 | .then((result) => {
163 | return next();
164 | });
165 | },
166 |
167 | /**
168 | * This method will work to add a new target into our targets.json file
169 | * We will first read from the file before pushing our body into it and writing over the file
170 | */
171 | addTarget(req, res, next) {
172 | const targets = JSON.parse(fs.readFileSync('./prometheus/targets.json', 'utf-8'));
173 | targets.push(req.body);
174 | fs.writeFileSync('./prometheus/targets.json', JSON.stringify(targets, null, 4));
175 | return next();
176 | }
177 |
178 | };
179 |
180 |
181 | export default grafanaController;
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Docker Storm ·     
2 |
3 | ## About
4 | Docker Storm provides a easy to use interface in order to view important metrics regarding your current
5 | Docker Swarm cluster and the containers which are being run on them. With the ablity to add new ports
6 | and create new users it's quick to implement and get up and running on your device. Metric tracking is done
7 | using information gathered using cadvisor and node-exporter.
8 |
9 | ## Table of Contents
10 | Application usage/documentation
11 |
12 | - [Features](#features)
13 | - [Documentation](#documentation)
14 | - [Prerequisites](#prerequisites)
15 |
16 | Installation guides
17 |
18 | - [Installation](#installation)
19 | - [Docker Swarm Setup (If needed)](#if-you-need-to-setup-docker-swarm)
20 |
21 | Contributers and other info
22 | - [Contributers](#contributers)
23 | - [Contributing](#contributing)
24 |
25 | ## Features:
26 | Live updating metric tracking in an organized grafana graph
27 |
28 | 
29 |
30 | Settings page to change important user/system information in addition to the ability to add new servers/vm's to track
31 |
32 | 
33 |
34 | Users page to see all the current users and add new users
35 |
36 | 
37 |
38 | Login page with passwords encrypted using bcrypt
39 |
40 | 
41 |
42 | Signup page with fields to enter initial setup information
43 |
44 | 
45 |
46 | [↥Back to top](#table-of-contents)
47 |
48 | ## Prerequisites:
49 | - The host computer running Docker Storm (does not have to be part of the swarm) will need these installed
50 | - `Prometheus` (https://github.com/prometheus/prometheus)
51 | - `Grafana` (https://github.com/grafana/grafana)
52 | - Once installation is complete ensure that `allow_embedding` is enabled see docs for more info on how to enable this
53 | - If you want to allow users to view your Grafana charts without having to log in ensure that anonymous which is under `[auth.anonymous]` is enabled see docs for more info on how to enable this
54 | - (https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/)
55 |
56 | Before being able to run Docker Storm it is expected that you already have a Docker Swarm running with access to the IP addresses of each worker/manager. If not please follow the steps [HERE](#if-you-need-to-setup-docker-swarm) to create a basic Docker Swarm setup using Multipass
57 |
58 | Otherwise if you have a pre-existing swarm running make sure that:
59 | - All Manager/Worker machines have installed
60 | - `Node-Exporter` (https://github.com/prometheus/node_exporter)
61 | - `cAdvisor` (https://github.com/google/cadvisor)
62 |
63 |
64 | [↥Back to top](#table-of-contents)
65 |
66 | ## Installation:
67 |
68 | Clone Repo:
69 | ```sh
70 | git clone https://github.com/oslabs-beta/Docker-Storm.git
71 | ```
72 |
73 | Install Dependencies:
74 | ```sh
75 | npm install
76 | ```
77 |
78 | Please start prometheus using the configuration file provided by Docker Storm:
79 | ```sh
80 | prometheus --web.enable-lifecycle --config.file=prometheus/prometheus.yml
81 | ```
82 |
83 | Create a .env file in the root directory of Docker Storm and enter in a Postgres URI in this format:
84 | ```sh
85 | POSTGRES_URI = "PostgresURI Here"
86 | ```
87 | All other keys will be asked upon first launch
88 |
89 |
90 |
91 | To start application:
92 | ```sh
93 | npm run electron
94 | OR
95 | npm start
96 | ```
97 |
98 | [↥Back to top](#table-of-contents)
99 | ## If you need to setup Docker Swarm
100 | Docker Swarm Setup (Multipass)
101 |
102 | ## VM Installation using Multipass (Mac OS):
103 | Install multipass (please make sure you have brew installed):
104 | ```sh
105 | brew install --cask multipass
106 | ```
107 |
108 | Create VM's for each worker and manager:
109 | ```sh
110 | multipass launch docker --name manager1
111 | multipass launch docker --name worker1
112 | multipass launch docker --name worker2
113 | ```
114 |
115 | ## Install Node Exporter on each Multipass instance:
116 | The below steps need to be replicated on all multipass instances
117 |
118 | To run commands for your multipass instance prefix each command with
119 | ```sh
120 | multipass exec –-
121 | ```
122 |
123 | Download the latest version of linux prometheus (example below downloads v.1.4.0):
124 | ```sh
125 | multipass exec –- wget https://github.com/prometheus/node_exporter/releases/download/v1.4.0/node_exporter-1.4.0.linux-amd64.tar.gz
126 | ```
127 |
128 | Extract the files:
129 | ```sh
130 | multipass exec –- tar xvfz node_exporter-1.4.0.linux-amd64.tar.gz
131 | ```
132 |
133 | Move the files to /usr/local/bin/:
134 | ```sh
135 | multipass exec –- sudo mv node_exporter-1.4.0.linux-amd64/node_exporter /usr/local/bin/
136 | ```
137 |
138 | Add a node_exporter.service to add a new service:
139 | ```sh
140 | multipass exec –- sudo vi /etc/systemd/system/node_exporter.service
141 | ```
142 | Insert using vim:
143 | ```sh
144 | [Unit]
145 | Description=Node Exporter
146 | After=network.target
147 |
148 | [Service]
149 | User=root
150 | Group=root
151 | Type=simple
152 | ExecStart=/usr/local/bin/node_exporter
153 |
154 | [Install]
155 | WantedBy=multi-user.target
156 | ```
157 |
158 | Reload the Daemon then start node_exporter:
159 | ```sh
160 | multipass exec –- sudo systemctl daemon-reload
161 | multipass exec –- sudo systemctl start node_exporter
162 | ```
163 |
164 | Ensure service has started without issue:
165 | ```sh
166 | multipass exec –- sudo systemctl status node_exporter
167 | ```
168 |
169 | Setup automatic launch on restart:
170 | ```sh
171 | multipass exec –- sudo systemctl enable node_exporter
172 | ```
173 | ## Reveal the Docker Daemon on a manager node (only needs to be done once):
174 | Add/edit the daemon.json:
175 | ```sh
176 | multipass exec –- sudo vi /etc/docker/daemon.json
177 | ```
178 | Insert in vim:
179 | ```sh
180 | {
181 | “metrics-addr”: “0.0.0.0:9323”,
182 | “experimental”: true
183 | }
184 | ```
185 |
186 |
187 |
188 |
189 | [↥Back to top](#table-of-contents)
190 |
191 | ## Contributers
192 |
193 | - [@Kelvin Van](https://github.com/KelvinVan1)
194 | - [@Shay Sheller](https://github.com/shaysheller)
195 | - [@Kevin Tseng](https://github.com/Kevin-J-Tseng)
196 | - [@Jeffrey Lee](https://github.com/jclee8888)
197 |
198 | [↥Back to top](#table-of-contents)
199 |
200 | ## Contributing
201 |
202 | Contributions are always welcome!
203 |
204 | See `CONTRIBUTING.md` for ways to get started.
205 |
206 | Please adhere to this project's `code of conduct` in `CODE_OF_CONDUCT.md`
207 |
208 | [↥Back to top](#table-of-contents)
209 |
--------------------------------------------------------------------------------
/src/client/pages/settings.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import { Job, Target, Role } from '../../types.js';
3 | import {ImageList, TextField, Select, MenuItem, Container, Box, Grid, Button, Typography } from '@mui/material';
4 | import theme from '../theme.jsx';
5 |
6 |
7 |
8 | interface Props {
9 | targetsArr: Target[];
10 | setTargetsArr: React.Dispatch>;
11 | }
12 |
13 | interface Body {
14 | panelTitles: Job[],
15 | expr: string;
16 | panelType: string;
17 | }
18 |
19 | const styles = {
20 | buttonStyles: {
21 | marginLeft: '20px',
22 | marginRight: '20px',
23 | paddingLeft: '20px',
24 | paddingRight: '20px',
25 | border: theme.palette.primary.main,
26 | borderStyle: 'solid',
27 | backgroundColor: theme.palette.primary.main,
28 | '&:hover': {
29 | backgroundColor: 'white',
30 | color: theme.palette.primary.main,
31 |
32 | },
33 | color: 'white'
34 | },
35 |
36 | gridStyles: {
37 | width: '50%',
38 | margin: '0px'
39 | },
40 |
41 | };
42 |
43 |
44 | const Settings = (props : Props) => {
45 | const [password, setPassword] = useState('');
46 | const [newPassword, setNewPassword] = useState('');
47 | const [verifyPassword, setVerifyPassword] = useState('');
48 | const [job, setJob] = useState('');
49 | const [role, setRole] = useState('Manager');
50 | const [ip, setIp] = useState('');
51 | const [ports, setPorts] = useState('');
52 | const [added, setAdded] = useState(false);
53 | const [pwAdded, setPwAdded] = useState(false);
54 |
55 | function changePassword(){
56 | if(newPassword !== verifyPassword){
57 | alert('Both new passwords need to be the same');
58 | }
59 | else{
60 | const body = {password, newPassword};
61 | fetch('/user', {
62 | method: 'PATCH',
63 | headers: {'Content-Type': 'application/json'},
64 | body: JSON.stringify(body),
65 | })
66 | .then((result) => {
67 | if(result.status === 400)
68 | alert('Invalid current password');
69 | else{
70 | setPassword('');
71 | setNewPassword('');
72 | setVerifyPassword('');
73 | setPwAdded(true);
74 | }
75 | });
76 | }
77 | }
78 |
79 | function addTarget() {
80 | const portArr: string[] = ports.split(/[ ,]+/).filter(Boolean);
81 | const ipArr: string[] = [];
82 | portArr.forEach((portElem: string) => {
83 | ipArr.push(`${ip}:${portElem}`);
84 | });
85 |
86 | const obj : Target = {
87 | targets: ipArr,
88 | labels: {
89 | job: job,
90 | role: role
91 | }
92 | };
93 | props.setTargetsArr([...props.targetsArr, obj]);
94 | setAdded(true);
95 |
96 |
97 | // could maybe add type validation here
98 | fetch('/graf/targetsAdd', {
99 | method: 'POST',
100 | headers: {
101 | 'content-type': 'application/json'
102 | },
103 | body: JSON.stringify(obj)
104 | });
105 |
106 | const body: Body = {
107 | panelTitles: [
108 | {job: job, role: role}
109 | ],
110 | panelType: 'gauge',
111 | expr: '100 - (avg(irate(node_cpu_seconds_total{mode=\'idle\', job=}[1m])) * 100)'
112 | };
113 |
114 | fetch('/metric/genPanel', {
115 | method: 'POST',
116 | headers: {
117 | 'content-type': 'application/json',
118 | },
119 | body: JSON.stringify(body)
120 | }).then((data) => data.json())
121 | .then((result) => {
122 | fetch('/graf/', {
123 | method: 'PATCH',
124 | headers: {
125 | 'content-type': 'application/json',
126 | },
127 | body: JSON.stringify(result)
128 | });
129 | });
130 |
131 | setJob('');
132 | setRole('Manager');
133 | setIp('');
134 | setPorts('');
135 | }
136 |
137 |
138 |
139 |
140 | const targetMap = props.targetsArr.map((target) => {
141 | const str = `${target.targets[0]} ${target.labels.job} ${target.labels.role}`;
142 | return (
143 | {`IP Address: ${target.targets[0]}`}
144 | {`Job Name: ${target.labels.job}`}
145 | {`Role: ${target.labels.role}`}
146 | );
147 | });
148 |
149 | const style = {
150 | width: '100px'
151 | };
152 |
153 |
154 | return (
155 |
156 |
157 | Settings
158 |
159 | e.preventDefault()} sx={{justifyItems:'center'}}>
160 |
161 | UPDATE PASSWORD
162 |
163 | setPassword(input.target.value)} />
164 | setNewPassword(input.target.value)} />
165 | setVerifyPassword(input.target.value)} />
166 | changePassword()}>SUBMIT
167 |
168 |
169 | {pwAdded && Changed password!
}
170 |
171 |
172 | e.preventDefault()}>
173 |
174 | ADD A TARGET
175 |
176 | setIp(input.target.value)} />
177 | setPorts(input.target.value)} />
178 | setJob(input.target.value)} />
179 | setRole(input.target.value as Role)}>
180 | Manager
181 | Worker
182 | Daemon
183 | Overall
184 |
185 | addTarget()}>SUBMIT
186 |
187 |
188 |
189 | {added && Added node!
}
190 |
191 |
192 | LIST OF TARGETS:
193 |
195 | {targetMap}
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 | );
207 | };
208 |
209 | export default Settings;
--------------------------------------------------------------------------------
/src/server/controllers/userController.ts:
--------------------------------------------------------------------------------
1 | import bcrypt from 'bcryptjs';
2 | import db from '../models/dockerStormModel.js';
3 | import { ResponseObject } from '../../types.js';
4 |
5 | //Controller interface
6 | interface UserController {
7 | verifyUser: ResponseObject;
8 | createUser: ResponseObject;
9 | encrypt: ResponseObject;
10 | updateUser: ResponseObject;
11 | deleteUser: ResponseObject;
12 | getAllUsers: ResponseObject;
13 | createAdminUser: ResponseObject;
14 | createAdminUserInfo: ResponseObject;
15 | checkEnv: ResponseObject;
16 | }
17 |
18 | //Controller
19 | const userController: UserController = {
20 |
21 | /**
22 | * Method will verify that the user entered the correct credentials using bycrpt's compare
23 | * First we grab the user info then compare that hashed password to the input passsword
24 | */
25 | verifyUser: async (req, res, next) => {
26 | console.log('In verifyUser');
27 |
28 | const { password } = req.body;
29 | const username = req.body.username || req.cookies.username;
30 | const queryStr = 'SELECT * FROM users WHERE username = $1';
31 |
32 | try {
33 | db.query(queryStr, [username])
34 | .then((data) => {
35 | if(data.rows.length === 1){
36 | const validPassword = bcrypt.compareSync(password, data.rows[0].password);
37 | if(validPassword) return next();
38 | else {
39 | return next({
40 | log: 'Error caught in userController.verifyUser',
41 | status: 400,
42 | message: 'Missing username or password in request',
43 | });
44 | }
45 | } else {
46 | return next({
47 | log: 'Error caught in userController.verifyUser',
48 | status: 400,
49 | message: 'Missing username or password in request',
50 | });
51 | }
52 | });
53 | } catch {
54 | return next({
55 | log: 'Error caught in userController.verifyUser',
56 | status: 400,
57 | message: 'Missing username or password in request',
58 | });
59 | }
60 | },
61 |
62 |
63 | /**
64 | * This method will create a new user
65 | * We go ahead and insert a new user into our users table upon creation
66 | */
67 | createUser: async (req, res, next) => {
68 | console.log('In createUser');
69 |
70 | const { username, role } = req.body;
71 |
72 | try {
73 | if(!username || !res.locals.password) {
74 | return next({
75 | log: 'Error caught in userController.createUser',
76 | status: 400,
77 | message: 'Missing username or password in request',
78 | });
79 | }
80 | const queryStr = 'INSERT INTO users (username, password, role) VALUES ($1, $2, $3);';
81 |
82 | db.query(queryStr, [username, res.locals.password, role])
83 | .then(() => {return next();})
84 | .catch((err: Error) => {
85 | return next({
86 | log: 'Error caught in createUser db call',
87 | status: 400,
88 | message: {err: err}
89 | });
90 | });
91 |
92 | } catch (error) {
93 | return next({
94 | log: 'Error caught in userController.createUser',
95 | status: 400,
96 | message: 'Username already taken',
97 | });
98 | }
99 | },
100 |
101 | /**
102 | * This method encrypt's our password using a has of 10 and the password passed into it saving it to res.locals
103 | */
104 | encrypt: async (req, res, next) => {
105 | console.log('In encrypt');
106 | const password = req.body.newPassword || req.body.password;
107 |
108 | const saltFactor = bcrypt.genSaltSync(10);
109 | res.locals.password = bcrypt.hashSync(password, saltFactor);
110 | return next();
111 | },
112 |
113 | /**
114 | * This method updates the user's password with a new hashed password
115 | */
116 | updateUser: (req, res, next) => {
117 | console.log('In updateUser');
118 | const username = req.cookies.username;
119 | const password = res.locals.password;
120 |
121 | const queryString = 'UPDATE users SET password=($1) WHERE username=($2);';
122 |
123 | db.query(queryString, [password, username])
124 | .then(() => next());
125 |
126 | },
127 |
128 | /**
129 | * This method if will delete the user from the users table
130 | */
131 | deleteUser: (req, res, next) => {
132 | console.log('In deleteUser');
133 | const { username } = req.body;
134 |
135 | const queryStr = 'DELETE FROM users WHERE username=($1);';
136 |
137 | db.query(queryStr, [username])
138 | .then(() => {
139 | return next();
140 | })
141 | .catch((err) => {
142 | return next(err);
143 | });
144 | },
145 |
146 |
147 | /**
148 | * This method grabs each user and saves it into res.locals to display later
149 | */
150 | getAllUsers: (req,res,next) => {
151 | console.log('In getAllUsers');
152 | const queryString = 'SELECT * FROM users INNER JOIN users_info ON users.username = users_info.username';
153 | db.query(queryString, [])
154 | .then((result) => {
155 | res.locals.allUsers = result.rows;
156 | return next();
157 | })
158 | .catch((err: Error) => {
159 | return next({
160 | log: 'Error caught in getAllUsers',
161 | status: 400,
162 | message: {err: err}
163 | });
164 | });
165 |
166 | },
167 |
168 | /**
169 | * This method creates the admin user along with org info
170 | */
171 | createAdminUser: async (req, res, next) => {
172 | console.log('In createAdminUser');
173 | const { username, email, organization, jobTitle, password } = req.body;
174 | res.locals.username = username;
175 | res.locals.email = email;
176 | res.locals.organization = organization;
177 | res.locals.jobTitle = jobTitle;
178 |
179 |
180 | try {
181 | if(!username || !password) {
182 | return next({
183 | log: 'Error caught in userController.createAdminUser',
184 | status: 400,
185 | message: 'Missing username or password in request',
186 | });
187 | }
188 | const queryStr = 'INSERT INTO users (username, password, role) VALUES ($1, $2, \'admin\');';
189 |
190 | db.query(queryStr, [username, res.locals.password])
191 | .then(() => {return next();})
192 | .catch((err: Error) => {
193 | return next({
194 | log: 'Error caught in createAdminUser db call',
195 | status: 400,
196 | message: {err: err}
197 | });
198 | });
199 |
200 | } catch (error) {
201 | return next({
202 | log: 'Error caught in userController.createAdminUser',
203 | status: 400,
204 | message: 'Error in createAdminUser',
205 | });
206 | }
207 | },
208 |
209 | /**
210 | * This method populates the additional info for a specific user (email, org, job title)
211 | */
212 | createAdminUserInfo: async (req, res, next) => {
213 | console.log('In createAdminUserInfo');
214 |
215 | try {
216 | const queryStr = 'INSERT INTO users_info (username, email, organization, job_title) VALUES ($1, $2, $3, $4);';
217 |
218 | db.query(queryStr, [res.locals.username, res.locals.email, res.locals.organization, res.locals.jobTitle])
219 | .then(() => {return next();})
220 | .catch((err: Error) => {
221 | return next({
222 | log: 'Error caught in createAdminUser db call',
223 | status: 400,
224 | message: {err: err}
225 | });
226 | });
227 |
228 | } catch (error) {
229 | return next({
230 | log: 'Error caught in userController.createAdminUser',
231 | status: 400,
232 | message: 'Error in createAdminUser',
233 | });
234 | }
235 | },
236 |
237 | /**
238 | * This method sets the res.locals of grafUrl and apiKey
239 | */
240 | checkEnv: (req, res, next) => {
241 | console.log('In checkEnv');
242 |
243 | res.locals.grafUrl = process.env.GRAFANA_URL || '';
244 | res.locals.apiKey = process.env.GRAFANA_API_KEY || '';
245 | return next();
246 | }
247 | };
248 |
249 | export default userController;
--------------------------------------------------------------------------------
/src/client/pages/signup.tsx:
--------------------------------------------------------------------------------
1 | import React, {useState} from 'react';
2 | import { useNavigate } from 'react-router-dom';
3 | import {TextField, Container, Box, Grid, Button } from '@mui/material';
4 | import theme from '../theme.jsx';
5 | import Tooltip from './tooltip.jsx';
6 |
7 |
8 |
9 |
10 | interface Props {
11 | setApiKey: (arg: string) => void;
12 | apiKey: string;
13 | openSignup: boolean;
14 | setOpenSignup: (arg: boolean) => void;
15 | setGrafUrl: (value: string) => void;
16 | grafUrl: string;
17 | }
18 |
19 | interface ResponseObject {
20 | db: string;
21 | key: string;
22 | }
23 |
24 | const urlText = 'Please enter exactly in the form of http://localhost:XXXX/ or http://[IP ADDRESS]/ or http://[URL]/ . Please do not add anything after the final slash';
25 | const apiText = 'You can find your Grafana API key under the configuration gear in your Grafana account.';
26 |
27 |
28 | const Signup = (props: Props) => {
29 | const [usernameSignup, setUsernameSignup] = useState('');
30 | const [passwordSignup, setPasswordSignup] = useState('');
31 | const [verifyPasswordSignup, setVerifyPasswordSignup] = useState('');
32 | const [emailSignup, setEmailSignup] = useState('');
33 | const [organization, setOrganization] = useState('');
34 | const [jobTitle, setJobTitle] = useState('');
35 | const [invalid, setInvalid] = useState(false);
36 | const [signupSuccess, setSignupSuccess] = useState(false);
37 | const [currentApi, setCurrentApi] = useState(props.apiKey);
38 | const [currentGrafUrl, setCurrentGrafUrl] = useState(props.grafUrl);
39 | const navigate = useNavigate();
40 |
41 |
42 | const envSetup = () => {
43 | const body = {
44 | apiKey: currentApi,
45 | grafUrl: currentGrafUrl
46 | };
47 |
48 | props.setApiKey(currentApi);
49 | props.setGrafUrl(currentGrafUrl);
50 |
51 | fetch('/user/env', {
52 | method: 'POST',
53 | headers: {
54 | 'content-type': 'application/json'
55 | },
56 | body: JSON.stringify(body),
57 | });
58 | };
59 |
60 |
61 |
62 | const createAdminUser = async () => {
63 | if(!usernameSignup || !passwordSignup || !verifyPasswordSignup || !emailSignup || !organization || !currentApi || !currentGrafUrl || !jobTitle) {
64 | setInvalid(true);
65 | return;
66 | }
67 |
68 | if(passwordSignup !== verifyPasswordSignup) {
69 | return;
70 | }
71 |
72 |
73 |
74 | const body = {
75 | username: usernameSignup,
76 | password: passwordSignup,
77 | email: emailSignup,
78 | organization: organization,
79 | jobTitle: jobTitle
80 | };
81 |
82 | const result = await fetch('/user/signupAdmin', {
83 | method: 'POST',
84 | headers: {'Content-Type': 'application/json'},
85 | body: JSON.stringify(body),
86 | });
87 |
88 | if(result.status !== 200) {
89 | setInvalid(true);
90 | return;
91 | }
92 |
93 | if(result.status == 200) {
94 | setSignupSuccess(true);
95 | envSetup();
96 | return;
97 | }
98 | };
99 |
100 |
101 |
102 | return (
103 |
104 |
105 |
106 |
107 | {!signupSuccess &&
108 |
109 | event.preventDefault()}
112 | >
113 |
116 |
120 | setUsernameSignup(input.target.value)}
129 |
130 | />
131 |
132 |
136 | setPasswordSignup(input.target.value)}
143 | placeholder="Password"/>
144 |
145 |
149 | setVerifyPasswordSignup(input.target.value)}
156 | placeholder="Type password again"/>
157 |
158 |
159 | setEmailSignup(input.target.value)}
166 | placeholder="Email"/>
167 |
168 |
169 | setOrganization(input.target.value)}
176 | placeholder="Organization"/>
177 |
178 |
182 | setJobTitle(input.target.value)}
189 | placeholder="Job title"/>
190 |
191 | {!props.grafUrl &&
196 |
197 | setCurrentGrafUrl(input.target.value)}
204 | placeholder="Grafana URL"/>
205 |
206 | }
207 | {!props.apiKey &&
212 |
213 | setCurrentApi(input.target.value)}
220 | placeholder="Grafana API key"/>
221 |
222 | }
223 |
228 | { props.setOpenSignup(false); }}>Cancel
231 |
232 |
233 |
238 | createAdminUser()}>Signup
250 |
251 |
252 |
253 | {(passwordSignup && passwordSignup !== verifyPasswordSignup) && Make sure your passwords match!
}
254 | {invalid && Please fill out all fields
}
255 |
256 |
257 |
258 |
259 |
260 | }
261 |
262 | {signupSuccess &&
263 |
264 |
269 | Signup Successful!
270 | { props.setOpenSignup(false); }}>LOGIN
278 |
279 |
280 | }
281 |
282 |
283 |
284 | );
285 | };
286 |
287 | export default Signup;
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | "jsx": "preserve", /* Specify what JSX code is generated. */
17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, z /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "NodeNext", /* Specify what module code is generated. */
29 | "rootDir": "./src", /* Specify the root folder within your source files. */
30 | "moduleResolution": "NodeNext", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "resolveJsonModule": true, /* Enable importing .json files. */
39 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
40 |
41 | /* JavaScript Support */
42 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
43 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
44 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
45 |
46 | /* Emit */
47 | "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
48 | "declarationMap": true, /* Create sourcemaps for d.ts files. */
49 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
50 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
51 | //"outFile": "./dist/", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
52 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
53 | // "removeComments": true, /* Disable emitting comments. */
54 | // "noEmit": true, /* Disable emitting files from a compilation. */
55 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
56 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
57 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
58 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
59 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
61 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
62 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
63 | // "newLine": "crlf", /* Set the newline character for emitting files. */
64 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
65 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
66 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
67 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
68 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
69 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
70 |
71 | /* Interop Constraints */
72 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
73 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
74 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
75 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
76 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
77 |
78 | /* Type Checking */
79 | "strict": true, /* Enable all strict type-checking options. */
80 | "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
81 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
82 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
83 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
84 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
85 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
86 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
87 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
88 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
89 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
90 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
91 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
92 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
93 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
94 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
95 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
96 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
97 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
98 |
99 | /* Completeness */
100 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
101 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
102 | },
103 | "include": ["src/**/*"]
104 | }
105 |
--------------------------------------------------------------------------------
/grafana/customConfig.ini:
--------------------------------------------------------------------------------
1 | ##################### Grafana Configuration Example #####################
2 | #
3 | # Everything has defaults so you only need to uncomment things you want to
4 | # change
5 |
6 | # possible values : production, development
7 | ;app_mode = production
8 |
9 | # instance name, defaults to HOSTNAME environment variable value or hostname if HOSTNAME var is empty
10 | ;instance_name = ${HOSTNAME}
11 |
12 | # force migration will run migrations that might cause dataloss
13 | ;force_migration = false
14 |
15 | #################################### Paths ####################################
16 | [paths]
17 | # Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
18 | ;data = /var/lib/grafana
19 |
20 | # Temporary files in `data` directory older than given duration will be removed
21 | ;temp_data_lifetime = 24h
22 |
23 | # Directory where grafana can store logs
24 | ;logs = /var/log/grafana
25 |
26 | # Directory where grafana will automatically scan and look for plugins
27 | ;plugins = /var/lib/grafana/plugins
28 |
29 | # folder that contains provisioning config files that grafana will apply on startup and while running.
30 | ;provisioning = conf/provisioning
31 |
32 | #################################### Server ####################################
33 | [server]
34 | # Protocol (http, https, h2, socket)
35 | ;protocol = http
36 |
37 | # The ip address to bind to, empty will bind to all interfaces
38 | ;http_addr =
39 |
40 | # The http port to use
41 | ;http_port = 3000
42 |
43 | # The public facing domain name used to access grafana from a browser
44 | ;domain = localhost
45 |
46 | # Redirect to correct domain if host header does not match domain
47 | # Prevents DNS rebinding attacks
48 | ;enforce_domain = false
49 |
50 | # The full public facing url you use in browser, used for redirects and emails
51 | # If you use reverse proxy and sub path specify full url (with sub path)
52 | ;root_url = %(protocol)s://%(domain)s:%(http_port)s/
53 |
54 | # Serve Grafana from subpath specified in `root_url` setting. By default it is set to `false` for compatibility reasons.
55 | ;serve_from_sub_path = false
56 |
57 | # Log web requests
58 | ;router_logging = false
59 |
60 | # the path relative working path
61 | ;static_root_path = public
62 |
63 | # enable gzip
64 | ;enable_gzip = false
65 |
66 | # https certs & key file
67 | ;cert_file =
68 | ;cert_key =
69 |
70 | # Unix socket path
71 | ;socket =
72 |
73 | # CDN Url
74 | ;cdn_url =
75 |
76 | # Sets the maximum time using a duration format (5s/5m/5ms) before timing out read of an incoming request and closing idle connections.
77 | # `0` means there is no timeout for reading the request.
78 | ;read_timeout = 0
79 |
80 | #################################### Database ####################################
81 | [database]
82 | # You can configure the database connection by specifying type, host, name, user and password
83 | # as separate properties or as on string using the url properties.
84 |
85 | # Either "mysql", "postgres" or "sqlite3", it's your choice
86 | ;type = sqlite3
87 | ;host = 127.0.0.1:3306
88 | ;name = grafana
89 | ;user = root
90 | # If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
91 | ;password =
92 |
93 | # Use either URL or the previous fields to configure the database
94 | # Example: mysql://user:secret@host:port/database
95 | ;url =
96 |
97 | # For "postgres" only, either "disable", "require" or "verify-full"
98 | ;ssl_mode = disable
99 |
100 | # Database drivers may support different transaction isolation levels.
101 | # Currently, only "mysql" driver supports isolation levels.
102 | # If the value is empty - driver's default isolation level is applied.
103 | # For "mysql" use "READ-UNCOMMITTED", "READ-COMMITTED", "REPEATABLE-READ" or "SERIALIZABLE".
104 | ;isolation_level =
105 |
106 | ;ca_cert_path =
107 | ;client_key_path =
108 | ;client_cert_path =
109 | ;server_cert_name =
110 |
111 | # For "sqlite3" only, path relative to data_path setting
112 | ;path = grafana.db
113 |
114 | # Max idle conn setting default is 2
115 | ;max_idle_conn = 2
116 |
117 | # Max conn setting default is 0 (mean not set)
118 | ;max_open_conn =
119 |
120 | # Connection Max Lifetime default is 14400 (means 14400 seconds or 4 hours)
121 | ;conn_max_lifetime = 14400
122 |
123 | # Set to true to log the sql calls and execution times.
124 | ;log_queries =
125 |
126 | # For "sqlite3" only. cache mode setting used for connecting to the database. (private, shared)
127 | ;cache_mode = private
128 |
129 | # For "mysql" only if migrationLocking feature toggle is set. How many seconds to wait before failing to lock the database for the migrations, default is 0.
130 | ;locking_attempt_timeout_sec = 0
131 |
132 | ################################### Data sources #########################
133 | [datasources]
134 | # Upper limit of data sources that Grafana will return. This limit is a temporary configuration and it will be deprecated when pagination will be introduced on the list data sources API.
135 | ;datasource_limit = 5000
136 |
137 | #################################### Cache server #############################
138 | [remote_cache]
139 | # Either "redis", "memcached" or "database" default is "database"
140 | ;type = database
141 |
142 | # cache connectionstring options
143 | # database: will use Grafana primary database.
144 | # redis: config like redis server e.g. `addr=127.0.0.1:6379,pool_size=100,db=0,ssl=false`. Only addr is required. ssl may be 'true', 'false', or 'insecure'.
145 | # memcache: 127.0.0.1:11211
146 | ;connstr =
147 |
148 | #################################### Data proxy ###########################
149 | [dataproxy]
150 |
151 | # This enables data proxy logging, default is false
152 | ;logging = false
153 |
154 | # How long the data proxy waits to read the headers of the response before timing out, default is 30 seconds.
155 | # This setting also applies to core backend HTTP data sources where query requests use an HTTP client with timeout set.
156 | ;timeout = 30
157 |
158 | # How long the data proxy waits to establish a TCP connection before timing out, default is 10 seconds.
159 | ;dialTimeout = 10
160 |
161 | # How many seconds the data proxy waits before sending a keepalive probe request.
162 | ;keep_alive_seconds = 30
163 |
164 | # How many seconds the data proxy waits for a successful TLS Handshake before timing out.
165 | ;tls_handshake_timeout_seconds = 10
166 |
167 | # How many seconds the data proxy will wait for a server's first response headers after
168 | # fully writing the request headers if the request has an "Expect: 100-continue"
169 | # header. A value of 0 will result in the body being sent immediately, without
170 | # waiting for the server to approve.
171 | ;expect_continue_timeout_seconds = 1
172 |
173 | # Optionally limits the total number of connections per host, including connections in the dialing,
174 | # active, and idle states. On limit violation, dials will block.
175 | # A value of zero (0) means no limit.
176 | ;max_conns_per_host = 0
177 |
178 | # The maximum number of idle connections that Grafana will keep alive.
179 | ;max_idle_connections = 100
180 |
181 | # How many seconds the data proxy keeps an idle connection open before timing out.
182 | ;idle_conn_timeout_seconds = 90
183 |
184 | # If enabled and user is not anonymous, data proxy will add X-Grafana-User header with username into the request, default is false.
185 | ;send_user_header = false
186 |
187 | # Limit the amount of bytes that will be read/accepted from responses of outgoing HTTP requests.
188 | ;response_limit = 0
189 |
190 | # Limits the number of rows that Grafana will process from SQL data sources.
191 | ;row_limit = 1000000
192 |
193 | #################################### Analytics ####################################
194 | [analytics]
195 | # Server reporting, sends usage counters to stats.grafana.org every 24 hours.
196 | # No ip addresses are being tracked, only simple counters to track
197 | # running instances, dashboard and error counts. It is very helpful to us.
198 | # Change this option to false to disable reporting.
199 | ;reporting_enabled = true
200 |
201 | # The name of the distributor of the Grafana instance. Ex hosted-grafana, grafana-labs
202 | ;reporting_distributor = grafana-labs
203 |
204 | # Set to false to disable all checks to https://grafana.com
205 | # for new versions of grafana. The check is used
206 | # in some UI views to notify that a grafana update exists.
207 | # This option does not cause any auto updates, nor send any information
208 | # only a GET request to https://raw.githubusercontent.com/grafana/grafana/main/latest.json to get the latest version.
209 | ;check_for_updates = true
210 |
211 | # Set to false to disable all checks to https://grafana.com
212 | # for new versions of plugins. The check is used
213 | # in some UI views to notify that a plugin update exists.
214 | # This option does not cause any auto updates, nor send any information
215 | # only a GET request to https://grafana.com to get the latest versions.
216 | ;check_for_plugin_updates = true
217 |
218 | # Google Analytics universal tracking code, only enabled if you specify an id here
219 | ;google_analytics_ua_id =
220 |
221 | # Google Analytics 4 tracking code, only enabled if you specify an id here
222 | ;google_analytics_4_id =
223 |
224 | # Google Tag Manager ID, only enabled if you specify an id here
225 | ;google_tag_manager_id =
226 |
227 | # Rudderstack write key, enabled only if rudderstack_data_plane_url is also set
228 | ;rudderstack_write_key =
229 |
230 | # Rudderstack data plane url, enabled only if rudderstack_write_key is also set
231 | ;rudderstack_data_plane_url =
232 |
233 | # Rudderstack SDK url, optional, only valid if rudderstack_write_key and rudderstack_data_plane_url is also set
234 | ;rudderstack_sdk_url =
235 |
236 | # Rudderstack Config url, optional, used by Rudderstack SDK to fetch source config
237 | ;rudderstack_config_url =
238 |
239 | # Controls if the UI contains any links to user feedback forms
240 | ;feedback_links_enabled = true
241 |
242 | #################################### Security ####################################
243 | [security]
244 | # disable creation of admin user on first start of grafana
245 | ;disable_initial_admin_creation = false
246 |
247 | # default admin user, created on startup
248 | ;admin_user = admin
249 |
250 | # default admin password, can be changed before first start of grafana, or in profile settings
251 | ;admin_password = admin
252 |
253 | # default admin email, created on startup
254 | ;admin_email = admin@localhost
255 |
256 | # used for signing
257 | ;secret_key = SW2YcwTIb9zpOOhoPsMm
258 |
259 | # current key provider used for envelope encryption, default to static value specified by secret_key
260 | ;encryption_provider = secretKey.v1
261 |
262 | # list of configured key providers, space separated (Enterprise only): e.g., awskms.v1 azurekv.v1
263 | ;available_encryption_providers =
264 |
265 | # disable gravatar profile images
266 | ;disable_gravatar = false
267 |
268 | # data source proxy whitelist (ip_or_domain:port separated by spaces)
269 | ;data_source_proxy_whitelist =
270 |
271 | # disable protection against brute force login attempts
272 | ;disable_brute_force_login_protection = false
273 |
274 | # set to true if you host Grafana behind HTTPS. default is false.
275 | ;cookie_secure = false
276 |
277 | # set cookie SameSite attribute. defaults to `lax`. can be set to "lax", "strict", "none" and "disabled"
278 | ;cookie_samesite = lax
279 |
280 | # set to true if you want to allow browsers to render Grafana in a ,