Skip to content

Commit

Permalink
Demo UI refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
zseta authored Feb 3, 2025
2 parents 478bfdb + e2ce994 commit bd25f57
Show file tree
Hide file tree
Showing 53 changed files with 6,056 additions and 6 deletions.
104 changes: 104 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
from flask import Flask, send_from_directory, abort
from flask_socketio import SocketIO
from flask_cors import CORS
import os
import subprocess
import configparser
import json


app = Flask(__name__,
static_folder='dist',
static_url_path='')
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="http://localhost:5173")

env = os.environ.copy()
env["PYTHONUNBUFFERED"] = "1"
env["ANSIBLE_FORCE_COLOR"] = "1"

program_cwd = os.path.dirname(os.path.abspath(__file__))
terraform_data_folder = os.path.join(program_cwd, "frontend/public/data")

with open(terraform_data_folder + "/terraform-data.json", 'r') as file:
tf_data = json.load(file)

ansible_folder = os.path.join(program_cwd, f"{tf_data['demo']}/ansible")
data_folder = os.path.join(program_cwd, "frontend/public/data")

@app.route("/")
def index():
try:
return send_from_directory(app.static_folder, 'index.html')
except FileNotFoundError:
abort(404)
except Exception as e:
print(f"An error occurred: {e}")
return f"Error: {str(e)}", 500

@app.route("/data/<path:filename>")
def serve_data(filename):
try:
return send_from_directory(data_folder, filename)
except FileNotFoundError:
abort(404)
except Exception as e:
print(f"An error occurred while serving data: {e}")
return f"Error: {str(e)}", 500

# Global process variable
globals()["process"] = None

def run_ansible_playbook(playbook_path):
playbook_cmd = ["ansible-playbook", playbook_path]
process = subprocess.Popen(playbook_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=ansible_folder)
for line in process.stdout:
socketio.emit("playbook_output", {"output": line})
socketio.sleep(0)
process.wait()

@socketio.on("original_cluster")
def handle_original_cluster():
run_ansible_playbook(ansible_folder + "/1_original_cluster.yml")

@socketio.on("sample_data")
def handle_sample_data():
run_ansible_playbook(ansible_folder + "/2_restore_snapshot.yml")

@socketio.on("start_stress")
def handle_start_stress():
run_ansible_playbook(ansible_folder + "/3_stress.yml")

@socketio.on("scale_out")
def handle_scale_out():
run_ansible_playbook(ansible_folder + "/4_scale_out.yml")

@socketio.on("stop_stress")
def handle_stop_stress():
run_ansible_playbook(ansible_folder + "/5_stop_stress.yml")

@socketio.on("scale_in")
def handle_scale_in():
run_ansible_playbook(ansible_folder + "/6_scale_in.yml")


def parse_ansible_inventory(inventory_file):
config = configparser.ConfigParser(allow_no_value=True)
config.optionxform = str # Preserve case sensitivity

# Read the inventory file
config.read(inventory_file)

inventory = {}
for section in config.sections():
hosts = {}
for item in config.items(section):
hostname, *variables = item[0].split()
host_vars = dict(var.split('=') for var in variables)
hosts[hostname] = host_vars
inventory[section] = hosts

return inventory

if __name__ == "__main__":
socketio.run(app, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=True)
16 changes: 16 additions & 0 deletions frontend/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# top-most EditorConfig file
root = true

# LF newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

# charset
[*.{js,ts,tsx}]
charset = utf-8

# indents
[*.{js,ts,tsx}]
indent_style = space
indent_size = 2
22 changes: 22 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
5 changes: 5 additions & 0 deletions frontend/.husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
cd tablets-scaling/frontend

npm run lint-staged
npm run build
git add dist
1 change: 1 addition & 0 deletions frontend/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock.json
13 changes: 13 additions & 0 deletions frontend/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"trailingComma": "es5",
"tabWidth": 2,
"useTabs": false,
"printWidth": 80,
"semi": true,
"singleQuote": true,
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always",
"endOfLine": "lf",
"singleAttributePerLine": true
}
32 changes: 32 additions & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Tablets Scaling Demo App

### Setting up the frontend development environment

1. Open this directory (/tablets-scaling/frontend) in your editor and open the Git repository in the parent directory when prompted.

2. Install dependencies
`npm install`

3. Set the TypeScript version
Ensure that you're using the project's TypeScript version rather than your editor's. If you're not using VS Code, please see your editor's documentation. If using VS Code:
a. Open any .ts or .tsx file
b. Use Cmd+Shift+P (Mac) or Ctrl+Shift+P (Win) to open the Preferences search bar
c. Type "Select TypeScript" and press Enter
d. Select "Use Workspace Version"

4. Run the dev server and follow the link in the console output to the [dev server URL]('http://localhost:5173')
`npm run dev`

### Communicating with the Flask app

The frontend communicates with the backend via Websocket. These connection attempts will respond with `500` errors if the backend isn't running.

To set up and run the backend, follow step 4. in tablets-scaling/README.md, and keep the backend running while the Vite dev server is running.

Note: if you open the backend dev server at https://localhost:5000 and your frontend changes aren't present, then you'll need to `npm build` and refresh the backend server, as it serves build artifacts in tablets-scaling/frontend/dist.

### Committing

Because the backend server reads from /frontend/dist, we build on each commit and commit the changes in /frontend/dist. This is handled automatically in the pre-commit hook, so be careful about committing with the `--no-verify` or `-n` flag.

It might be better to move this to a GitHub Action that checks for changes in /src and /public before performing a build, but this is okay for now.
33 changes: 33 additions & 0 deletions frontend/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';

export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.strictTypeChecked],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
parser: tseslint.parser,
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.url,
},
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
);
22 changes: 22 additions & 0 deletions frontend/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>ScyllaDB Demo</title>
</head>

<body>
<div
id="root"
class="app-body"
></div>
<script
type="module"
src="/src/main.tsx"
></script>
</body>
</html>
7 changes: 7 additions & 0 deletions frontend/lint-staged.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default {
// Run eslint
'**/*.ts?(x)':
'eslint . --report-unused-disable-directives --ignore-pattern dist',
// Format files with Prettier, ignore unknown extensions
'*.{ts,tsx,js,jsx,json,html,css,md}': 'prettier --write --ignore-unknown',
};
Loading

0 comments on commit bd25f57

Please sign in to comment.