From 6518461906cb30326349f535ee615f88884e33e9 Mon Sep 17 00:00:00 2001 From: Matthijs Bijman Date: Tue, 24 Jan 2017 11:58:44 +0100 Subject: Initial commit --- README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..1eccbe6f --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# OpenDC Simulator -- cgit v1.2.3 From 86a50a4f6df9ece982743a3b7ca510846d248909 Mon Sep 17 00:00:00 2001 From: leonoverweel Date: Tue, 24 Jan 2017 12:05:15 +0100 Subject: Initial commit --- .gitignore | 14 + main.py | 148 ++++++++++ opendc/__init__.py | 0 opendc/api/__init__.py | 0 opendc/api/v1/__init__.py | 0 opendc/api/v1/room-types/__init__.py | 0 opendc/api/v1/room-types/endpoint.py | 17 ++ opendc/api/v1/room-types/name/__init__.py | 0 .../v1/room-types/name/allowed-objects/__init__.py | 0 .../v1/room-types/name/allowed-objects/endpoint.py | 30 ++ opendc/api/v1/schedulers/__init__.py | 0 opendc/api/v1/schedulers/endpoint.py | 17 ++ opendc/api/v1/simulations/__init__.py | 0 opendc/api/v1/simulations/endpoint.py | 86 ++++++ opendc/api/v1/simulations/simulationId/__init__.py | 0 .../simulationId/authorizations/__init__.py | 0 .../simulationId/authorizations/endpoint.py | 43 +++ .../simulationId/authorizations/userId/__init__.py | 0 .../simulationId/authorizations/userId/endpoint.py | 208 +++++++++++++ .../simulationId/datacenters/__init__.py | 0 .../datacenters/datacenterId/__init__.py | 0 .../datacenters/datacenterId/endpoint.py | 43 +++ .../datacenters/datacenterId/rooms/__init__.py | 0 .../datacenters/datacenterId/rooms/endpoint.py | 111 +++++++ .../datacenterId/rooms/roomId/__init__.py | 0 .../datacenterId/rooms/roomId/endpoint.py | 140 +++++++++ .../datacenterId/rooms/roomId/tiles/__init__.py | 0 .../datacenterId/rooms/roomId/tiles/endpoint.py | 123 ++++++++ .../rooms/roomId/tiles/tileId/__init__.py | 0 .../rooms/roomId/tiles/tileId/endpoint.py | 89 ++++++ .../rooms/roomId/tiles/tileId/rack/__init__.py | 0 .../rooms/roomId/tiles/tileId/rack/endpoint.py | 245 +++++++++++++++ .../roomId/tiles/tileId/rack/machines/__init__.py | 0 .../roomId/tiles/tileId/rack/machines/endpoint.py | 122 ++++++++ .../tileId/rack/machines/position/__init__.py | 0 .../tileId/rack/machines/position/endpoint.py | 170 +++++++++++ .../simulationId/datacenters/endpoint.py | 60 ++++ opendc/api/v1/simulations/simulationId/endpoint.py | 132 +++++++++ .../simulationId/experiments/__init__.py | 0 .../simulationId/experiments/endpoint.py | 114 +++++++ .../experiments/experimentId/__init__.py | 0 .../experiments/experimentId/endpoint.py | 138 +++++++++ .../experimentId/last-simulated-tick/__init__.py | 0 .../experimentId/last-simulated-tick/endpoint.py | 43 +++ .../experimentId/machine-states/__init__.py | 0 .../experimentId/machine-states/endpoint.py | 51 ++++ .../experimentId/rack-states/__init__.py | 0 .../experimentId/rack-states/endpoint.py | 51 ++++ .../experimentId/room-states/__init__.py | 0 .../experimentId/room-states/endpoint.py | 51 ++++ .../experimentId/statistics/__init__.py | 0 .../statistics/task-durations/__init__.py | 0 .../statistics/task-durations/endpoint.py | 44 +++ .../experimentId/task-states/__init__.py | 0 .../experimentId/task-states/endpoint.py | 51 ++++ .../v1/simulations/simulationId/paths/__init__.py | 0 .../v1/simulations/simulationId/paths/endpoint.py | 42 +++ .../simulationId/paths/pathId/__init__.py | 0 .../simulationId/paths/pathId/branches/__init__.py | 0 .../simulationId/paths/pathId/branches/endpoint.py | 166 +++++++++++ .../simulationId/paths/pathId/endpoint.py | 44 +++ .../simulationId/paths/pathId/sections/__init__.py | 0 .../simulationId/paths/pathId/sections/endpoint.py | 43 +++ .../paths/pathId/sections/sectionId/__init__.py | 0 .../paths/pathId/sections/sectionId/endpoint.py | 44 +++ opendc/api/v1/specifications/__init__.py | 0 opendc/api/v1/specifications/cpus/__init__.py | 0 opendc/api/v1/specifications/cpus/endpoint.py | 17 ++ opendc/api/v1/specifications/cpus/id/__init__.py | 0 opendc/api/v1/specifications/cpus/id/endpoint.py | 33 +++ .../v1/specifications/failure-models/__init__.py | 0 .../v1/specifications/failure-models/endpoint.py | 17 ++ .../specifications/failure-models/id/__init__.py | 0 .../specifications/failure-models/id/endpoint.py | 33 +++ opendc/api/v1/specifications/gpus/__init__.py | 0 opendc/api/v1/specifications/gpus/endpoint.py | 17 ++ opendc/api/v1/specifications/gpus/id/__init__.py | 0 opendc/api/v1/specifications/gpus/id/endpoint.py | 33 +++ opendc/api/v1/specifications/memories/__init__.py | 0 opendc/api/v1/specifications/memories/endpoint.py | 17 ++ .../api/v1/specifications/memories/id/__init__.py | 0 .../api/v1/specifications/memories/id/endpoint.py | 33 +++ opendc/api/v1/specifications/storages/__init__.py | 0 opendc/api/v1/specifications/storages/endpoint.py | 17 ++ .../api/v1/specifications/storages/id/__init__.py | 0 .../api/v1/specifications/storages/id/endpoint.py | 33 +++ opendc/api/v1/traces/__init__.py | 0 opendc/api/v1/traces/endpoint.py | 17 ++ opendc/api/v1/traces/traceId/__init__.py | 0 opendc/api/v1/traces/traceId/endpoint.py | 33 +++ opendc/api/v1/traces/traceId/tasks/__init__.py | 0 opendc/api/v1/traces/traceId/tasks/endpoint.py | 36 +++ opendc/api/v1/users/__init__.py | 0 opendc/api/v1/users/endpoint.py | 80 +++++ opendc/api/v1/users/userId/__init__.py | 0 .../api/v1/users/userId/authorizations/__init__.py | 0 .../api/v1/users/userId/authorizations/endpoint.py | 41 +++ opendc/api/v1/users/userId/endpoint.py | 121 ++++++++ opendc/models/__init__.py | 0 opendc/models/allowed_object.py | 27 ++ opendc/models/authorization.py | 53 ++++ opendc/models/cpu.py | 41 +++ opendc/models/datacenter.py | 36 +++ opendc/models/experiment.py | 51 ++++ opendc/models/failure_model.py | 23 ++ opendc/models/gpu.py | 41 +++ opendc/models/machine.py | 129 ++++++++ opendc/models/machine_state.py | 79 +++++ opendc/models/memory.py | 41 +++ opendc/models/model.py | 328 +++++++++++++++++++++ opendc/models/object.py | 20 ++ opendc/models/path.py | 35 +++ opendc/models/queued_experiment.py | 15 + opendc/models/rack.py | 61 ++++ opendc/models/rack_state.py | 74 +++++ opendc/models/room.py | 34 +++ opendc/models/room_state.py | 82 ++++++ opendc/models/room_type.py | 21 ++ opendc/models/scheduler.py | 18 ++ opendc/models/section.py | 32 ++ opendc/models/simulation.py | 41 +++ opendc/models/storage.py | 41 +++ opendc/models/task.py | 22 ++ opendc/models/task_duration.py | 47 +++ opendc/models/task_state.py | 49 +++ opendc/models/tile.py | 47 +++ opendc/models/trace.py | 19 ++ opendc/models/user.py | 49 +++ opendc/util/__init__.py | 0 opendc/util/database.py | 82 ++++++ opendc/util/exceptions.py | 61 ++++ opendc/util/parameter_checker.py | 90 ++++++ opendc/util/rest.py | 137 +++++++++ static/index.html | 55 ++++ 134 files changed, 5239 insertions(+) create mode 100644 .gitignore create mode 100644 main.py create mode 100644 opendc/__init__.py create mode 100644 opendc/api/__init__.py create mode 100644 opendc/api/v1/__init__.py create mode 100644 opendc/api/v1/room-types/__init__.py create mode 100644 opendc/api/v1/room-types/endpoint.py create mode 100644 opendc/api/v1/room-types/name/__init__.py create mode 100644 opendc/api/v1/room-types/name/allowed-objects/__init__.py create mode 100644 opendc/api/v1/room-types/name/allowed-objects/endpoint.py create mode 100644 opendc/api/v1/schedulers/__init__.py create mode 100644 opendc/api/v1/schedulers/endpoint.py create mode 100644 opendc/api/v1/simulations/__init__.py create mode 100644 opendc/api/v1/simulations/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/authorizations/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/authorizations/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/authorizations/userId/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/authorizations/userId/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/position/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/position/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/datacenters/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/last-simulated-tick/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/last-simulated-tick/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/machine-states/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/machine-states/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/rack-states/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/rack-states/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/room-states/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/room-states/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/task-durations/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/task-durations/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/task-states/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/experiments/experimentId/task-states/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/pathId/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/pathId/branches/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/pathId/branches/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/pathId/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/pathId/sections/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/pathId/sections/endpoint.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/pathId/sections/sectionId/__init__.py create mode 100644 opendc/api/v1/simulations/simulationId/paths/pathId/sections/sectionId/endpoint.py create mode 100644 opendc/api/v1/specifications/__init__.py create mode 100644 opendc/api/v1/specifications/cpus/__init__.py create mode 100644 opendc/api/v1/specifications/cpus/endpoint.py create mode 100644 opendc/api/v1/specifications/cpus/id/__init__.py create mode 100644 opendc/api/v1/specifications/cpus/id/endpoint.py create mode 100644 opendc/api/v1/specifications/failure-models/__init__.py create mode 100644 opendc/api/v1/specifications/failure-models/endpoint.py create mode 100644 opendc/api/v1/specifications/failure-models/id/__init__.py create mode 100644 opendc/api/v1/specifications/failure-models/id/endpoint.py create mode 100644 opendc/api/v1/specifications/gpus/__init__.py create mode 100644 opendc/api/v1/specifications/gpus/endpoint.py create mode 100644 opendc/api/v1/specifications/gpus/id/__init__.py create mode 100644 opendc/api/v1/specifications/gpus/id/endpoint.py create mode 100644 opendc/api/v1/specifications/memories/__init__.py create mode 100644 opendc/api/v1/specifications/memories/endpoint.py create mode 100644 opendc/api/v1/specifications/memories/id/__init__.py create mode 100644 opendc/api/v1/specifications/memories/id/endpoint.py create mode 100644 opendc/api/v1/specifications/storages/__init__.py create mode 100644 opendc/api/v1/specifications/storages/endpoint.py create mode 100644 opendc/api/v1/specifications/storages/id/__init__.py create mode 100644 opendc/api/v1/specifications/storages/id/endpoint.py create mode 100644 opendc/api/v1/traces/__init__.py create mode 100644 opendc/api/v1/traces/endpoint.py create mode 100644 opendc/api/v1/traces/traceId/__init__.py create mode 100644 opendc/api/v1/traces/traceId/endpoint.py create mode 100644 opendc/api/v1/traces/traceId/tasks/__init__.py create mode 100644 opendc/api/v1/traces/traceId/tasks/endpoint.py create mode 100644 opendc/api/v1/users/__init__.py create mode 100644 opendc/api/v1/users/endpoint.py create mode 100644 opendc/api/v1/users/userId/__init__.py create mode 100644 opendc/api/v1/users/userId/authorizations/__init__.py create mode 100644 opendc/api/v1/users/userId/authorizations/endpoint.py create mode 100644 opendc/api/v1/users/userId/endpoint.py create mode 100644 opendc/models/__init__.py create mode 100644 opendc/models/allowed_object.py create mode 100644 opendc/models/authorization.py create mode 100644 opendc/models/cpu.py create mode 100644 opendc/models/datacenter.py create mode 100644 opendc/models/experiment.py create mode 100644 opendc/models/failure_model.py create mode 100644 opendc/models/gpu.py create mode 100644 opendc/models/machine.py create mode 100644 opendc/models/machine_state.py create mode 100644 opendc/models/memory.py create mode 100644 opendc/models/model.py create mode 100644 opendc/models/object.py create mode 100644 opendc/models/path.py create mode 100644 opendc/models/queued_experiment.py create mode 100644 opendc/models/rack.py create mode 100644 opendc/models/rack_state.py create mode 100644 opendc/models/room.py create mode 100644 opendc/models/room_state.py create mode 100644 opendc/models/room_type.py create mode 100644 opendc/models/scheduler.py create mode 100644 opendc/models/section.py create mode 100644 opendc/models/simulation.py create mode 100644 opendc/models/storage.py create mode 100644 opendc/models/task.py create mode 100644 opendc/models/task_duration.py create mode 100644 opendc/models/task_state.py create mode 100644 opendc/models/tile.py create mode 100644 opendc/models/trace.py create mode 100644 opendc/models/user.py create mode 100644 opendc/util/__init__.py create mode 100644 opendc/util/database.py create mode 100644 opendc/util/exceptions.py create mode 100644 opendc/util/parameter_checker.py create mode 100644 opendc/util/rest.py create mode 100644 static/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..7abc763b --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.DS_Store +*.pyc +*.pyo +venv +venv* +dist +build +*.egg +*.egg-info +_mailinglist +.tox +.cache/ +.idea/ +config/ diff --git a/main.py b/main.py new file mode 100644 index 00000000..67ff72ac --- /dev/null +++ b/main.py @@ -0,0 +1,148 @@ +#!/var/www/opendc.ewi.tudelft.nl/web-server/venv/bin/python + +import json +import os +import sys +import traceback + +from flask import Flask, abort, request, send_from_directory, session, jsonify +import flask_socketio +from oauth2client import client, crypt + +from opendc.models.user import User +from opendc.util import exceptions, rest + +# Get keys from config file +with open('/var/www/opendc.ewi.tudelft.nl/web-server/config/keys.json') as file: + KEYS = json.load(file) + +STATIC_ROOT = os.path.join(KEYS['ROOT_DIR'], 'static', 'build') + +FLASK_CORE_APP = Flask(__name__, static_url_path='') +FLASK_CORE_APP.config['SECREY_KEY'] = KEYS['FLASK_SECRET'] + +SOCKET_IO_CORE = flask_socketio.SocketIO(FLASK_CORE_APP) + +@FLASK_CORE_APP.errorhandler(404) +def page_not_found(e): + return send_from_directory(STATIC_ROOT, '404.html') + +@FLASK_CORE_APP.route('/') +def serve_splash(): + """Serve the splash page on /""" + + return send_from_directory(STATIC_ROOT, 'index.html') + +@FLASK_CORE_APP.route('/app') +def serve_app(): + """Serve the app on /app.""" + + return send_from_directory(STATIC_ROOT, 'app.html') + +@FLASK_CORE_APP.route('/profile') +def serve_profile(): + """Serve profile page.""" + + return send_from_directory(STATIC_ROOT, 'profile.html') + +@FLASK_CORE_APP.route('/projects') +def serve_projects(): + """Serve the projects page.""" + + return send_from_directory(STATIC_ROOT, 'projects.html') + +@FLASK_CORE_APP.route('/web-server-test') +def serve_web_server_test(): + """Serve the web server test.""" + + return send_from_directory(os.path.join(KEYS['ROOT_DIR'], 'web-server', 'static'), 'index.html') + +@FLASK_CORE_APP.route('//') +def serve_static(folder, filepath): + """Serve static files from the build directory""" + + if not folder in ['bower_components', 'img', 'scripts', 'styles']: + abort(404) + + return send_from_directory(os.path.join(KEYS['ROOT_DIR'], 'static', 'build', folder), filepath) + +@FLASK_CORE_APP.route('/tokensignin', methods=['POST']) +def sign_in(): + """Authenticate a user with Google sign in""" + + try: + token = request.form['idtoken'] + except KeyError: + return 'No idtoken provided', 401 + + try: + idinfo = client.verify_id_token(token, KEYS['OAUTH_CLIENT_ID']) + + if idinfo['aud'] != KEYS['OAUTH_CLIENT_ID']: + raise crypt.AppIdentityError('Unrecognized client.') + + if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: + raise crypt.AppIdentityError('Wrong issuer.') + + except crypt.AppIdentityError, e: + return 'Did not successfully authenticate' + + user = User.from_google_id(idinfo['sub']) + + data = { + 'isNewUser': not user.exists() + } + + if user.exists(): + data['userId'] = user.id + + return jsonify(**data) + +@SOCKET_IO_CORE.on('request') +def receive_message(message): + """"Receive a SocketIO request""" + + try: + request = rest.Request(message) + response = request.process() + + flask_socketio.emit('response', response.to_JSON(), json=True) + + print 'Socket: {} to `/{}` resulted in {}: {}'.format( + request.method, + request.path, + response.status['code'], + response.status['description'] + ) + + return + + except exceptions.AuthorizationTokenError as e: + response = rest.Response(401, 'Authorization error') + response.id = message['id'] + + flask_socketio.emit('response', response.to_JSON(), json=True) + + except exceptions.RequestInitializationError as e: + response = rest.Response(400, e.message) + response.id = message['id'] + + flask_socketio.emit('response', response.to_JSON(), json=True) + + except Exception as e: + response = rest.Response(500, 'Internal server error') + response.id = message['id'] + + flask_socketio.emit('response', response.to_JSON(), json=True) + traceback.print_exc() + + print 'Socket: {} to `{}` resulted in {}: {}'.format( + message['method'], + message['path'], + response.status['code'], + response.status['description'] + ) + + +SOCKET_IO_CORE.run(FLASK_CORE_APP, port=8081) + diff --git a/opendc/__init__.py b/opendc/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/__init__.py b/opendc/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/__init__.py b/opendc/api/v1/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/room-types/__init__.py b/opendc/api/v1/room-types/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/room-types/endpoint.py b/opendc/api/v1/room-types/endpoint.py new file mode 100644 index 00000000..2030b538 --- /dev/null +++ b/opendc/api/v1/room-types/endpoint.py @@ -0,0 +1,17 @@ +from opendc.models.room_type import RoomType +from opendc.util.rest import Response + +def GET(request): + """Get all available room types.""" + + # Get the RoomTypes + + room_types = RoomType.query() + + # Return the RoomTypes + + return Response( + 200, + 'Successfully retrieved RoomTypes.', + [x.to_JSON() for x in room_types] + ) diff --git a/opendc/api/v1/room-types/name/__init__.py b/opendc/api/v1/room-types/name/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/room-types/name/allowed-objects/__init__.py b/opendc/api/v1/room-types/name/allowed-objects/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/room-types/name/allowed-objects/endpoint.py b/opendc/api/v1/room-types/name/allowed-objects/endpoint.py new file mode 100644 index 00000000..76b863f1 --- /dev/null +++ b/opendc/api/v1/room-types/name/allowed-objects/endpoint.py @@ -0,0 +1,30 @@ +from opendc.models.allowed_object import AllowedObject +from opendc.util import exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this room's allowed objects.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'name': 'string' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Get the AllowedObjects + + allowed_objects = AllowedObject.query('room_type', request.params_path['name']) + + # Return the AllowedObjects + + return Response( + 200, + 'Successfully retrieved AllowedObjects.', + [x.to_JSON() for x in allowed_objects] + ) diff --git a/opendc/api/v1/schedulers/__init__.py b/opendc/api/v1/schedulers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/schedulers/endpoint.py b/opendc/api/v1/schedulers/endpoint.py new file mode 100644 index 00000000..206c7cb9 --- /dev/null +++ b/opendc/api/v1/schedulers/endpoint.py @@ -0,0 +1,17 @@ +from opendc.models.scheduler import Scheduler +from opendc.util.rest import Response + +def GET(request): + """Get all available Schedulers.""" + + # Get the Schedulers + + schedulers = Scheduler.query() + + # Return the Schedulers + + return Response( + 200, + 'Successfully retrieved Schedulers.', + [x.to_JSON() for x in schedulers] + ) diff --git a/opendc/api/v1/simulations/__init__.py b/opendc/api/v1/simulations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/endpoint.py b/opendc/api/v1/simulations/endpoint.py new file mode 100644 index 00000000..ff669290 --- /dev/null +++ b/opendc/api/v1/simulations/endpoint.py @@ -0,0 +1,86 @@ +from datetime import datetime + +from opendc.models.authorization import Authorization +from opendc.models.datacenter import Datacenter +from opendc.models.path import Path +from opendc.models.section import Section +from opendc.models.simulation import Simulation +from opendc.models.user import User +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def POST(request): + """Create a new simulation, and return that new simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + body = { + 'simulation': { + 'name': 'string' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Simulation + + simulation_data = request.params_body['simulation'] + + simulation_data['datetimeCreated'] = database.datetime_to_string(datetime.now()) + simulation_data['datetimeLastEdited'] = database.datetime_to_string(datetime.now()) + + simulation = Simulation.from_JSON(simulation_data) + + # Insert this Simulation into the database + + simulation.insert() + + # Instantiate an Authorization and insert it into the database + + authorization = Authorization( + user_id = User.from_google_id(request.google_id).id, + simulation_id = simulation.id, + authorization_level = 'OWN' + ) + + authorization.insert() + + # Instantiate a Path and insert it into the database + + path = Path( + simulation_id = simulation.id, + datetime_created = database.datetime_to_string(datetime.now()) + ) + + path.insert() + + # Instantiate a Datacenter and insert it into the database + + datacenter = Datacenter( + starred = 0, + simulation_id = simulation.id + ) + + datacenter.insert() + + # Instantiate a Section and insert it into the database + + section = Section( + path_id = path.id, + datacenter_id = datacenter.id, + start_tick = 0 + ) + + section.insert() + + # Return this Simulation + + return Response( + 200, + 'Successfully created {}.'.format(simulation), + simulation.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/__init__.py b/opendc/api/v1/simulations/simulationId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/authorizations/__init__.py b/opendc/api/v1/simulations/simulationId/authorizations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/authorizations/endpoint.py b/opendc/api/v1/simulations/simulationId/authorizations/endpoint.py new file mode 100644 index 00000000..d880564e --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/authorizations/endpoint.py @@ -0,0 +1,43 @@ +from opendc.models.authorization import Authorization +from opendc.models.simulation import Simulation +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Find all authorizations for a Simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Simulation and make sure it exists + + simulation = Simulation.from_primary_key((request.params_path['simulationId'],)) + + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this User is allowed to view this Simulation's Authorizations + + if not simulation.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from retrieving Authorizations for {}.'.format(simulation)) + + # Get the Authorizations + + authorizations = Authorization.query('simulation_id', request.params_path['simulationId']) + + # Return the Authorizations + + return Response( + 200, + 'Successfully retrieved Authorizations for {}.'.format(simulation), + [x.to_JSON() for x in authorizations] + ) diff --git a/opendc/api/v1/simulations/simulationId/authorizations/userId/__init__.py b/opendc/api/v1/simulations/simulationId/authorizations/userId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/authorizations/userId/endpoint.py b/opendc/api/v1/simulations/simulationId/authorizations/userId/endpoint.py new file mode 100644 index 00000000..c3e599cf --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/authorizations/userId/endpoint.py @@ -0,0 +1,208 @@ +from opendc.models.authorization import Authorization +from opendc.models.simulation import Simulation +from opendc.models.user import User +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def DELETE(request): + """Delete a user's authorization level over a simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'userId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Authorization + + authorization = Authorization.from_primary_key(( + request.params_path['userId'], + request.params_path['simulationId'] + )) + + # Make sure this Authorization exists in the database + + if not authorization.exists(): + return Response (404, '{} not found.'.format(authorization)) + + # Make sure this User is allowed to delete this Authorization + + if not authorization.google_id_has_at_least(request.google_id, 'OWN'): + return Response(403, 'Forbidden from deleting {}.'.format(authorization)) + + # Delete this Authorization + + authorization.delete() + + return Response( + 200, + 'Successfully deleted {}.'.format(authorization), + authorization.to_JSON() + ) + +def GET(request): + """Get this User's Authorization over this Simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'userId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Authorization + + authorization = Authorization.from_primary_key(( + request.params_path['userId'], + request.params_path['simulationId'] + )) + + # Make sure this Authorization exists in the database + + if not authorization.exists(): + return Response(404, '{} not found.'.format(authorization)) + + # Read this Authorization from the database + + authorization.read() + + # Return this Authorization + + return Response( + 200, + 'Successfully retrieved {}'.format(authorization), + authorization.to_JSON() + ) + +def POST(request): + """Add an authorization for a user's access to a simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'userId': 'int', + 'simulationId': 'int' + }, + body = { + 'authorization': { + 'authorizationLevel': 'string' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Authorization + + authorization = Authorization.from_JSON({ + 'userId': request.params_path['userId'], + 'simulationId': request.params_path['simulationId'], + 'authorizationLevel': request.params_body['authorization']['authorizationLevel'] + }) + + # Make sure the Simulation and User exist + + user = User.from_primary_key((authorization.user_id,)) + if not user.exists(): + return Response(404, '{} not found.'.format(user)) + + simulation = Simulation.from_primary_key((authorization.simulation_id,)) + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this User is allowed to add this Authorization + + if not simulation.google_id_has_at_least(request.google_id, 'OWN'): + return Response(403, 'Forbidden from creating {}.'.format(authorization)) + + # Make sure this Authorization does not already exist + + if authorization.exists(): + return Response(409, '{} already exists.'.format(authorization)) + + # Try to insert this Authorization into the database + + try: + authorization.insert() + + except exceptions.ForeignKeyError: + return Response(400, 'Invalid authorizationLevel') + + # Return this Authorization + + return Response( + 200, + 'Successfully added {}'.format(authorization), + authorization.to_JSON() + ) + +def PUT(request): + """Change a user's authorization level over a simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'userId': 'int' + }, + body = { + 'authorization': { + 'authorizationLevel': 'string' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate and Authorization + + authorization = Authorization.from_JSON({ + 'userId': request.params_path['userId'], + 'simulationId': request.params_path['simulationId'], + 'authorizationLevel': request.params_body['authorization']['authorizationLevel'] + }) + + # Make sure this Authorization exists + + if not authorization.exists(): + return Response(404, '{} not found.'.format(authorization)) + + # Make sure this User is allowed to edit this Authorization + + if not authorization.google_id_has_at_least(request.google_id, 'OWN'): + return Response(403, 'Forbidden from updating {}.'.format(authorization)) + + # Try to update this Authorization + + try: + authorization.update() + + except exceptions.ForeignKeyError as e: + return Response(400, 'Invalid authorization level.') + + # Return this Authorization + + return Response( + 200, + 'Successfully updated {}.'.format(authorization), + authorization.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/endpoint.py new file mode 100644 index 00000000..c9c78a8a --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/endpoint.py @@ -0,0 +1,43 @@ +from opendc.models.datacenter import Datacenter +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Datacenter.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Datacenter from the database + + datacenter = Datacenter.from_primary_key((request.params_path['datacenterId'],)) + + # Make sure this Datacenter exists + + if not datacenter.exists(): + return Response(404, '{} not found.'.format(datacenter)) + + # Make sure this user is authorized to view this Datacenter + + if not datacenter.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from retrieving {}.'.format(datacenter)) + + # Return this Datacenter + + datacenter.read() + + return Response( + 200, + 'Successfully retrieved {}.'.format(datacenter), + datacenter.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/endpoint.py new file mode 100644 index 00000000..1127ce95 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/endpoint.py @@ -0,0 +1,111 @@ +from opendc.models.room import Room +from opendc.models.datacenter import Datacenter +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Datacenter's Rooms.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int' + } + ) + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Datacenter from the database + + datacenter = Datacenter.from_primary_key((request.params_path['datacenterId'],)) + + # Make sure this Datacenter exists + + if not datacenter.exists(): + return Response(404, '{} not found.'.format(datacenter)) + + # Make sure this user is authorized to view this Datacenter's Rooms + + if not datacenter.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Rooms for {}.'.format(datacenter)) + + # Get and return the Rooms + + rooms = Room.query('datacenter_id', datacenter.id) + + return Response( + 200, + 'Successfully retrieved Rooms for {}.'.format(datacenter), + [x.to_JSON() for x in rooms] + ) + +def POST(request): + """Add a Room.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int' + }, + body = { + 'room': { + 'id': 'int', + 'datacenterId': 'int', + 'roomType': 'string' + } + } + ) + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Make sure the passed object's datacenter id matches the path datacenter id + + if request.params_path['datacenterId'] != request.params_body['room']['datacenterId']: + return Response(400, 'ID mismatch.') + + # Instantiate a Datacenter from the database + + datacenter = Datacenter.from_primary_key((request.params_path['datacenterId'],)) + + # Make sure this Datacenter exists + + if not datacenter.exists(): + return Response(404, '{} not found.'.format(datacenter)) + + # Make sure this user is authorized to edit this Datacenter's Rooms + + if not datacenter.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from adding a Room to {}.'.format(datacenter)) + + # Add a name if not provided + + if not 'name' in request.params_body['room']: + room_count = len(Room.query('datacenter_id', datacenter.id)) + request.params_body['room']['name'] = 'Room {}'.format(room_count) + + # Instantiate a Room + + room = Room.from_JSON(request.params_body['room']) + + # Try to insert this Room + + try: + room.insert() + except Exception as e: + return Response(400, 'Invalid `roomType` or existing `name`.') + + # Return this Room + + room.read() + + return Response( + 200, + 'Successfully added {}.'.format(room), + room.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/endpoint.py new file mode 100644 index 00000000..44ed82d6 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/endpoint.py @@ -0,0 +1,140 @@ +from opendc.models.room import Room +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Room.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Room from the database + + room = Room.from_primary_key((request.params_path['roomId'],)) + + # Make sure this Room exists + + if not room.exists(): + return Response(404, '{} not found.'.format(room)) + + # Make sure this user is authorized to view this Room + + if not room.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from retrieving {}.'.format(room)) + + # Return this Room + + room.read() + + return Response( + 200, + 'Successfully retrieved {}.'.format(room), + room.to_JSON() + ) + +def PUT(request): + """Update this Room's name and type.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int' + }, + body = { + 'room': { + 'name': 'string', + 'roomType': 'string' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Room from the database + + room = Room.from_primary_key((request.params_path['roomId'],)) + + # Make sure this Room exists + + if not room.exists(): + return Response(404, '{} not found.'.format(room)) + + # Make sure this user is authorized to edit this Room + + if not room.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from updating {}.'.format(room)) + + # Update this Room + + room.name = request.params_body['room']['name'] + room.type = request.params_body['room']['roomType'] + + try: + room.update() + except exceptions.ForeignKeyError: + return Response(400, 'Invalid `roomType` or existing `name`.') + + # Return this Room + + return Response( + 200, + 'Successfully updated {}.'.format(room), + room.to_JSON() + ) + +def DELETE(request): + """Delete this Room.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Room and make sure it exists + + room = Room.from_primary_key((request.params_path['roomId'],)) + + if not room.exists(): + return Response(404, '{} not found.'.format(room)) + + # Make sure this user is authorized to delete this Room + + if not room.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from deleting {}.'.format(room)) + + # Delete this Room + + room.delete() + + # Return this Room + + return Response( + 200, + 'Sucessfully deleted {}.'.format(room), + room.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/endpoint.py new file mode 100644 index 00000000..f615a6d4 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/endpoint.py @@ -0,0 +1,123 @@ +from opendc.models.tile import Tile +from opendc.models.room import Room +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Room's Tiles.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Room from the database + + room = Room.from_primary_key((request.params_path['roomId'],)) + + # Make sure this Room exists + + if not room.exists(): + return Response(404, '{} not found.'.format(room)) + + # Make sure this user is authorized to view this Room's Tiles + + if not room.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Tiles for {}.'.format(room)) + + # Get and return the Tiles + + tiles = Tile.query('room_id', room.id) + + for tile in tiles: + tile.read() + + return Response( + 200, + 'Successfully retrieved Tiles for {}.'.format(room), + [x.to_JSON() for x in tiles] + ) + +def POST(request): + """Add a Tile.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int' + }, + body = { + 'tile': { + 'roomId': 'int', + 'positionX': 'int', + 'positionY': 'int' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + if request.params_path['roomId'] != request.params_body['tile']['roomId']: + return Response(400, 'ID mismatch') + + # Instantiate a Room from the database + + room = Room.from_primary_key((request.params_path['roomId'],)) + + # Make sure this Room exists + + if not room.exists(): + return Response(404, '{} not found.'.format(room)) + + # Make sure this user is authorized to edit this Room's Tiles + + if not room.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from adding Tiles to {}.'.format(room)) + + # Clean the tile JSON + + tile_json = request.params_body['tile'] + + tile_json['objectId'] = None + tile_json['objectType'] = None + + # Instantiate a Tile + + tile = Tile.from_JSON(tile_json) + + # Try to insert this Tile + + try: + tile.insert() + + except exceptions.ForeignKeyError as e: + + if e.message == 'OccupiedTilePosition': + return Response(409, 'Tile position occupied.') + + elif e.message == 'InvalidTilePosition': + return Response(400, 'Invalid Tile position (new Tiles must neighbor existing Tiles).') + + # Return this Tile + + tile.read() + + return Response( + 200, + 'Successfully added {}.'.format(tile), + tile.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/endpoint.py new file mode 100644 index 00000000..b15a10f7 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/endpoint.py @@ -0,0 +1,89 @@ +from opendc.models.tile import Tile +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Tile.""" + + # Make sure request parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Tile from the database + + tile = Tile.from_primary_key((request.params_path['tileId'],)) + + # Make sure this Tile exists + + if not tile.exists(): + return Response(404, '{} not found.'.format(tile)) + + # Make sure this user is authorized to view this Tile + + if not tile.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from retrieving {}.'.format(tile)) + + # Return this Tile + + tile.read() + + return Response( + 200, + 'Successfully retrieved {}.'.format(tile), + tile.to_JSON() + ) + +def DELETE(request): + """Delete this Tile.""" + + # Make sure request parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Tile from the database + + tile = Tile.from_primary_key((request.params_path['tileId'],)) + + # Make sure this Tile exists + + if not tile.exists(): + return Response(404, '{} not found.'.format(tile)) + + # Make sure this user is authorized to edit this Tile + + if not tile.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from deleting {}.'.format(tile)) + + # Delete this Tile + + tile.delete() + + # Return this Tile + + return Response( + 200, + 'Successfully deleted {}.'.format(tile), + tile.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/endpoint.py new file mode 100644 index 00000000..d9fb1959 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/endpoint.py @@ -0,0 +1,245 @@ +from opendc.models.rack import Rack +from opendc.models.tile import Tile +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Tile's Rack.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int' + }, + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Tile from the database + + tile = Tile.from_primary_key((request.params_path['tileId'],)) + + # Make sure this Tile exists + + if not tile.exists(): + return Response(404, '{} not found.'.format(tile)) + + # Make sure this user is authorized to view this Tile + + if not tile.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from editing {}'.format(tile)) + + # Instantiate a Rack from the database + + rack = Rack.from_primary_key((tile.object_id,)) + + # Make sure this Rack exists + + if not rack.exists(): + return Response(404, '{} not found'.format(rack)) + + # Return the Rack + + rack.read() + + return Response( + 200, + 'Successfully retrieved {}.'.format(rack), + rack.to_JSON() + ) + +def POST(request): + """Add a Rack to this Tile if it is empty.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int' + }, + body = { + 'rack': { + 'name': 'string', + 'capacity': 'int', + 'powerCapacityW': 'int' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Tile from the database + + tile = Tile.from_primary_key((request.params_path['tileId'],)) + + # Make sure this Tile exists + + if not tile.exists(): + return Response(404, '{} not found.'.format(tile)) + + # Make sure this user is authorized to edit this Tile + + if not tile.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from editing {}'.format(tile)) + + # Make sure this Tile isn't occupied + + if tile.object_id is not None: + return Response(409, '{} occupied.'.format(tile)) + + # Instantiate a Rack and insert it into the database + + rack = Rack.from_JSON(request.params_body['rack']) + rack.insert() + + # Try to add this Rack to this Tile + + tile.object_id = rack.id + tile.object_type = 'RACK' + tile.update() + + # Return this Rack + + rack.read() + + return Response( + 200, + 'Successfully added {}.'.format(rack), + rack.to_JSON() + ) + +def PUT(request): + """Update the Rack on this Tile.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int' + }, + body = { + 'rack': { + 'name': 'string', + 'capacity': 'int', + 'powerCapacityW': 'int' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Tile from the database + + tile = Tile.from_primary_key((request.params_path['tileId'],)) + + # Make sure this Tile exists + + if not tile.exists(): + return Response(404, '{} not found.'.format(tile)) + + # Make sure this user is authorized to edit this Tile + + if not tile.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from editing {}'.format(tile)) + + # Instantiate a Rack from the database + + rack = Rack.from_primary_key((tile.object_id,)) + + # Make sure this Rack exists + + if not rack.exists(): + return Response(404, '{} not found'.format(rack)) + + # Update this Rack + + rack.name = request.params_body['rack']['name'] + rack.capacity = request.params_body['rack']['capacity'] + + rack.update() + + # Return this Rack + + rack.read() + + return Response( + 200, + 'Successfully updated {}.'.format(rack), + rack.to_JSON() + ) + +def DELETE(request): + """Delete this Tile's Rack.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int' + }, + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Tile from the database + + tile = Tile.from_primary_key((request.params_path['tileId'],)) + + # Make sure this Tile exists + + if not tile.exists(): + return Response(404, '{} not found.'.format(tile)) + + # Make sure this user is authorized to edit this Tile + + if not tile.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from editing {}'.format(tile)) + + # Instantiate a Rack from the database + + rack = Rack.from_primary_key((tile.object_id,)) + + # Make sure this Rack exists + + if not rack.exists(): + return Response(404, '{} not found'.format(rack)) + + # Remove this Rack from this Tile + + tile.object_id = None + tile.object_type = None + + tile.update() + + # Delete this Rack + + rack.delete() + + # Return this Rack + + return Response( + 200, + 'Successfully deleted {}.'.format(rack), + rack.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/endpoint.py new file mode 100644 index 00000000..a67bb1c3 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/endpoint.py @@ -0,0 +1,122 @@ +from opendc.models.machine import Machine +from opendc.models.rack import Rack +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Rack's Machines.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Rack from the database + + rack = Rack.from_tile_id(request.params_path['tileId']) + + # Make sure this Rack exists + + if not rack.exists(): + return Response(404, '{} not found.'.format(rack)) + + # Make sure this user is authorized to view this Rack's Machines + + if not rack.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing {}.'.format(rack)) + + # Get and return the Machines + + machines = Machine.query('rack_id', rack.id) + + for machine in machines: + machine.read() + + return Response( + 200, + 'Successfully retrieved Machines for {}.'.format(rack), + [x.to_JSON() for x in machines] + ) + +def POST(request): + """Add a Machine to this rack.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int' + }, + body = { + 'machine': { + 'rackId': 'int', + 'position': 'int', + 'tags': 'list-string', + 'cpuIds': 'list-int', + 'gpuIds': 'list-int', + 'memoryIds': 'list-int', + 'storageIds': 'list-int' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Rack from the database + + rack = Rack.from_tile_id(request.params_path['tileId']) + + # Make sure this Rack exists + + if not rack.exists(): + return Response(404, '{} not found.'.format(rack)) + + # Make sure this Rack's ID matches the given rack ID + + if rack.id != request.params_body['machine']['rackId']: + return Response(400, 'Rack ID in `machine` and path do not match.') + + # Make sure this user is authorized to edit this Rack's Machines + + if not rack.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing {}.'.format(rack)) + + # Instantiate a Machine + + machine = Machine.from_JSON(request.params_body['machine']) + + # Try to insert this Machine + + try: + machine.insert() + + except exceptions.ForeignKeyError: + return Response(409, 'Rack position occupied.') + + except: + return Response(400, 'Invalid Machine.') + + # Return this Machine + + machine.read() + + return Response( + 200, + 'Successfully added {}.'.format(machine), + machine.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/position/__init__.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/position/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/position/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/position/endpoint.py new file mode 100644 index 00000000..e33da5d6 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/datacenterId/rooms/roomId/tiles/tileId/rack/machines/position/endpoint.py @@ -0,0 +1,170 @@ +from opendc.models.machine import Machine +from opendc.models.rack import Rack +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get the Machine at this location in this Rack.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int', + 'position': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Machine from the database + + machine = Machine.from_tile_id_and_rack_position(request.params_path['tileId'], request.params_path['position']) + + # Make sure this Machine exists + + if not machine.exists(): + return Response(404, '{} not found.'.format(machine)) + + # Make sure this user is authorized to view this Machine + + if not machine.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from retrieving {}.'.format(machine)) + + # Return this Machine + + machine.read() + + return Response( + 200, + 'Successfully retrieved {}.'.format(machine), + machine.to_JSON() + ) + +def PUT(request): + """Update the Machine at this location in this Rack.""" + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int', + 'position': 'int' + }, + body = { + 'machine': { + 'rackId': 'int', + 'position': 'int', + 'tags': 'list-string', + 'cpuIds': 'list-int', + 'gpuIds': 'list-int', + 'memoryIds': 'list-int', + 'storageIds': 'list-int' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Machine from the database + + machine = Machine.from_tile_id_and_rack_position(request.params_path['tileId'], request.params_path['position']) + + # Make sure this Machine exists + + if not machine.exists(): + return Response(404, '{} not found.'.format(machine)) + + # Make sure this Machine's rack ID is right + + rack = Rack.from_tile_id(request.params_path['tileId']) + + if not rack.exists() or rack.id != request.params_body['machine']['rackId']: + return Response(400, 'Mismatch in Rack IDs.') + + # Make sure this user is authorized to edit this Machine + + if not machine.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from retrieving {}.'.format(machine)) + + # Update this Machine + + machine.positoin = request.params_body['machine']['position'] + machine.tags = request.params_body['machine']['tags'] + machine.cpu_ids = request.params_body['machine']['cpuIds'] + machine.gpu_ids = request.params_body['machine']['gpuIds'] + machine.memory_ids = request.params_body['machine']['memoryIds'] + machine.storage_ids = request.params_body['machine']['storageIds'] + + try: + machine.update() + + except exceptions.ForeignKeyError: + return Response(409, 'Rack position occupied.') + + except Exception as e: + print e + return Response(400, 'Invalid Machine.') + + # Return this Machine + + machine.read() + + return Response( + 200, + 'Successfully updated {}.'.format(machine), + machine.to_JSON() + ) + +def DELETE(request): + """Delete the Machine at this location in this Rack.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'datacenterId': 'int', + 'roomId': 'int', + 'tileId': 'int', + 'position': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Machine from the database + + machine = Machine.from_tile_id_and_rack_position(request.params_path['tileId'], request.params_path['position']) + + # Make sure this Machine exists + + if not machine.exists(): + return Response(404, '{} not found.'.format(machine)) + + # Make sure this user is authorized to edit this Machine + + if not machine.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from retrieving {}.'.format(machine)) + + # Delete this Machine + + machine.delete() + + # Return this Machine + + return Response( + 200, + 'Successfully deleted {}.'.format(machine), + machine.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/datacenters/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/endpoint.py new file mode 100644 index 00000000..d53cd1c8 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/datacenters/endpoint.py @@ -0,0 +1,60 @@ +from opendc.models.datacenter import Datacenter +from opendc.models.simulation import Simulation +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def POST(request): + """Add a new Datacenter to this Simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int' + }, + body = { + 'datacenter': { + 'starred': 'int', + 'simulationId': 'int' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Make sure the passed object's simulation id matches the path simulation id + + if request.params_path['simulationId'] != request.params_body['datacenter']['simulationId']: + return Response(400, 'ID mismatch.') + + # Instantiate a Simulation from the database + + simulation = Simulation.from_primary_key((request.params_path['simulationId'],)) + + # Make sure this Simulation exists + + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this user is authorized to edit this Simulation's Databases + + if not simulation.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from adding a datacenter to {}.'.format(simulation)) + + # Instantiate a Datacenter + + datacenter = Datacenter.from_JSON(request.params_body['datacenter']) + + datacenter.insert() + + # return this Datacenter + + datacenter.read() + + return Response( + 200, + 'Successfully added {}.'.format(datacenter), + datacenter.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/endpoint.py b/opendc/api/v1/simulations/simulationId/endpoint.py new file mode 100644 index 00000000..01623973 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/endpoint.py @@ -0,0 +1,132 @@ +from datetime import datetime + +from opendc.models.authorization import Authorization +from opendc.models.simulation import Simulation +from opendc.models.user import User +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def DELETE(request): + """Delete this Simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Simulation and make sure it exists + + simulation = Simulation.from_primary_key((request.params_path['simulationId'],)) + + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this User is allowed to delete this Simulation + + if not simulation.google_id_has_at_least(request.google_id, 'OWN'): + return Response(403, 'Forbidden from deleting {}.'.format(simulation)) + + # Delete this Simulation from the database + + simulation.delete() + + # Return this Simulation + + return Response( + 200, + 'Successfully deleted {}.'.format(simulation), + simulation.to_JSON() + ) + +def GET(request): + """Get this Simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Simulation and make sure it exists + + simulation = Simulation.from_primary_key((request.params_path['simulationId'],)) + + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this User is allowed to view this Simulation + + if not simulation.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from retrieving {}.'.format(simulation)) + + # Return this Simulation + + simulation.read() + + return Response( + 200, + 'Successfully retrieved {}'.format(simulation), + simulation.to_JSON() + ) + +def PUT(request): + """Update a simulation's name.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + body = { + 'simulation': { + 'name': 'name' + } + }, + path = { + 'simulationId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Simulation and make sure it exists + + simulation = Simulation.from_primary_key((request.params_path['simulationId'],)) + + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this User is allowed to edit this Simulation + + if not simulation.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from editing {}.'.format(simulation)) + + # Update this Simulation in the database + + simulation.read() + + simulation.name = request.params_body['simulation']['name'] + simulation.datetime_last_edited = database.datetime_to_string(datetime.now()) + + simulation.update() + + # Return this Simulation + + return Response( + 200, + 'Successfully updated {}.'.format(simulation), + simulation.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/experiments/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/endpoint.py new file mode 100644 index 00000000..8cc4165f --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/experiments/endpoint.py @@ -0,0 +1,114 @@ +from opendc.models.experiment import Experiment +from opendc.models.queued_experiment import QueuedExperiment +from opendc.models.simulation import Simulation +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Simulation's Experiments.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Simulation from the database + + simulation = Simulation.from_primary_key((request.params_path['simulationId'],)) + + # Make sure this Simulation exists + + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this user is authorized to view this Simulation's Experiments + + if not simulation.google_id_has_at_least(request.google_id, 'VIEW'): + return Reponse(403, 'Forbidden from viewing Experiments for {}.'.format(simulation)) + + # Get and return the Experiments + + experiments = Experiment.query('simulation_id', request.params_path['simulationId']) + + return Response( + 200, + 'Successfully retrieved Experiments for {}.'.format(simulation), + [x.to_JSON() for x in experiments] + ) + +def POST(request): + """Add a new Experiment for this Simulation.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int' + }, + body = { + 'experiment': { + 'simulationId': 'int', + 'pathId': 'int', + 'traceId': 'int', + 'schedulerName': 'string', + 'name': 'string' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Make sure the passed object's simulation id matches the path simulation id + + if request.params_path['simulationId'] != request.params_body['experiment']['simulationId']: + return Response(403, 'ID mismatch.') + + # Instantiate a Simulation from the database + + simulation = Simulation.from_primary_key((request.params_path['simulationId'],)) + + # Make sure this Simulation exists + + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this user is authorized to edit this Simulation's Experiments + + if not simulation.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from adding an experiment to {}.'.format(simulation)) + + # Instantiate an Experiment + + experiment = Experiment.from_JSON(request.params_body['experiment']) + + # Try to insert this Experiment + + try: + experiment.insert() + + except exceptions.ForeignKeyError as e: + return Response(400, 'Foreign key constraint not met.') + + # Queue this Experiment for simulation + + queued_experiment = QueuedExperiment(experiment_id = experiment.id) + queued_experiment.insert() + + # Return this Experiment + + experiment.read() + + return Response( + 200, + 'Successfully added {}.'.format(experiment), + experiment.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/endpoint.py new file mode 100644 index 00000000..7af62b92 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/experiments/experimentId/endpoint.py @@ -0,0 +1,138 @@ +from opendc.models.experiment import Experiment +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Experiment.""" + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment from the database + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + # Make sure this Experiment exists + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to view this Experiment + + if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from retrieving {}.'.format(experiment)) + + # Return this Experiment + + experiment.read() + + return Response( + 200, + 'Successfully retrieved {}.'.format(experiment), + experiment.to_JSON() + ) + +def PUT(request): + """Update this Experiment's Path, Trace, Scheduler, and/or name.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + }, + body = { + 'experiment': { + 'pathId': 'int', + 'traceId': 'int', + 'schedulerName': 'string', + 'name': 'string' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment from the database + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + # Make sure this Experiment exists + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to edit this Experiment + + if not experiment.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from updating {}.'.format(experiment)) + + # Update this Experiment + + experiment.path_id = request.params_body['experiment']['pathId'] + experiment.trace_id = request.params_body['experiment']['traceId'] + experiment.scheduler_name = request.params_body['experiment']['schedulerName'] + experiment.name = request.params_body['experiment']['name'] + + try: + experiment.update() + + except exceptions.ForeignKeyError: + return Response(400, 'Foreign key error.') + + # Return this Experiment + + return Response( + 200, + 'Successfully updated {}.'.format(experiment), + experiment.to_JSON() + ) + +def DELETE(request): + """Delete this Experiment.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment and make sure it exists + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to delete this Experiment + + if not experiment.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from deleting {}.'.format(experiment)) + + # Delete and return this Experiment + + experiment.delete() + + return Response( + 200, + 'Successfully deleted {}.'.format(experiment), + experiment.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/last-simulated-tick/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/last-simulated-tick/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/last-simulated-tick/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/last-simulated-tick/endpoint.py new file mode 100644 index 00000000..ed33be85 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/experiments/experimentId/last-simulated-tick/endpoint.py @@ -0,0 +1,43 @@ +from opendc.models.experiment import Experiment +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Experiment's last simulated tick.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment from the database + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + # Make sure this Experiment exisits + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to view this Experiment's last simulated tick + + if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Room States for {}.'.format(experiment)) + + # Get and return the last simulated tick + + last_simulated_tick = experiment.get_last_simulated_tick() + + return Response( + 200, + 'Successfully retrieved Room States for {}.'.format(experiment), + {'lastSimulatedTick': last_simulated_tick} + ) diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/machine-states/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/machine-states/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/machine-states/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/machine-states/endpoint.py new file mode 100644 index 00000000..c5ba0abe --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/experiments/experimentId/machine-states/endpoint.py @@ -0,0 +1,51 @@ +from opendc.models.experiment import Experiment +from opendc.models.machine_state import MachineState +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Experiment's Machine States.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment from the database + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + # Make sure this Experiment exisits + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to view this Experiment's Machine States + + if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Machine States for {}.'.format(experiment)) + + # Get and return the Machine States + + if 'tick' in request.params_query: + machine_states = MachineState.from_experiment_id_and_tick( + request.params_path['experimentId'], + request.params_query['tick'] + ) + + else: + machine_states = MachineState.from_experiment_id(request.params_path['experimentId']) + + return Response( + 200, + 'Successfully retrieved Machine States for {}.'.format(experiment), + [x.to_JSON() for x in machine_states] + ) diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/rack-states/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/rack-states/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/rack-states/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/rack-states/endpoint.py new file mode 100644 index 00000000..6e71c496 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/experiments/experimentId/rack-states/endpoint.py @@ -0,0 +1,51 @@ +from opendc.models.experiment import Experiment +from opendc.models.rack_state import RackState +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Experiment's Tack States.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment from the database + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + # Make sure this Experiment exisits + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to view this Experiment's Rack States + + if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Rack States for {}.'.format(experiment)) + + # Get and return the Rack States + + if 'tick' in request.params_query: + rack_states = RackState.from_experiment_id_and_tick( + request.params_path['experimentId'], + request.params_query['tick'] + ) + + else: + rack_states = RackState.from_experiment_id(request.params_path['experimentId']) + + return Response( + 200, + 'Successfully retrieved Rack States for {}.'.format(experiment), + [x.to_JSON() for x in rack_states] + ) diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/room-states/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/room-states/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/room-states/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/room-states/endpoint.py new file mode 100644 index 00000000..d8c9fb45 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/experiments/experimentId/room-states/endpoint.py @@ -0,0 +1,51 @@ +from opendc.models.experiment import Experiment +from opendc.models.room_state import RoomState +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Experiment's Room States.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment from the database + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + # Make sure this Experiment exisits + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to view this Experiment's Room States + + if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Room States for {}.'.format(experiment)) + + # Get and return the Room States + + if 'tick' in request.params_query: + room_states = RoomState.from_experiment_id_and_tick( + request.params_path['experimentId'], + request.params_query['tick'] + ) + + else: + room_states = RoomState.from_experiment_id(request.params_path['experimentId']) + + return Response( + 200, + 'Successfully retrieved Room States for {}.'.format(experiment), + [x.to_JSON() for x in room_states] + ) diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/task-durations/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/task-durations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/task-durations/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/task-durations/endpoint.py new file mode 100644 index 00000000..1bb60ca2 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/experiments/experimentId/statistics/task-durations/endpoint.py @@ -0,0 +1,44 @@ +from opendc.models.experiment import Experiment +from opendc.models.task_duration import TaskDuration +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Experiment's Task Durations.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment from the database + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + # Make sure this Experiment exisits + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to view this Experiment's Task Durations + + if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Task Durations for {}.'.format(experiment)) + + # Get and return the Task Durations + + task_durations = TaskDuration.from_experiment_id(request.params_path['experimentId']) + + return Response( + 200, + 'Successfully retrieved Task Durations for {}.'.format(experiment), + [x.to_JSON() for x in task_durations] + ) diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/task-states/__init__.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/task-states/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/experiments/experimentId/task-states/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/experimentId/task-states/endpoint.py new file mode 100644 index 00000000..b11512c0 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/experiments/experimentId/task-states/endpoint.py @@ -0,0 +1,51 @@ +from opendc.models.experiment import Experiment +from opendc.models.task_state import TaskState +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Experiment's Task States.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'experimentId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate an Experiment from the database + + experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) + + # Make sure this Experiment exists + + if not experiment.exists(): + return Response(404, '{} not found.'.format(experiment)) + + # Make sure this user is authorized to view Task States for this Experiment + + if not experiment.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Task States for {}.'.format(experiment)) + + # Get and return the Task States + + if 'tick' in request.params_query: + task_states = TaskState.from_experiment_id_and_tick( + request.params_path['experimentId'], + request.params_query['tick'] + ) + + else: + task_states = TaskState.query('experiment_id', request.params_path['experimentId']) + + return Response( + 200, + 'Successfully retrieved Task States for {}.'.format(experiment), + [x.to_JSON() for x in task_states] + ) diff --git a/opendc/api/v1/simulations/simulationId/paths/__init__.py b/opendc/api/v1/simulations/simulationId/paths/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/paths/endpoint.py b/opendc/api/v1/simulations/simulationId/paths/endpoint.py new file mode 100644 index 00000000..e74c8d22 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/paths/endpoint.py @@ -0,0 +1,42 @@ +from opendc.models.path import Path +from opendc.models.simulation import Simulation +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Simulation's Paths.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int' + } + ) + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Simulation from the database + + simulation = Simulation.from_primary_key((request.params_path['simulationId'],)) + + # Make sure this Simulation exists + + if not simulation.exists(): + return Response(404, '{} not found.'.format(simulation)) + + # Make sure this user is authorized to view this Simulation's path + + if not simulation.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Paths for {}.'.format(simulation)) + + # Get and return the Paths + + paths = Path.query('simulation_id', request.params_path['simulationId']) + + return Response( + 200, + 'Successfully retrieved Paths for {}.'.format(simulation), + [x.to_JSON() for x in paths] + ) diff --git a/opendc/api/v1/simulations/simulationId/paths/pathId/__init__.py b/opendc/api/v1/simulations/simulationId/paths/pathId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/paths/pathId/branches/__init__.py b/opendc/api/v1/simulations/simulationId/paths/pathId/branches/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/paths/pathId/branches/endpoint.py b/opendc/api/v1/simulations/simulationId/paths/pathId/branches/endpoint.py new file mode 100644 index 00000000..2aa34238 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/paths/pathId/branches/endpoint.py @@ -0,0 +1,166 @@ +from datetime import datetime + +from opendc.models.datacenter import Datacenter +from opendc.models.machine import Machine +from opendc.models.object import Object +from opendc.models.path import Path +from opendc.models.rack import Rack +from opendc.models.room import Room +from opendc.models.section import Section +from opendc.models.tile import Tile +from opendc.util import database, exceptions +from opendc.util.rest import Request, Response + +def POST(request): + """Create a new Path that branches off of this Path at the specified tick.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'pathId': 'int' + }, + body = { + 'section': { + 'startTick': 'int' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate the current Path from the database + + current_path = Path.from_primary_key((request.params_path['pathId'],)) + + # Make sure the current Path exists + + if not current_path.exists(): + return Response(404, '{} not found.'.format(current_path)) + + # Make sure this user is authorized to branch off the current Path + + if not current_path.google_id_has_at_least(request.google_id, 'EDIT'): + return Response(403, 'Forbidden from branching off {}.'.format(current_path)) + + # Create the new Path + + new_path = Path( + simulation_id = current_path.simulation_id, + datetime_created = database.datetime_to_string(datetime.now()) + ) + + new_path.insert() + + # Get the current Path's sections and add them to the new Path if they're before the branch + + current_sections = Section.query('path_id', current_path.id) + last_section = None + + for current_section in current_sections: + + if current_section.start_tick < request.params_body['section']['startTick'] or current_section.start_tick == 0: + + new_section = Section( + path_id = new_path.id, + datacenter_id = current_section.datacenter_id, + start_tick = current_section.start_tick + ) + + new_section.insert() + + last_section = current_section + + # Make a deep copy of the last section's datacenter, its rooms, their tiles, etc. + + path_parameters = { + 'simulationId': new_path.simulation_id + } + + # Copy the Datacenter + + old_datacenter = Datacenter.from_primary_key((last_section.datacenter_id,)) + + message = old_datacenter.generate_api_call(path_parameters, request.token) + response = Request(message).process() + + path_parameters['datacenterId'] = response.content['id'] + + # Create the new last Section, with the IDs of the new Path and new Datacenter + + if last_section.start_tick != 0: + new_section = Section( + path_id = new_path.id, + datacenter_id = path_parameters['datacenterId'], + start_tick = request.params_body['section']['startTick'] + ) + + new_section.insert() + + else: + last_section.datacenter_id = path_parameters['datacenterId'] + last_section.update() + + # Copy the rest of the Datacenter, starting with the Rooms... + + old_rooms = Room.query('datacenter_id', old_datacenter.id) + + for old_room in old_rooms: + + old_room.datacenter_id = path_parameters['datacenterId'] + + message = old_room.generate_api_call(path_parameters, request.token) + response = Request(message).process() + + path_parameters['roomId'] = response.content['id'] + + # ... then the Tiles, ... + + old_tiles = Tile.query('room_id', old_room.id) + + for old_tile in old_tiles: + + old_tile.room_id = path_parameters['roomId'] + + message = old_tile.generate_api_call(path_parameters, request.token) + response = Request(message).process() + + path_parameters['tileId'] = response.content['id'] + + old_objects = Object.query('id', old_tile.object_id) + + # ... then the Tile's Rack, ... + + if len(old_objects) == 1 and old_objects[0].type == 'RACK': + + old_rack = Rack.query('id', old_objects[0].id)[0] + + message = old_rack.generate_api_call(path_parameters, request.token) + response = Request(message).process() + + path_parameters['rackId'] = response.content['id'] + + # ... then the Rack's Machines ... + + old_machines = Machine.query('rack_id', old_rack.id) + + for old_machine in old_machines: + + old_machine.read() + old_machine.rack_id = path_parameters['rackId'] + + message = old_machine.generate_api_call(path_parameters, request.token) + response = Request(message).process() + + path_parameters['machineId'] = response.content['id'] + + # Return the new Path + + return Response( + 200, + 'Successfully created {}.'.format(new_path), + new_path.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/paths/pathId/endpoint.py b/opendc/api/v1/simulations/simulationId/paths/pathId/endpoint.py new file mode 100644 index 00000000..71d97a67 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/paths/pathId/endpoint.py @@ -0,0 +1,44 @@ +from opendc.models.path import Path +from opendc.models.simulation import Simulation +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Path.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'pathId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Path from the database + + path = Path.from_primary_key((request.params_path['pathId'],)) + + # Make sure this Path exists + + if not path.exists(): + return Response(404, '{} not found.'.format(path)) + + # Make sure this user is authorized to view this Path + + if not path.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from retrieving {}.'.format(path)) + + # Return this Path + + path.read() + + return Response( + 200, + 'Successfully retrieved {}.'.format(path), + path.to_JSON() + ) diff --git a/opendc/api/v1/simulations/simulationId/paths/pathId/sections/__init__.py b/opendc/api/v1/simulations/simulationId/paths/pathId/sections/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/paths/pathId/sections/endpoint.py b/opendc/api/v1/simulations/simulationId/paths/pathId/sections/endpoint.py new file mode 100644 index 00000000..775de346 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/paths/pathId/sections/endpoint.py @@ -0,0 +1,43 @@ +from opendc.models.section import Section +from opendc.models.path import Path +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Path's Sections.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'pathId': 'int' + } + ) + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Path from the database + + path = Path.from_primary_key((request.params_path['pathId'],)) + + # Make sure this Path exists + + if not path.exists(): + return Response(404, '{} not found.'.format(path)) + + # Make sure this user is authorized to view this Path's Sections + + if not path.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing Sections for {}.'.format(path)) + + # Get and return the Sections + + sections = Section.query('path_id', request.params_path['pathId']) + + return Response( + 200, + 'Successfully retrieved Sections for {}.'.format(path), + [x.to_JSON() for x in sections] + ) diff --git a/opendc/api/v1/simulations/simulationId/paths/pathId/sections/sectionId/__init__.py b/opendc/api/v1/simulations/simulationId/paths/pathId/sections/sectionId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/simulations/simulationId/paths/pathId/sections/sectionId/endpoint.py b/opendc/api/v1/simulations/simulationId/paths/pathId/sections/sectionId/endpoint.py new file mode 100644 index 00000000..9cd397d0 --- /dev/null +++ b/opendc/api/v1/simulations/simulationId/paths/pathId/sections/sectionId/endpoint.py @@ -0,0 +1,44 @@ +from opendc.models.section import Section +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Path's Sections.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'simulationId': 'int', + 'pathId': 'int', + 'sectionId': 'int' + } + ) + except exceptions.ParameterError as e: + return Response(400, e.message) + + + # Instantiate a Section from the database + + section = Section.from_primary_key((request.params_path['sectionId'],)) + + # Make sure this Section exists + + if not section.exists(): + return Response(404, '{} not found.'.format(section)) + + # Make sure this user is authorized to view this Section + + if not section.google_id_has_at_least(request.google_id, 'VIEW'): + return Response(403, 'Forbidden from viewing {}.'.format(section)) + + # Return the Section + + section.read() + + return Response( + 200, + 'Successfully retrieved {}.'.format(section), + section.to_JSON() + ) diff --git a/opendc/api/v1/specifications/__init__.py b/opendc/api/v1/specifications/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/cpus/__init__.py b/opendc/api/v1/specifications/cpus/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/cpus/endpoint.py b/opendc/api/v1/specifications/cpus/endpoint.py new file mode 100644 index 00000000..5c856255 --- /dev/null +++ b/opendc/api/v1/specifications/cpus/endpoint.py @@ -0,0 +1,17 @@ +from opendc.models.cpu import CPU +from opendc.util.rest import Response + +def GET(request): + """Get a list of the specifications of all CPUs.""" + + # Get the CPUs + + cpus = CPU.query() + + # Return the CPUs + + return Response( + 200, + 'Successfully retrieved CPUs.', + [x.to_JSON() for x in cpus] + ) diff --git a/opendc/api/v1/specifications/cpus/id/__init__.py b/opendc/api/v1/specifications/cpus/id/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/cpus/id/endpoint.py b/opendc/api/v1/specifications/cpus/id/endpoint.py new file mode 100644 index 00000000..158576cb --- /dev/null +++ b/opendc/api/v1/specifications/cpus/id/endpoint.py @@ -0,0 +1,33 @@ +from opendc.models.cpu import CPU +from opendc.util import exceptions +from opendc.util.rest import Response + +def GET(request): + """Get the specs of a CPU.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'id': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a CPU and make sure it exists + + cpu = CPU.from_primary_key((request.params_path['id'],)) + + if not cpu.exists(): + return Response(404, '{} not found.'.format(cpu)) + + # Return this CPU + + return Response( + 200, + 'Successfully retrieved {}.'.format(cpu), + cpu.to_JSON() + ) diff --git a/opendc/api/v1/specifications/failure-models/__init__.py b/opendc/api/v1/specifications/failure-models/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/failure-models/endpoint.py b/opendc/api/v1/specifications/failure-models/endpoint.py new file mode 100644 index 00000000..2530d032 --- /dev/null +++ b/opendc/api/v1/specifications/failure-models/endpoint.py @@ -0,0 +1,17 @@ +from opendc.models.failure_model import FailureModel +from opendc.util.rest import Response + +def GET(request): + """Get all Failure Models.""" + + # Get the FailureModels + + failure_models = FailureModel.query() + + # Return the FailureModels + + return Response( + 200, + 'Successfully retrieved FailureModels.', + [x.to_JSON() for x in failure_models] + ) diff --git a/opendc/api/v1/specifications/failure-models/id/__init__.py b/opendc/api/v1/specifications/failure-models/id/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/failure-models/id/endpoint.py b/opendc/api/v1/specifications/failure-models/id/endpoint.py new file mode 100644 index 00000000..8a7d2e1d --- /dev/null +++ b/opendc/api/v1/specifications/failure-models/id/endpoint.py @@ -0,0 +1,33 @@ +from opendc.models.failure_model import FailureModel +from opendc.util import exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Failure Model.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'id': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a FailureModel and make sure it exists + + failure_model = FailureModel.from_primary_key((request.params_path['id'],)) + + if not failure_model.exists(): + return Response(404, '{} not found.'.format(failure_model)) + + # Return this FailureModel + + return Response( + 200, + 'Successfully retrieved {}.'.format(failure_model), + failure_model.to_JSON() + ) diff --git a/opendc/api/v1/specifications/gpus/__init__.py b/opendc/api/v1/specifications/gpus/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/gpus/endpoint.py b/opendc/api/v1/specifications/gpus/endpoint.py new file mode 100644 index 00000000..8728d203 --- /dev/null +++ b/opendc/api/v1/specifications/gpus/endpoint.py @@ -0,0 +1,17 @@ +from opendc.models.gpu import GPU +from opendc.util.rest import Response + +def GET(request): + """Get a list of the specifications of all GPUs.""" + + # Get the GPUs + + gpus = GPU.query() + + # Return the GPUs + + return Response( + 200, + 'Successfully retrieved GPUs.', + [x.to_JSON() for x in gpus] + ) diff --git a/opendc/api/v1/specifications/gpus/id/__init__.py b/opendc/api/v1/specifications/gpus/id/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/gpus/id/endpoint.py b/opendc/api/v1/specifications/gpus/id/endpoint.py new file mode 100644 index 00000000..41b5a9e4 --- /dev/null +++ b/opendc/api/v1/specifications/gpus/id/endpoint.py @@ -0,0 +1,33 @@ +from opendc.models.gpu import GPU +from opendc.util import exceptions +from opendc.util.rest import Response + +def GET(request): + """Get the specs of a GPU.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'id': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a GPU and make sure it exists + + gpu = GPU.from_primary_key((request.params_path['id'],)) + + if not gpu.exists(): + return Response(404, '{} not found.'.format(gpu)) + + # Return this GPU + + return Response( + 200, + 'Successfully retrieved {}.'.format(gpu), + gpu.to_JSON() + ) diff --git a/opendc/api/v1/specifications/memories/__init__.py b/opendc/api/v1/specifications/memories/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/memories/endpoint.py b/opendc/api/v1/specifications/memories/endpoint.py new file mode 100644 index 00000000..b275b6f0 --- /dev/null +++ b/opendc/api/v1/specifications/memories/endpoint.py @@ -0,0 +1,17 @@ +from opendc.models.memory import Memory +from opendc.util.rest import Response + +def GET(request): + """Get a list of the specifications of all Memories.""" + + # Get the Memories + + memories = Memory.query() + + # Return the Memories + + return Response( + 200, + 'Successfully retrieved Memories.', + [x.to_JSON() for x in memories] + ) diff --git a/opendc/api/v1/specifications/memories/id/__init__.py b/opendc/api/v1/specifications/memories/id/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/memories/id/endpoint.py b/opendc/api/v1/specifications/memories/id/endpoint.py new file mode 100644 index 00000000..3132efab --- /dev/null +++ b/opendc/api/v1/specifications/memories/id/endpoint.py @@ -0,0 +1,33 @@ +from opendc.models.memory import Memory +from opendc.util import exceptions +from opendc.util.rest import Response + +def GET(request): + """Get the specs of a Memory.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'id': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Memory and make sure it exists + + memory = Memory.from_primary_key((request.params_path['id'],)) + + if not memory.exists(): + return Response(404, '{} not found.'.format(memory)) + + # Return this Memory + + return Response( + 200, + 'Successfully retrieved {}.'.format(memory), + memory.to_JSON() + ) diff --git a/opendc/api/v1/specifications/storages/__init__.py b/opendc/api/v1/specifications/storages/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/storages/endpoint.py b/opendc/api/v1/specifications/storages/endpoint.py new file mode 100644 index 00000000..875ed987 --- /dev/null +++ b/opendc/api/v1/specifications/storages/endpoint.py @@ -0,0 +1,17 @@ +from opendc.models.storage import Storage +from opendc.util.rest import Response + +def GET(request): + """Get a list of the specifications of all Storages.""" + + # Get the Storages + + storages = Storage.query() + + # Return the Storages + + return Response( + 200, + 'Successfully retrieved Storages.', + [x.to_JSON() for x in storages] + ) diff --git a/opendc/api/v1/specifications/storages/id/__init__.py b/opendc/api/v1/specifications/storages/id/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/specifications/storages/id/endpoint.py b/opendc/api/v1/specifications/storages/id/endpoint.py new file mode 100644 index 00000000..b0d254a4 --- /dev/null +++ b/opendc/api/v1/specifications/storages/id/endpoint.py @@ -0,0 +1,33 @@ +from opendc.models.storage import Storage +from opendc.util import exceptions +from opendc.util.rest import Response + +def GET(request): + """Get the specs of a Storage.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'id': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Storage and make sure it exists + + storage = Storage.from_primary_key((request.params_path['id'],)) + + if not storage.exists(): + return Response(404, '{} not found.'.format(storage)) + + # Return this CPU + + return Response( + 200, + 'Successfully retrieved {}.'.format(storage), + storage.to_JSON() + ) diff --git a/opendc/api/v1/traces/__init__.py b/opendc/api/v1/traces/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/traces/endpoint.py b/opendc/api/v1/traces/endpoint.py new file mode 100644 index 00000000..d383b335 --- /dev/null +++ b/opendc/api/v1/traces/endpoint.py @@ -0,0 +1,17 @@ +from opendc.models.trace import Trace +from opendc.util.rest import Response + +def GET(request): + """Get all avaialble Traces.""" + + # Get the Traces + + traces = Trace.query() + + # Return the Traces + + return Response( + 200, + 'Successfully retrieved Traces', + [x.to_JSON() for x in traces] + ) diff --git a/opendc/api/v1/traces/traceId/__init__.py b/opendc/api/v1/traces/traceId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/traces/traceId/endpoint.py b/opendc/api/v1/traces/traceId/endpoint.py new file mode 100644 index 00000000..eabb23a4 --- /dev/null +++ b/opendc/api/v1/traces/traceId/endpoint.py @@ -0,0 +1,33 @@ +from opendc.models.trace import Trace +from opendc.util import exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Trace.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'traceId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Trace and make sure it exists + + trace = Trace.from_primary_key((request.params_path['traceId'],)) + + if not trace.exists(): + return Response(404, '{} not found.'.format(trace)) + + # Return this Trace + + return Response( + 200, + 'Successfully retrieved {}.'.format(trace), + trace.to_JSON() + ) diff --git a/opendc/api/v1/traces/traceId/tasks/__init__.py b/opendc/api/v1/traces/traceId/tasks/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/traces/traceId/tasks/endpoint.py b/opendc/api/v1/traces/traceId/tasks/endpoint.py new file mode 100644 index 00000000..6acf790c --- /dev/null +++ b/opendc/api/v1/traces/traceId/tasks/endpoint.py @@ -0,0 +1,36 @@ +from opendc.models.trace import Trace +from opendc.models.task import Task +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this Trace's Tasks.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'traceId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a Trace and make sure it exists + + trace = Trace.from_primary_key((request.params_path['traceId'],)) + + if not trace.exists(): + return Response(404, '{} not found.'.format(trace)) + + # Get and return the Tasks + + tasks = Task.query('trace_id', request.params_path['traceId']) + + return Response( + 200, + 'Successfully retrieved Tasks for {}.'.format(trace), + [x.to_JSON() for x in tasks] + ) diff --git a/opendc/api/v1/users/__init__.py b/opendc/api/v1/users/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/users/endpoint.py b/opendc/api/v1/users/endpoint.py new file mode 100644 index 00000000..1f43f665 --- /dev/null +++ b/opendc/api/v1/users/endpoint.py @@ -0,0 +1,80 @@ +from opendc.models.user import User +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Search for a User using their email address.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + query = { + 'email': 'string' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate and read a User from the database + + user = User.from_email(request.params_query['email']) + + # Make sure this User exists in the database + + if not user.exists(): + return Response(404, '{} not found'.format(user)) + + # Return this User + + return Response( + 200, + 'Successfully retrieved {}.'.format(user), + user.to_JSON() + ) + +def POST(request): + """Add a new User.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + body = { + 'user': { + 'googleId': 'string', + 'email': 'string' + } + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a User + + user = User.from_JSON(request.params_body['user']) + + # Make sure a User with this Google ID does not already exist + + if user.exists('google_id'): + user = user.from_google_id(user.google_id) + return Response(409, '{} already exists.'.format(user)) + + # Make sure this User is authorized to create this User + + if not request.google_id == user.google_id: + return Response(403, 'Fobidden from creating this User.') + + # Insert the User + + user.insert() + + # Return a JSON representation of the User + + return Response( + 200, + 'Successfully created {}'.format(user), + user.to_JSON() + ) diff --git a/opendc/api/v1/users/userId/__init__.py b/opendc/api/v1/users/userId/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/users/userId/authorizations/__init__.py b/opendc/api/v1/users/userId/authorizations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/api/v1/users/userId/authorizations/endpoint.py b/opendc/api/v1/users/userId/authorizations/endpoint.py new file mode 100644 index 00000000..2320456f --- /dev/null +++ b/opendc/api/v1/users/userId/authorizations/endpoint.py @@ -0,0 +1,41 @@ +from opendc.models.authorization import Authorization +from opendc.models.user import User +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def GET(request): + """Get this User's Authorizations.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'userId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a User and make sure they exist + + user = User.from_primary_key((request.params_path['userId'],)) + + if not user.exists(): + return Response(404, '{} not found.'.format(user)) + + # Make sure this requester is allowed to retrieve this User's Authorizations + + if not user.google_id_has_at_least(request.google_id, 'OWN'): + return Response(403, 'Forbidden from retrieving Authorizations for {}.'.format(user)) + + # Return this User's Authorizations + + authorizations = Authorization.query('user_id', request.params_path['userId']) + + return Response( + 200, + 'Successfully retrieved Authorizations for {}.'.format(user), + [x.to_JSON() for x in authorizations] + ) diff --git a/opendc/api/v1/users/userId/endpoint.py b/opendc/api/v1/users/userId/endpoint.py new file mode 100644 index 00000000..e4edc107 --- /dev/null +++ b/opendc/api/v1/users/userId/endpoint.py @@ -0,0 +1,121 @@ +from opendc.models.user import User +from opendc.util import database, exceptions +from opendc.util.rest import Response + +def DELETE(request): + """Delete this user.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'userId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a User and make sure they exist + + user = User.from_primary_key((request.params_path['userId'],)) + + if not user.exists(): + return Response(404, '{} not found'.format(user)) + + # Make sure this User is allowed to delete this User + + if not user.google_id_has_at_least(request.google_id, 'OWN'): + return Response(403, 'Forbidden from deleting {}.'.format(user)) + + # Delete this User + + user.delete() + + # Return this User + + return Response( + 200, + 'Succesfully deleted {}'.format(user), + user.to_JSON() + ) + +def GET(request): + """Get this User.""" + + # Make sure required parameters are there + + try: + request.check_required_parameters( + path = { + 'userId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a User and make sure they exist + + user = User.from_primary_key((request.params_path['userId'],)) + + if not user.exists(): + return Response(404, '{} not found.'.format(user)) + + # Return this User + + return Response( + 200, + 'Successfully retrieved {}'.format(user), + user.to_JSON(), + ) + +def PUT(request): + """Update this User's given name and/ or family name.""" + + # Make sure the required parameters are there + + try: + request.check_required_parameters( + body = { + 'user': { + 'givenName': 'string', + 'familyName': 'string' + } + }, + path = { + 'userId': 'int' + } + ) + + except exceptions.ParameterError as e: + return Response(400, e.message) + + # Instantiate a User and make sure they exist + + user = User.from_primary_key((request.params_path['userId'],)) + + if not user.exists(): + return Response(404, '{} not found.'.format(user)) + + # Make sure this User is allowed to edit this User + + if not user.google_id_has_at_least(request.google_id, 'OWN'): + return Response(403, 'Forbidden from editing {}.'.format(user)) + + # Update this User + + user.given_name = request.params_body['user']['givenName'] + user.family_name = request.params_body['user']['familyName'] + + user.update() + + # Return this User + + return Response( + 200, + 'Successfully updated {}.'.format(user), + user.to_JSON() + ) + diff --git a/opendc/models/__init__.py b/opendc/models/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/models/allowed_object.py b/opendc/models/allowed_object.py new file mode 100644 index 00000000..acd58e94 --- /dev/null +++ b/opendc/models/allowed_object.py @@ -0,0 +1,27 @@ +from opendc.models.model import Model + +class AllowedObject(Model): + + JSON_TO_PYTHON_DICT = { + 'AllowedObject': { + 'roomType': 'room_type', + 'objectType': 'object_type' + } + } + + TABLE_NAME = 'allowed_objects' + COLUMNS = ['room_type', 'object_type'] + COLUMNS_PRIMARY_KEY = ['room_type', 'object_type'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this AllowedObject.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True + + def to_JSON(self): + """Return a JSON representation of this AllowedObject.""" + + return self.object_type diff --git a/opendc/models/authorization.py b/opendc/models/authorization.py new file mode 100644 index 00000000..90c7d399 --- /dev/null +++ b/opendc/models/authorization.py @@ -0,0 +1,53 @@ +import json + +from opendc.models.model import Model +from opendc.models.user import User + +class Authorization(Model): + + JSON_TO_PYTHON_DICT = { + 'Authorization': { + 'userId': 'user_id', + 'simulationId': 'simulation_id', + 'authorizationLevel': 'authorization_level' + } + } + + TABLE_NAME = 'authorizations' + COLUMNS = ['user_id', 'simulation_id', 'authorization_level'] + COLUMNS_PRIMARY_KEY = ['user_id', 'simulation_id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this Authorization.""" + + authorization = Authorization.from_primary_key( + ( + User.from_google_id(google_id).id, + self.simulation_id + ) + ) + + if authorization is None: + return False + + return authorization.has_at_least(authorization_level) + + def has_at_least(self, required_level): + """Return True if this Authorization has at least the required level.""" + + if not self.exists(): + return False + + authorization_levels = ['VIEW', 'EDIT', 'OWN'] + + try: + index_actual = authorization_levels.index(self.authorization_level) + index_required = authorization_levels.index(required_level) + except: + return False + + if index_actual >= index_required: + return True + else: + return False + diff --git a/opendc/models/cpu.py b/opendc/models/cpu.py new file mode 100644 index 00000000..a2a0e79f --- /dev/null +++ b/opendc/models/cpu.py @@ -0,0 +1,41 @@ +from opendc.models.model import Model + +class CPU(Model): + + JSON_TO_PYTHON_DICT = { + 'CPU': { + 'id': 'id', + 'manufacturer': 'manufacturer', + 'family': 'family', + 'generation': 'generation', + 'model': 'model', + 'clockRateMhz': 'clock_rate_mhz', + 'numberOfCores': 'number_of_cores', + 'energyConsumptionW': 'energy_consumption_w', + 'failureModelId': 'failure_model_id' + } + } + + TABLE_NAME = 'cpus' + + COLUMNS = [ + 'id', + 'manufacturer', + 'family', + 'generation', + 'model', + 'clock_rate_mhz', + 'number_of_cores', + 'energy_consumption_w', + 'failure_model_id' + ] + + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this CPU.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/datacenter.py b/opendc/models/datacenter.py new file mode 100644 index 00000000..32ce1d49 --- /dev/null +++ b/opendc/models/datacenter.py @@ -0,0 +1,36 @@ +import json + +from opendc.models.model import Model +from opendc.models.section import Section +from opendc.util import database, exceptions + +class Datacenter(Model): + + JSON_TO_PYTHON_DICT = { + 'datacenter': { + 'id': 'id', + 'starred': 'starred', + 'simulationId': 'simulation_id' + } + } + + PATH = '/v1/simulations/{simulationId}/datacenters' + + TABLE_NAME = 'datacenters' + COLUMNS = ['id', 'simulation_id', 'starred'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Datacenter.""" + + # Get a Section that contains this Datacenter. It doesn't matter which one, since all Sections that have this + # Datacenter belong to the same Simulation, so the User's Authorization is the same for each one. + + try: + section = Section.query('datacenter_id', self.id)[0] + except Exception as e: + return False + + # Check the Section's Authorization + + return section.google_id_has_at_least(google_id, authorization_level) diff --git a/opendc/models/experiment.py b/opendc/models/experiment.py new file mode 100644 index 00000000..35056d0f --- /dev/null +++ b/opendc/models/experiment.py @@ -0,0 +1,51 @@ +from opendc.models.model import Model +from opendc.models.simulation import Simulation +from opendc.util import database, exceptions + +class Experiment(Model): + + JSON_TO_PYTHON_DICT = { + 'Experiment': { + 'id': 'id', + 'simulationId': 'simulation_id', + 'pathId': 'path_id', + 'traceId': 'trace_id', + 'schedulerName': 'scheduler_name', + 'name': 'name' + } + } + + TABLE_NAME = 'experiments' + COLUMNS = ['id', 'simulation_id', 'path_id', 'trace_id', 'scheduler_name', 'name'] + COLUMNS_PRIMARY_KEY = ['id'] + + def get_last_simulated_tick(self): + """Get this Experiment's last simulated tick.""" + + statement = ''' + SELECT tick + FROM task_states + WHERE experiment_id = ? + ORDER BY tick DESC + LIMIT 1 + ''' + result = database.fetchone(statement, (self.id,)) + + if result is not None: + return result[0] + + return -1 + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Experiment.""" + + # Get the Simulation + + try: + simulation = Simulation.from_primary_key((self.simulation_id,)) + except exceptions.RowNotFoundError: + return False + + # Check the Simulation's Authorization + + return simulation.google_id_has_at_least(google_id, authorization_level) diff --git a/opendc/models/failure_model.py b/opendc/models/failure_model.py new file mode 100644 index 00000000..8dd16d6c --- /dev/null +++ b/opendc/models/failure_model.py @@ -0,0 +1,23 @@ +from opendc.models.model import Model + +class FailureModel(Model): + + JSON_TO_PYTHON_DICT = { + 'FailureModel': { + 'id': 'id', + 'name': 'name', + 'rate': 'rate' + } + } + + TABLE_NAME = 'failure_models' + COLUMNS = ['id', 'name', 'rate'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this FailureModel.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/gpu.py b/opendc/models/gpu.py new file mode 100644 index 00000000..d9978ec7 --- /dev/null +++ b/opendc/models/gpu.py @@ -0,0 +1,41 @@ +from opendc.models.model import Model + +class GPU(Model): + + JSON_TO_PYTHON_DICT = { + 'GPU': { + 'id': 'id', + 'manufacturer': 'manufacturer', + 'family': 'family', + 'generation': 'generation', + 'model': 'model', + 'clockRateMhz': 'clock_rate_mhz', + 'numberOfCores': 'number_of_cores', + 'energyConsumptionW': 'energy_consumption_w', + 'failureModelId': 'failure_model_id' + } + } + + TABLE_NAME = 'gpus' + + COLUMNS = [ + 'id', + 'manufacturer', + 'family', + 'generation', + 'model', + 'clock_rate_mhz', + 'number_of_cores', + 'energy_consumption_w', + 'failure_model_id' + ] + + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this GPU.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/machine.py b/opendc/models/machine.py new file mode 100644 index 00000000..52cf221b --- /dev/null +++ b/opendc/models/machine.py @@ -0,0 +1,129 @@ +import copy + +from opendc.models.model import Model +from opendc.models.rack import Rack +from opendc.util import database, exceptions + +class Machine(Model): + + JSON_TO_PYTHON_DICT = { + 'machine': { + 'id': 'id', + 'rackId': 'rack_id', + 'position': 'position', + 'tags': 'tags', + 'cpuIds': 'cpu_ids', + 'gpuIds': 'gpu_ids', + 'memoryIds': 'memory_ids', + 'storageIds': 'storage_ids' + } + } + + PATH = '/v1/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack/machines' + + TABLE_NAME = 'machines' + COLUMNS = ['id', 'rack_id', 'position'] + COLUMNS_PRIMARY_KEY = ['id'] + + device_table_to_attribute = { + 'cpus': 'cpu_ids', + 'gpus': 'gpu_ids', + 'memories': 'memory_ids', + 'storages': 'storage_ids' + } + + def _update_devices(self, before_insert): + """Update this Machine's devices in the database.""" + + for device_table in self.device_table_to_attribute.keys(): + + # First, create the statements to execute + + statements = [] + values = [] + + # First, delete current machine-device links + + statement = 'DELETE FROM machine_{} WHERE machine_id = ?'.format(device_table) + database.execute(statement, (before_insert.id,)) + + # Then, add current ones + + for device_id in getattr(before_insert, before_insert.device_table_to_attribute[device_table]): + + statement = 'INSERT INTO machine_{} (machine_id, {}) VALUES (?, ?)'.format( + device_table, + before_insert.device_table_to_attribute[device_table][:-1] + ) + + database.execute(statement, (before_insert.id, device_id)) + + @classmethod + def from_tile_id_and_rack_position(cls, tile_id, position): + """Get a Rack from the ID of the tile its Rack is on, and its position in the Rack.""" + + try: + rack = Rack.from_tile_id(tile_id) + except: + return cls(id = -1) + + try: + statement = 'SELECT id FROM machines WHERE rack_id = ? AND position = ?' + machine_id = database.fetchone(statement, (rack.id, position))[0] + except: + return cls(id = -1) + + return cls.from_primary_key((machine_id,)) + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Machine.""" + + # Get the Rack + + try: + rack = Rack.from_primary_key((self.rack_id,)) + except exceptions.RowNotFoundError: + return False + + # Check the Rack's Authorization + + return rack.google_id_has_at_least(google_id, authorization_level) + + def insert(self): + """Insert this Machine by also updating its devices.""" + + before_insert = copy.deepcopy(self) + + super(Machine, self).insert() + + before_insert.id = self.id + self._update_devices(before_insert) + + def read(self): + """Read this Machine by also getting its CPU, GPU, Memory and Storage IDs.""" + + super(Machine, self).read() + + for device_table in self.device_table_to_attribute.keys(): + + statement = 'SELECT * FROM machine_{} WHERE machine_id = ?'.format(device_table) + results = database.fetchall(statement, (self.id,)) + + device_ids = [] + + for row in results: + device_ids.append(row[2]) + + setattr(self, self.device_table_to_attribute[device_table], device_ids) + + setattr(self, 'tags', []) + + def update(self): + """Update this Machine by also updating its devices.""" + + before_update = copy.deepcopy(self) + + super(Machine, self).update() + + before_update.id = self.id + self._update_devices(before_update) diff --git a/opendc/models/machine_state.py b/opendc/models/machine_state.py new file mode 100644 index 00000000..44bc6746 --- /dev/null +++ b/opendc/models/machine_state.py @@ -0,0 +1,79 @@ +from opendc.models.model import Model +from opendc.util import database + +class MachineState(Model): + + JSON_TO_PYTHON_DICT = { + 'MachineState': { + 'taskId': 'task_id', + 'machineId': 'machine_id', + 'temperatureC': 'temperature_c', + 'inUseMemoryMb': 'in_use_memory_mb', + 'loadFraction': 'load_fraction', + 'tick': 'tick' + } + } + + TABLE_NAME = 'machine_states' + COLUMNS = ['id', 'task_id', 'machine_id', 'experiment_id', 'tick', 'temperature_c', 'in_use_memory_mb', 'load_fraction'] + + COLUMNS_PRIMARY_KEY= ['id'] + + @classmethod + def _from_database_row(cls, row): + """Instantiate a MachineState from a database row (including tick from the TaskState).""" + + return cls( + task_id = row[1], + machine_id = row[2], + temperature_c = row[5], + in_use_memory_mb = row[6], + load_fraction = row[7], + tick = row[4] + ) + + @classmethod + def from_experiment_id(cls, experiment_id): + """Query MachineStates by their Experiment id.""" + + machine_states = [] + + statement = 'SELECT * FROM machine_states WHERE experiment_id = ?' + results = database.fetchall(statement, (experiment_id,)) + + for row in results: + machine_states.append(cls._from_database_row(row)) + + return machine_states + + @classmethod + def from_experiment_id_and_tick(cls, experiment_id, tick): + """Query MachineStates by their Experiment id and tick.""" + + machine_states = [] + + statement = 'SELECT * FROM machine_states WHERE experiment_id = ? AND machine_states.tick = ?' + results = database.fetchall(statement, (experiment_id, tick)) + + for row in results: + machine_states.append(cls._from_database_row(row)) + + return machine_states + + def read(self): + """Read this MachineState by also getting its tick.""" + + super(MachineState, self).read() + + statement = 'SELECT tick FROM task_states WHERE id = ?' + result = database.fetchone(statement, (self.task_state_id,)) + + self.tick = result[0] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this MachineState.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/memory.py b/opendc/models/memory.py new file mode 100644 index 00000000..56497bd4 --- /dev/null +++ b/opendc/models/memory.py @@ -0,0 +1,41 @@ +from opendc.models.model import Model + +class Memory(Model): + + JSON_TO_PYTHON_DICT = { + 'Memory': { + 'id': 'id', + 'manufacturer': 'manufacturer', + 'family': 'family', + 'generation': 'generation', + 'model': 'model', + 'speedMbPerS': 'speed_mb_per_s', + 'sizeMb': 'size_mb', + 'energyConsumptionW': 'energy_consumption_w', + 'failureModelId': 'failure_model_id' + } + } + + TABLE_NAME = 'memories' + + COLUMNS = [ + 'id', + 'manufacturer', + 'family', + 'generation', + 'model', + 'speed_mb_per_s', + 'size_mb', + 'energy_consumption_w', + 'failure_model_id' + ] + + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this Memory.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/model.py b/opendc/models/model.py new file mode 100644 index 00000000..e8a14e76 --- /dev/null +++ b/opendc/models/model.py @@ -0,0 +1,328 @@ +from opendc.util import database, exceptions + +class Model(object): + + # MUST OVERRIDE IN DERIVED CLASS + + JSON_TO_PYTHON_DICT = { + 'Model': { + 'jsonParameterName': 'python_parameter_name' + } + } + + PATH = '' + PATH_PARAMETERS = {} + + TABLE_NAME = '' + COLUMNS = [] + COLUMNS_PRIMARY_KEY = [] + + # INITIALIZATION + + def __init__(self, **kwargs): + """Initialize a model from its keyword arguments.""" + + for name, value in kwargs.items(): + setattr(self, name, value) + + def __repr__(self): + """Return a string representation of this object.""" + + identifiers = [] + + for attribute in self.COLUMNS_PRIMARY_KEY: + identifiers.append('{} = {}'.format(attribute, getattr(self, attribute))) + + return '{} ({})'.format( + self.TABLE_NAME[:-1].title().replace('_', ''), + '; '.join(identifiers) + ) + + # JSON CONVERSION METHODS + + @classmethod + def from_JSON(cls, json_object): + """Initialize a Model from its JSON object representation.""" + + parameters = {} + parameter_map = cls.JSON_TO_PYTHON_DICT.values()[0] + + for json_name in parameter_map: + + python_name = parameter_map[json_name] + + if json_name in json_object: + parameters[python_name] = json_object.get(json_name) + + else: + parameters[python_name] = None + + return cls(**parameters) + + def to_JSON(self): + """Return a JSON-serializable object representation of this Model.""" + + parameters = {} + parameter_map = self.JSON_TO_PYTHON_DICT.values()[0] + + for json_name in parameter_map: + + python_name = parameter_map[json_name] + + if hasattr(self, python_name): + parameters[json_name] = getattr(self, python_name) + + else: + parameters[json_name] = None + + return parameters + + + # API CALL GENERATION + + def generate_api_call(self, path_parameters, token): + """Return a message that can be executed by a Request to recreate this object.""" + + return { + 'id': 0, + 'path': self.PATH, + 'method': 'POST', + 'parameters': { + 'body': { + self.JSON_TO_PYTHON_DICT.keys()[0]: self.to_JSON() + }, + 'path': path_parameters, + 'query': {} + }, + 'token': token + } + + # SQL STATEMENT GENERATION METHODS + + @classmethod + def _generate_insert_columns_string(cls): + """Generate a SQLite insertion columns string for this Model""" + + return ', '.join(cls.COLUMNS) + + @classmethod + def _generate_insert_placeholders_string(cls): + """Generate a SQLite insertion placeholders string for this Model.""" + + return ', '.join(['?'] * len(cls.COLUMNS)) + + @classmethod + def _generate_primary_key_string(cls): + """Generate the SQLite primary key string for this Model.""" + + return ' AND '.join(['{} = ?'.format(x) for x in cls.COLUMNS_PRIMARY_KEY]) + + @classmethod + def _generate_update_columns_string(cls): + """Generate a SQLite updatable columns string for this Model.""" + + return ', '.join( + ['{} = ?'.format(x) for x in cls.COLUMNS if not x in cls.COLUMNS_PRIMARY_KEY] + ) + + # SQL TUPLE GENERATION METHODS + + def _generate_insert_columns_tuple(self): + """Generate the tuple of insertion column values for this object.""" + + value_list = [] + + for column in self.COLUMNS: + value_list.append(getattr(self, column, None)) + + return tuple(value_list) + + def _generate_primary_key_tuple(self): + """Generate the tuple of primary key values for this object.""" + + primary_key_list = [] + + for column in self.COLUMNS_PRIMARY_KEY: + primary_key_list.append(getattr(self, column, None)) + + return tuple(primary_key_list) + + def _generate_update_columns_tuple(self): + """Generate the tuple of updatable column values for this object.""" + + value_list = [] + + for column in [x for x in self.COLUMNS if not x in self.COLUMNS_PRIMARY_KEY]: + value_list.append(getattr(self, column, None)) + + return tuple(value_list) + + # DATABASE HELPER METHODS + + @classmethod + def _from_database(cls, statement, values): + """Initialize a Model by fetching it from the database.""" + + parameters = {} + model_from_database = database.fetchone(statement, values) + + if model_from_database is None: + return None + + for i in range(len(cls.COLUMNS)): + parameters[cls.COLUMNS[i]] = model_from_database[i] + + return cls(**parameters) + + # PUBLIC DATABASE INTERACTION METHODS + + @classmethod + def from_primary_key(cls, primary_key_tuple): + """Initialize a Model by fetching it by its primary key tuple. + + If the primary key does not exist in the database, return a stub. + """ + + query = 'SELECT * FROM {} WHERE {}'.format( + cls.TABLE_NAME, + cls._generate_primary_key_string() + ) + + # Return an instantiation of the Model with values from the row if it exists + + model = cls._from_database(query, primary_key_tuple) + if model is not None: + return model + + # Return a stub instantiation of the Model with just the primary key if it does not + + parameters = {} + for i, column in enumerate(cls.COLUMNS_PRIMARY_KEY): + parameters[column] = primary_key_tuple[i] + + return cls(**parameters) + + @classmethod + def query(cls, column_name=None, value=None): + """Return all instances of the Model in the database where column_name = value.""" + + if column_name is not None and value is not None: + statement = 'SELECT * FROM {} WHERE {} = ?'.format(cls.TABLE_NAME, column_name) + database_models = database.fetchall(statement, (value,)) + + else: + statement = 'SELECT * FROM {}'.format(cls.TABLE_NAME) + database_models = database.fetchall(statement) + + models = [] + + for database_model in database_models: + + parameters = {} + for i, parameter in enumerate(cls.COLUMNS): + parameters[parameter] = database_model[i] + + models.append(cls(**parameters)) + + return models + + def delete(self): + """Delete this Model from the database.""" + + self.read() + + statement = 'DELETE FROM {} WHERE {}'.format( + self.TABLE_NAME, + self._generate_primary_key_string() + ) + + values = self._generate_primary_key_tuple() + + database.execute(statement, values) + + def exists(self, column=None): + """Return True if this Model exists in the database. + + Check the primary key by default, or a column if one is specified. + """ + + query = """ + SELECT EXISTS ( + SELECT 1 FROM {} + WHERE {} + LIMIT 1 + ) + """ + + if column is None: + query = query.format( + self.TABLE_NAME, + self._generate_primary_key_string() + ) + values = self._generate_primary_key_tuple() + + else: + query = query.format( + self.TABLE_NAME, + '{} = ?'.format(column) + ) + values = (getattr(self, column),) + + return database.fetchone(query, values)[0] == 1 + + def insert(self): + """Insert this Model into the database.""" + + if hasattr(self, 'id'): + self.id = None + + self.insert_with_id() + + def insert_with_id(self): + """Insert this Model into the database without removing its id.""" + + statement = 'INSERT INTO {} ({}) VALUES ({})'.format( + self.TABLE_NAME, + self._generate_insert_columns_string(), + self._generate_insert_placeholders_string() + ) + + values = self._generate_insert_columns_tuple() + + try: + last_row_id = database.execute(statement, values) + except Exception as e: + raise exceptions.ForeignKeyError(e.message) + + if 'id' in self.COLUMNS_PRIMARY_KEY: + setattr(self, 'id', last_row_id) + self.read() + + def read(self): + """Read this Model's non-primary key attributes from the database.""" + + if not self.exists(): + raise exceptions.RowNotFoundError(self.TABLE_NAME) + + database_model = self.from_primary_key(self._generate_primary_key_tuple()) + + for attribute in self.COLUMNS: + setattr(self, attribute, getattr(database_model, attribute)) + + return self + + def update(self): + """Update this Model's non-primary key attributes in the database.""" + + statement = 'UPDATE {} SET {} WHERE {}'.format( + self.TABLE_NAME, + self._generate_update_columns_string(), + self._generate_primary_key_string() + ) + + values = self._generate_update_columns_tuple() + self._generate_primary_key_tuple() + + try: + database.execute(statement, values) + except Exception as e: + raise exceptions.ForeignKeyError(e.message) diff --git a/opendc/models/object.py b/opendc/models/object.py new file mode 100644 index 00000000..4103107a --- /dev/null +++ b/opendc/models/object.py @@ -0,0 +1,20 @@ +from opendc.models.model import Model +from opendc.util import database, exceptions + +class Object(Model): + + JSON_TO_PYTHON_DICT = { + 'Object': { + 'id': 'id', + 'type': 'type' + } + } + + TABLE_NAME = 'objects' + COLUMNS = ['id', 'type'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Tile.""" + + return True diff --git a/opendc/models/path.py b/opendc/models/path.py new file mode 100644 index 00000000..6ce29b9b --- /dev/null +++ b/opendc/models/path.py @@ -0,0 +1,35 @@ +from opendc.models.authorization import Authorization +from opendc.models.model import Model +from opendc.models.user import User +from opendc.util import database, exceptions + +class Path(Model): + + JSON_TO_PYTHON_DICT = { + 'Path': { + 'id': 'id', + 'simulationId': 'simulation_id', + 'name': 'name', + 'datetimeCreated': 'datetime_created' + } + } + + TABLE_NAME = 'paths' + COLUMNS = ['id', 'simulation_id', 'name', 'datetime_created'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Path.""" + + # Get the User id + + try: + user_id = User.from_google_id(google_id).read().id + except exceptions.RowNotFoundError: + return False + + # Check the Authorization + + authorization = Authorization.from_primary_key((user_id, self.simulation_id)) + + return authorization.has_at_least(authorization_level) diff --git a/opendc/models/queued_experiment.py b/opendc/models/queued_experiment.py new file mode 100644 index 00000000..fbaed9cb --- /dev/null +++ b/opendc/models/queued_experiment.py @@ -0,0 +1,15 @@ +from opendc.models.model import Model +from opendc.models.experiment import Experiment +from opendc.util import database, exceptions + +class QueuedExperiment(Model): + + JSON_TO_PYTHON_DICT = { + 'QueuedExperiment': { + 'experimentId': 'experiment_id' + } + } + + TABLE_NAME = 'queued_experiments' + COLUMNS = ['experiment_id'] + COLUMNS_PRIMARY_KEY = ['experiment_id'] diff --git a/opendc/models/rack.py b/opendc/models/rack.py new file mode 100644 index 00000000..a9aeeff9 --- /dev/null +++ b/opendc/models/rack.py @@ -0,0 +1,61 @@ +from opendc.models.model import Model +from opendc.models.tile import Tile +from opendc.models.object import Object +from opendc.util import database, exceptions + +class Rack(Model): + + JSON_TO_PYTHON_DICT = { + 'rack': { + 'id': 'id', + 'name': 'name', + 'capacity': 'capacity', + 'powerCapacityW': 'power_capacity_w' + } + } + + PATH = '/v1/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack' + + TABLE_NAME = 'racks' + COLUMNS = ['id', 'name', 'capacity', 'power_capacity_w'] + COLUMNS_PRIMARY_KEY = ['id'] + + @classmethod + def from_tile_id(cls, tile_id): + """Get a Rack from the ID of the Tile it's on.""" + + tile = Tile.from_primary_key((tile_id,)) + + if not tile.exists(): + return Rack(id = -1) + + return cls.from_primary_key((tile.object_id,)) + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Rack.""" + + # Get the Tile + + try: + tile = Tile.query('object_id', self.id)[0] + except: + return False + + # Check the Tile's Authorization + + return tile.google_id_has_at_least(google_id, authorization_level) + + def insert(self): + """Insert a Rack by first inserting an object.""" + + obj = Object(type = 'RACK') + obj.insert() + + self.id = obj.id + self.insert_with_id() + + def delete(self): + """Delete a Rack by deleting its associated object.""" + + obj = Object.from_primary_key((self.id,)) + obj.delete() diff --git a/opendc/models/rack_state.py b/opendc/models/rack_state.py new file mode 100644 index 00000000..77cafd95 --- /dev/null +++ b/opendc/models/rack_state.py @@ -0,0 +1,74 @@ +from opendc.models.model import Model +from opendc.util import database + +class RackState(Model): + + JSON_TO_PYTHON_DICT = { + 'RackState': { + 'rackId': 'rack_id', + 'loadFraction': 'load_fraction', + 'tick': 'tick' + } + } + + @classmethod + def _from_database_row(cls, row): + """Instantiate a RackState from a database row.""" + + return cls( + rack_id = row[0], + load_fraction = row[1], + tick = row[2] + ) + + @classmethod + def from_experiment_id(cls, experiment_id): + """Query RackStates by their Experiment id.""" + + rack_states = [] + + statement = ''' + SELECT racks.id, avg(machine_states.load_fraction), machine_states.tick + FROM racks + JOIN machines ON racks.id = machines.rack_id + JOIN machine_states ON machines.id = machine_states.machine_id + WHERE machine_states.experiment_id = ? + GROUP BY machine_states.tick, racks.id + ''' + results = database.fetchall(statement, (experiment_id,)) + + for row in results: + rack_states.append(cls._from_database_row(row)) + + return rack_states + + @classmethod + def from_experiment_id_and_tick(cls, experiment_id, tick): + """Query RackStates by their Experiment id.""" + + rack_states = [] + + statement = ''' + SELECT racks.id, avg(machine_states.load_fraction), machine_states.tick + FROM racks + JOIN machines ON racks.id = machines.rack_id + JOIN machine_states ON machines.id = machine_states.machine_id + WHERE machine_states.experiment_id = ? + AND machine_states.tick = ? + GROUP BY machine_states.tick, racks.id + ''' + results = database.fetchall(statement, (experiment_id, tick)) + + for row in results: + rack_states.append(cls._from_database_row(row)) + + return rack_states + + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this RackState.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/room.py b/opendc/models/room.py new file mode 100644 index 00000000..b8be88f9 --- /dev/null +++ b/opendc/models/room.py @@ -0,0 +1,34 @@ +from opendc.models.model import Model +from opendc.models.datacenter import Datacenter +from opendc.util import database, exceptions + +class Room(Model): + + JSON_TO_PYTHON_DICT = { + 'room': { + 'id': 'id', + 'datacenterId': 'datacenter_id', + 'name': 'name', + 'roomType': 'type' + } + } + + PATH = '/v1/simulations/{simulationId}/datacenters/{datacenterId}/rooms' + + TABLE_NAME = 'rooms' + COLUMNS = ['id', 'name', 'datacenter_id', 'type'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Room.""" + + # Get the Datacenter + + try: + datacenter = Datacenter.from_primary_key((self.datacenter_id,)) + except exceptions.RowNotFoundError: + return False + + # Check the Datacenter's Authorization + + return datacenter.google_id_has_at_least(google_id, authorization_level) diff --git a/opendc/models/room_state.py b/opendc/models/room_state.py new file mode 100644 index 00000000..7dd151e6 --- /dev/null +++ b/opendc/models/room_state.py @@ -0,0 +1,82 @@ +from opendc.models.model import Model +from opendc.util import database + +class RoomState(Model): + + JSON_TO_PYTHON_DICT = { + 'RoomState': { + 'roomId': 'room_id', + 'loadFraction': 'load_fraction', + 'tick': 'tick' + } + } + + @classmethod + def _from_database_row(cls, row): + """Instantiate a RoomState from a database row.""" + + return cls( + room_id = row[0], + load_fraction = row[1], + tick = row[2] + ) + + @classmethod + def from_experiment_id(cls, experiment_id): + """Query RoomStates by their Experiment id.""" + + room_states = [] + + statement = ''' + SELECT rooms.id, avg(machine_states.load_fraction), machine_states.tick + FROM rooms + JOIN tiles ON rooms.id = tiles.room_id + JOIN objects ON tiles.object_id = objects.id + JOIN racks ON objects.id = racks.id + JOIN machines ON racks.id = machines.rack_id + JOIN machine_states ON machines.id = machine_states.machine_id + WHERE objects.type = "RACK" + AND machine_states.experiment_id = ? + GROUP BY machine_states.tick, rooms.id + ''' + results = database.fetchall(statement, (experiment_id,)) + + for row in results: + room_states.append(cls._from_database_row(row)) + + return room_states + + @classmethod + def from_experiment_id_and_tick(cls, experiment_id, tick): + """Query RoomStates by their Experiment id.""" + + room_states = [] + + statement = ''' + SELECT rooms.id, avg(machine_states.load_fraction), machine_states.tick + FROM rooms + JOIN tiles ON rooms.id = tiles.room_id + JOIN objects ON tiles.object_id = objects.id + JOIN racks ON objects.id = racks.id + JOIN machines ON racks.id = machines.rack_id + JOIN machine_states ON machines.id = machine_states.machine_id + WHERE objects.type = "RACK" + AND machine_states.experiment_id = ? + AND machine_states.tick = ? + GROUP BY rooms.id + ''' + results = database.fetchall(statement, (experiment_id, tick)) + + for row in results: + room_states.append(cls._from_database_row(row)) + + return room_states + + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this RackState.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/room_type.py b/opendc/models/room_type.py new file mode 100644 index 00000000..73b06cc1 --- /dev/null +++ b/opendc/models/room_type.py @@ -0,0 +1,21 @@ +from opendc.models.model import Model + +class RoomType(Model): + + JSON_TO_PYTHON_DICT = { + 'RoomType': { + 'name': 'name' + } + } + + TABLE_NAME = 'room_types' + COLUMNS = ['name'] + COLUMNS_PRIMARY_KEY = ['name'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this RoomType.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/scheduler.py b/opendc/models/scheduler.py new file mode 100644 index 00000000..9d78ec6f --- /dev/null +++ b/opendc/models/scheduler.py @@ -0,0 +1,18 @@ +from opendc.models.model import Model + +class Scheduler(Model): + + JSON_TO_PYTHON_DICT = { + 'Scheduler': { + 'name': 'name' + } + } + + TABLE_NAME = 'schedulers' + COLUMNS = ['name'] + COLUMNS_PRIMARY_KEY = ['name'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Scheduler.""" + + return authorization_level not in ['EDIT', 'OWN'] diff --git a/opendc/models/section.py b/opendc/models/section.py new file mode 100644 index 00000000..5434cdfb --- /dev/null +++ b/opendc/models/section.py @@ -0,0 +1,32 @@ +from opendc.models.model import Model +from opendc.models.path import Path +from opendc.util import database, exceptions + +class Section(Model): + + JSON_TO_PYTHON_DICT = { + 'Section': { + 'id': 'id', + 'pathId': 'path_id', + 'datacenterId': 'datacenter_id', + 'startTick': 'start_tick' + } + } + + TABLE_NAME = 'sections' + COLUMNS = ['id', 'path_id', 'datacenter_id', 'start_tick'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Section.""" + + # Get the Path + + try: + path = Path.from_primary_key((self.path_id,)) + except exceptions.RowNotFoundError: + return False + + # Check the Path's Authorization + + return path.google_id_has_at_least(google_id, authorization_level) diff --git a/opendc/models/simulation.py b/opendc/models/simulation.py new file mode 100644 index 00000000..b698867c --- /dev/null +++ b/opendc/models/simulation.py @@ -0,0 +1,41 @@ +import json + +from opendc.models.authorization import Authorization +from opendc.models.model import Model +from opendc.models.user import User +from opendc.util import database, exceptions + +class Simulation(Model): + + JSON_TO_PYTHON_DICT = { + 'Simulation': { + 'id': 'id', + 'name': 'name', + 'datetimeCreated': 'datetime_created', + 'datetimeLastEdited': 'datetime_last_edited' + } + } + + TABLE_NAME = 'simulations' + COLUMNS = ['id', 'datetime_created', 'datetime_last_edited', 'name'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Simulation.""" + + # Get the User id + + try: + user_id = User.from_google_id(google_id).read().id + except exceptions.RowNotFoundError: + return False + + # Get the Simulation id + + simulation_id = self.id + + # Check the Authorization + + authorization = Authorization.from_primary_key((user_id, simulation_id)) + + return authorization.has_at_least(authorization_level) diff --git a/opendc/models/storage.py b/opendc/models/storage.py new file mode 100644 index 00000000..e82fa0b3 --- /dev/null +++ b/opendc/models/storage.py @@ -0,0 +1,41 @@ +from opendc.models.model import Model + +class Storage(Model): + + JSON_TO_PYTHON_DICT = { + 'Storage': { + 'id': 'id', + 'manufacturer': 'manufacturer', + 'family': 'family', + 'generation': 'generation', + 'model': 'model', + 'speedMbPerS': 'speed_mb_per_s', + 'sizeMb': 'size_mb', + 'energyConsumptionW': 'energy_consumption_w', + 'failureModelId': 'failure_model_id' + } + } + + TABLE_NAME = 'storages' + + COLUMNS = [ + 'id', + 'manufacturer', + 'family', + 'generation', + 'model', + 'speed_mb_per_s', + 'size_mb', + 'energy_consumption_w', + 'failure_model_id' + ] + + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this Storage.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/task.py b/opendc/models/task.py new file mode 100644 index 00000000..8ec03568 --- /dev/null +++ b/opendc/models/task.py @@ -0,0 +1,22 @@ +from opendc.models.model import Model + +class Task(Model): + + JSON_TO_PYTHON_DICT = { + 'Task': { + 'id': 'id', + 'startTick': 'start_tick', + 'totalFlopCount': 'total_flop_count', + 'traceId': 'trace_id', + 'taskDependencyId': 'task_dependency_id' + } + } + + TABLE_NAME = 'tasks' + COLUMNS = ['id', 'start_tick', 'total_flop_count', 'trace_id', 'task_dependency_id'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Task.""" + + return authorization_level not in ['EDIT', 'OWN'] diff --git a/opendc/models/task_duration.py b/opendc/models/task_duration.py new file mode 100644 index 00000000..31334040 --- /dev/null +++ b/opendc/models/task_duration.py @@ -0,0 +1,47 @@ +from opendc.models.model import Model +from opendc.util import database + +class TaskDuration(Model): + + JSON_TO_PYTHON_DICT = { + 'TaskDuration': { + 'taskId': 'task_id', + 'duration': 'duration' + } + } + + @classmethod + def _from_database_row(cls, row): + """Instantiate a RoomState from a database row.""" + + return cls( + task_id = row[0], + duration = row[1] + ) + + @classmethod + def from_experiment_id(cls, experiment_id): + """Query RoomStates by their Experiment id.""" + + room_states = [] + + statement = ''' + SELECT task_id, MAX(tick) - MIN(tick) as duration FROM task_states + WHERE experiment_id = ? + GROUP BY task_id + ''' + + results = database.fetchall(statement, (experiment_id,)) + + for row in results: + room_states.append(cls._from_database_row(row)) + + return room_states + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this TaskDuration.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/task_state.py b/opendc/models/task_state.py new file mode 100644 index 00000000..6569ec79 --- /dev/null +++ b/opendc/models/task_state.py @@ -0,0 +1,49 @@ +from opendc.models.model import Model +from opendc.util import database + +class TaskState(Model): + + JSON_TO_PYTHON_DICT = { + 'TaskState': { + 'id': 'id', + 'taskId': 'task_id', + 'experimentId': 'experiment_id', + 'tick': 'tick', + 'flopsLeft': 'flops_left' + } + } + + TABLE_NAME = 'task_states' + + COLUMNS = ['id', 'task_id', 'experiment_id', 'tick', 'flops_left'] + COLUMNS_PRIMARY_KEY = ['id'] + + @classmethod + def from_experiment_id_and_tick(cls, experiment_id, tick): + """Query Task States by their Experiment id and tick.""" + + task_states = [] + + statement = 'SELECT * FROM task_states WHERE experiment_id = ? AND tick = ?' + results = database.fetchall(statement, (experiment_id, tick)) + + for row in results: + task_states.append( + cls( + id = row[0], + task_id = row[1], + experiment_id = row[2], + tick = row[3], + flops_left = row[4] + ) + ) + + return task_states + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the Use rhas at least the given auth level over this TaskState.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models/tile.py b/opendc/models/tile.py new file mode 100644 index 00000000..95445419 --- /dev/null +++ b/opendc/models/tile.py @@ -0,0 +1,47 @@ +from opendc.models.model import Model +from opendc.models.room import Room +from opendc.models.object import Object +from opendc.util import database, exceptions + +class Tile(Model): + + JSON_TO_PYTHON_DICT = { + 'tile': { + 'id': 'id', + 'roomId': 'room_id', + 'objectId': 'object_id', + 'objectType': 'object_type', + 'positionX': 'position_x', + 'positionY': 'position_y' + } + } + + PATH = '/v1/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles' + + TABLE_NAME = 'tiles' + COLUMNS = ['id', 'position_x', 'position_y', 'room_id', 'object_id'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Tile.""" + + # Get the Room + + try: + room = Room.from_primary_key((self.room_id,)) + except exceptions.RowNotFoundError: + return False + + # Check the Room's Authorization + + return room.google_id_has_at_least(google_id, authorization_level) + + def read(self): + """Read this Tile by also getting its associated object type.""" + + super(Tile, self).read() + + if self.object_id is not None: + + obj = Object.from_primary_key((self.object_id,)) + self.object_type = obj.type diff --git a/opendc/models/trace.py b/opendc/models/trace.py new file mode 100644 index 00000000..ce8d4923 --- /dev/null +++ b/opendc/models/trace.py @@ -0,0 +1,19 @@ +from opendc.models.model import Model + +class Trace(Model): + + JSON_TO_PYTHON_DICT = { + 'Trace': { + 'id': 'id', + 'name': 'name' + } + } + + TABLE_NAME = 'traces' + COLUMNS = ['id', 'name'] + COLUMNS_PRIMARY_KEY = ['id'] + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the user has at least the given auth level over this Trace.""" + + return authorization_level not in ['EDIT', 'OWN'] diff --git a/opendc/models/user.py b/opendc/models/user.py new file mode 100644 index 00000000..9c716470 --- /dev/null +++ b/opendc/models/user.py @@ -0,0 +1,49 @@ +import json + +from opendc.models.model import Model + +class User(Model): + + JSON_TO_PYTHON_DICT = { + 'User': { + 'id': 'id', + 'googleId': 'google_id', + 'email': 'email', + 'givenName': 'given_name', + 'familyName': 'family_name' + } + } + + TABLE_NAME = 'users' + COLUMNS = ['id', 'google_id', 'email', 'given_name', 'family_name'] + COLUMNS_PRIMARY_KEY = ['id'] + + @classmethod + def from_google_id(cls, google_id): + """Initialize a User by fetching them by their google id.""" + + user = cls._from_database('SELECT * FROM users WHERE google_id = ?', (google_id,)) + + if user is not None: + return user + + return User() + + @classmethod + def from_email(cls, email): + """Initialize a User by fetching them by their email.""" + + user = cls._from_database('SELECT * FROM users WHERE email = ?', (email,)) + + if user is not None: + return user + + return User() + + def google_id_has_at_least(self, google_id, authorization_level): + """Return True if the User has at least the given auth level over this User.""" + + if authorization_level in ['EDIT', 'OWN']: + return google_id == self.google_id + + return True diff --git a/opendc/util/__init__.py b/opendc/util/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/util/database.py b/opendc/util/database.py new file mode 100644 index 00000000..16fff5f0 --- /dev/null +++ b/opendc/util/database.py @@ -0,0 +1,82 @@ +from datetime import datetime +import json +import sqlite3 + +# Get keys from config file +with open('/var/www/opendc.ewi.tudelft.nl/web-server/config/keys.json') as file: + KEYS = json.load(file) + +DATETIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S' + +def execute(statement, t): + """Open a database connection and execute the statement.""" + + # Connect to the database + connection = sqlite3.connect(KEYS['DATABASE_LOCATION']) + cursor = connection.cursor() + + # Turn on foreign key checks + cursor.execute('pragma foreign_keys=ON') + + # Execute the statement + cursor.execute(statement, t) + + # Get the id + database_id = cursor.execute('SELECT last_insert_rowid()').fetchone()[0] + + # Disconnect from the database + connection.commit() + connection.close() + + # Return the id + return database_id + +def fetchone(statement, t=None): + """Open a database connection and return the first row matched by the SELECT statement.""" + + # Connect to the database + connection = sqlite3.connect(KEYS['DATABASE_LOCATION']) + cursor = connection.cursor() + + # Execute the SELECT statement + + if t is not None: + cursor.execute(statement, t) + else: + cursor.execute(statement) + + value = cursor.fetchone() + + # Disconnect from the database and return + connection.close() + return value + +def fetchall(statement, t=None): + """Open a database connection and return all rows matched by the SELECT statement.""" + + # Connect to the database + connection = sqlite3.connect(KEYS['DATABASE_LOCATION']) + cursor = connection.cursor() + + # Execute the SELECT statement + + if t is not None: + cursor.execute(statement, t) + else: + cursor.execute(statement) + + values = cursor.fetchall() + + # Disconnect from the database and return + connection.close() + return values + +def datetime_to_string(datetime_to_convert): + """Return a database-compatible string representation of the given datetime object.""" + + return datetime_to_convert.strftime(DATETIME_STRING_FORMAT) + +def string_to_datetime(string_to_convert): + """Return a datetime corresponding to the given string representation.""" + + return datetime.strptime(string_to_convert, DATETIME_STRING_FORMAT) diff --git a/opendc/util/exceptions.py b/opendc/util/exceptions.py new file mode 100644 index 00000000..56a04ab9 --- /dev/null +++ b/opendc/util/exceptions.py @@ -0,0 +1,61 @@ +class RequestInitializationError(Exception): + """Raised when a Request cannot successfully be initialized""" + +class UnimplementedEndpointError(RequestInitializationError): + """Raised when a Request path does not point to a module.""" + +class MissingRequestParameterError(RequestInitializationError): + """Raised when a Request does not contain one or more required parameters.""" + +class UnsupportedMethodError(RequestInitializationError): + """Raised when a Request does not use a supported REST method. + + The method must be in all-caps, supported by REST, and implemented by the module. + """ + +class AuthorizationTokenError(RequestInitializationError): + """Raised when an authorization token is not correctly verified.""" + +class ForeignKeyError(Exception): + """Raised when a foreign key constraint is not met.""" + +class RowNotFoundError(Exception): + """Raised when a database row is not found.""" + + def __init__(self, table_name): + super(RowNotFoundError, self).__init__( + 'Row in `{}` table not found.'.format(table_name) + ) + + self.table_name = table_name + +class ParameterError(Exception): + """Raised when a paramter is either missing or incorrectly typed.""" + +class IncorrectParameterError(ParameterError): + """Raised when a parameter is of the wrong type.""" + + def __init__(self, parameter_name, parameter_location): + super(IncorrectParameterError, self).__init__( + 'Incorrectly typed `{}` {} parameter.'.format( + parameter_name, + parameter_location + ) + ) + + self.parameter_name = parameter_name + self.parameter_location = parameter_location + +class MissingParameterError(ParameterError): + """Raised when a parameter is missing.""" + + def __init__(self, parameter_name, parameter_location): + super(MissingParameterError, self).__init__( + 'Missing required `{}` {} parameter.'.format( + parameter_name, + parameter_location + ) + ) + + self.parameter_name = parameter_name + self.parameter_location = parameter_location diff --git a/opendc/util/parameter_checker.py b/opendc/util/parameter_checker.py new file mode 100644 index 00000000..32cd6777 --- /dev/null +++ b/opendc/util/parameter_checker.py @@ -0,0 +1,90 @@ +from opendc.util import database, exceptions + +def _missing_parameter(params_required, params_actual, parent=''): + """Recursively search for the first missing parameter.""" + + for param_name in params_required: + + if not param_name in params_actual: + return '{}.{}'.format(parent, param_name) + + param_required = params_required.get(param_name) + param_actual = params_actual.get(param_name) + + if isinstance(param_required, dict): + + param_missing = _missing_parameter( + param_required, + param_actual, + param_name + ) + + if param_missing is not None: + return '{}.{}'.format(parent, param_missing) + + return None + +def _incorrect_parameter(params_required, params_actual, parent=''): + """Recursively make sure each parameter is of the correct type.""" + + for param_name in params_required: + + param_required = params_required.get(param_name) + param_actual = params_actual.get(param_name) + + if isinstance(param_required, dict): + + param_incorrect = _incorrect_parameter( + param_required, + param_actual, + param_name + ) + + if param_incorrect is not None: + return '{}.{}'.format(parent, param_incorrect) + + else: + + if param_required == 'datetime': + try: + database.string_to_datetime(param_actual) + except: + return '{}.{}'.format(parent, param_name) + + if param_required == 'int' and not isinstance(param_actual, int): + return '{}.{}'.format(parent, param_name) + + if param_required == 'string' and not isinstance(param_actual, basestring): + return '{}.{}'.format(parent, param_name) + + if param_required.startswith('list') and not isinstance(param_actual, list): + return '{}.{}'.format(parent, param_name) + +def _format_parameter(parameter): + """Format the output of a parameter check.""" + + parts = parameter.split('.') + inner = ['["{}"]'.format(x) for x in parts[2:]] + return parts[1] + ''.join(inner) + +def check(request, **kwargs): + """Return True if all required parameters are there.""" + + for location, params_required in kwargs.iteritems(): + + params_actual = getattr(request, 'params_{}'.format(location)) + + missing_parameter = _missing_parameter(params_required, params_actual) + if missing_parameter is not None: + raise exceptions.MissingParameterError( + _format_parameter(missing_parameter), + location + ) + + incorrect_parameter = _incorrect_parameter(params_required, params_actual) + if incorrect_parameter is not None: + raise exceptions.IncorrectParameterError( + _format_parameter(incorrect_parameter), + location + ) + diff --git a/opendc/util/rest.py b/opendc/util/rest.py new file mode 100644 index 00000000..a52b0082 --- /dev/null +++ b/opendc/util/rest.py @@ -0,0 +1,137 @@ +import importlib +import json +import os +import sys + +from oauth2client import client, crypt + +from opendc.util import exceptions, parameter_checker + +with open('/var/www/opendc.ewi.tudelft.nl/web-server/config/keys.json') as file: + KEYS = json.load(file) + +class Request(object): + """WebSocket message to REST request mapping.""" + + def __init__(self, message): + """"Initialize a Request from a socket message.""" + + # Get the Request parameters from the message + + try: + self.message = message + + self.id = message['id'] + + self.path = message['path'] + self.method = message['method'] + + self.params_body = message['parameters']['body'] + self.params_path = message['parameters']['path'] + self.params_query = message['parameters']['query'] + + self.token = message['token'] + + except KeyError as exception: + raise exceptions.MissingRequestParameterError(exception) + + # Parse the path and import the appropriate module + + try: + self.path = message['path'].encode('ascii', 'ignore').strip('/') + + module_base = 'opendc.api.{}.endpoint' + module_path = self.path.translate(None, '{}').replace('/', '.') + + self.module = importlib.import_module(module_base.format(module_path)) + + except UnicodeError as e: + raise exceptions.UnimplementedEndpointError('Non-ASCII path') + + except ImportError: + raise exceptions.UnimplementedEndpointError( + 'Unimplemented endpoint: {}.'.format(self.path) + ) + + # Check the method + + if not self.method in ['POST', 'GET', 'PUT', 'PATCH', 'DELETE']: + raise exceptions.UnsupportedMethodError('Non-rest method: {}'.format(self.method)) + + if not hasattr(self.module, self.method): + raise exceptions.UnsupportedMethodError('Unimplemented method at endpoint {}: {}'.format(self.path, self.method)) + + # Verify the user + + try: + self.google_id = self._verify_token(self.token) + + except crypt.AppIdentityError as e: + raise exceptions.AuthorizationTokenError(e.message) + + def _verify_token(self, token): + """Return the ID of the signed-in user. + + Or throw an Exception if the token is invalid. + """ + + try: + idinfo = client.verify_id_token(token, KEYS['OAUTH_CLIENT_ID']) + except Exception as e: + raise crypt.AppIdentityError('Exception caught trying to verify ID token: {}'.format(e)) + + if idinfo['aud'] != KEYS['OAUTH_CLIENT_ID']: + raise crypt.AppIdentityError('Unrecognized client.') + + if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: + raise crypt.AppIdentityError('Wrong issuer.') + + return idinfo['sub'] + + def check_required_parameters(self, **kwargs): + """Raise an error if a parameter is missing or of the wrong type.""" + + parameter_checker.check(self, **kwargs) + + def process(self): + """Process the Request and return a Response.""" + + method = getattr(self.module, self.method) + + response = method(self) + response.id = self.id + + return response + + def to_JSON(self): + """Return a JSON representation of this Request""" + + self.message['id'] = 0 + self.message['token'] = None + + return json.dumps(self.message) + +class Response(object): + """Response to websocket mapping""" + + def __init__(self, status_code, status_description, content=None): + """Initialize a new Response.""" + + self.status = { + 'code': status_code, + 'description': status_description + } + self.content = content + + def to_JSON(self): + """"Return a JSON representation of this Response""" + + data = { + 'id': self.id, + 'status': self.status + } + + if self.content is not None: + data['content'] = self.content + + return json.dumps(data) diff --git a/static/index.html b/static/index.html new file mode 100644 index 00000000..39bb6460 --- /dev/null +++ b/static/index.html @@ -0,0 +1,55 @@ + + + + +
+Sign out + + -- cgit v1.2.3 From c96e6ffafb62bde1e08987b1fdf3c0786487f6ec Mon Sep 17 00:00:00 2001 From: Georgios Andreadis Date: Tue, 24 Jan 2017 12:06:09 +0100 Subject: Initial commit --- .bowerrc | 3 + .gitignore | 14 + README.md | 18 + bower.json | 17 + gulpfile.js | 138 ++ package.json | 38 + src/404.html | 26 + src/app.html | 457 ++++++ src/favicon.ico | Bin 0 -> 99678 bytes src/humans.txt | 27 + src/img/app/coolingitem.png | Bin 0 -> 2853 bytes src/img/app/loading.gif | Bin 0 -> 36550 bytes src/img/app/node-cpu.png | Bin 0 -> 4062 bytes src/img/app/node-gpu.png | Bin 0 -> 2227 bytes src/img/app/node-memory.png | Bin 0 -> 1980 bytes src/img/app/node-network.png | Bin 0 -> 3058 bytes src/img/app/node-storage.png | Bin 0 -> 4038 bytes src/img/app/psu.png | Bin 0 -> 1523 bytes src/img/app/rack-energy.png | Bin 0 -> 893 bytes src/img/app/rack-space.png | Bin 0 -> 957 bytes src/img/datacenter-drawing.png | Bin 0 -> 219576 bytes src/img/email-icon.png | Bin 0 -> 14761 bytes src/img/favicon.png | Bin 0 -> 2788 bytes src/img/github-icon.png | Bin 0 -> 6441 bytes src/img/logo.png | Bin 0 -> 2825 bytes src/img/mockups/construction-node.png | Bin 0 -> 71201 bytes src/img/mockups/simulation-node.png | Bin 0 -> 63291 bytes src/img/mockups/simulation-room.png | Bin 0 -> 45941 bytes src/img/opendc-splash.png | Bin 0 -> 304805 bytes src/img/portraits/aiosup.png | Bin 0 -> 111629 bytes src/img/portraits/gandreadis.png | Bin 0 -> 118477 bytes src/img/portraits/loverweel.png | Bin 0 -> 107768 bytes src/img/portraits/mbijman.png | Bin 0 -> 111670 bytes src/img/stakeholders/Developer.png | Bin 0 -> 11411 bytes src/img/stakeholders/Manager.png | Bin 0 -> 9946 bytes src/img/stakeholders/Researcher.png | Bin 0 -> 10984 bytes src/img/stakeholders/Sales.png | Bin 0 -> 10074 bytes src/img/stakeholders/Student.png | Bin 0 -> 12960 bytes src/img/technologies/arrow.png | Bin 0 -> 2153 bytes src/img/technologies/cogs-icon.png | Bin 0 -> 11500 bytes src/img/technologies/database-icon.png | Bin 0 -> 7848 bytes src/img/technologies/webserver-icon.png | Bin 0 -> 5762 bytes src/img/technologies/www-icon.png | Bin 0 -> 11205 bytes src/img/tudelfticon.png | Bin 0 -> 4387 bytes src/index.html | 411 ++++++ src/navbar.html | 18 + src/profile.html | 63 + src/projects.html | 94 ++ src/robots.txt | 4 + src/scripts/colors.ts | 43 + src/scripts/controllers/connection/api.ts | 1724 ++++++++++++++++++++++ src/scripts/controllers/connection/cache.ts | 85 ++ src/scripts/controllers/connection/socket.ts | 76 + src/scripts/controllers/mapcontroller.ts | 520 +++++++ src/scripts/controllers/modes/building.ts | 114 ++ src/scripts/controllers/modes/node.ts | 297 ++++ src/scripts/controllers/modes/object.ts | 297 ++++ src/scripts/controllers/modes/room.ts | 382 +++++ src/scripts/controllers/scaleindicator.ts | 45 + src/scripts/controllers/simulation/chart.ts | 241 +++ src/scripts/controllers/simulation/statecache.ts | 205 +++ src/scripts/controllers/simulation/taskview.ts | 64 + src/scripts/controllers/simulation/timeline.ts | 161 ++ src/scripts/controllers/simulationcontroller.ts | 586 ++++++++ src/scripts/definitions.ts | 318 ++++ src/scripts/error404.entry.ts | 26 + src/scripts/main.entry.ts | 69 + src/scripts/profile.entry.ts | 40 + src/scripts/projects.entry.ts | 651 ++++++++ src/scripts/serverconnection.ts | 59 + src/scripts/splash.entry.ts | 160 ++ src/scripts/tests/util.spec.ts | 326 ++++ src/scripts/user.ts | 76 + src/scripts/util.ts | 600 ++++++++ src/scripts/views/layers/dcobject.ts | 252 ++++ src/scripts/views/layers/dcprogressbar.ts | 99 ++ src/scripts/views/layers/gray.ts | 145 ++ src/scripts/views/layers/grid.ts | 59 + src/scripts/views/layers/hover.ts | 129 ++ src/scripts/views/layers/layer.ts | 8 + src/scripts/views/layers/room.ts | 177 +++ src/scripts/views/layers/roomtext.ts | 68 + src/scripts/views/layers/wall.ts | 62 + src/scripts/views/mapview.ts | 373 +++++ src/styles/404.less | 147 ++ src/styles/main.less | 1190 +++++++++++++++ src/styles/navbar.less | 158 ++ src/styles/profile.less | 22 + src/styles/projects.less | 391 +++++ src/styles/splash.less | 436 ++++++ src/unit-tests.html | 15 + tsconfig.json | 45 + tslint.json | 75 + typings.json | 16 + 94 files changed, 12360 insertions(+) create mode 100644 .bowerrc create mode 100644 .gitignore create mode 100644 README.md create mode 100644 bower.json create mode 100644 gulpfile.js create mode 100644 package.json create mode 100644 src/404.html create mode 100644 src/app.html create mode 100644 src/favicon.ico create mode 100644 src/humans.txt create mode 100644 src/img/app/coolingitem.png create mode 100644 src/img/app/loading.gif create mode 100644 src/img/app/node-cpu.png create mode 100644 src/img/app/node-gpu.png create mode 100644 src/img/app/node-memory.png create mode 100644 src/img/app/node-network.png create mode 100644 src/img/app/node-storage.png create mode 100644 src/img/app/psu.png create mode 100644 src/img/app/rack-energy.png create mode 100644 src/img/app/rack-space.png create mode 100644 src/img/datacenter-drawing.png create mode 100644 src/img/email-icon.png create mode 100644 src/img/favicon.png create mode 100644 src/img/github-icon.png create mode 100644 src/img/logo.png create mode 100644 src/img/mockups/construction-node.png create mode 100644 src/img/mockups/simulation-node.png create mode 100644 src/img/mockups/simulation-room.png create mode 100644 src/img/opendc-splash.png create mode 100644 src/img/portraits/aiosup.png create mode 100644 src/img/portraits/gandreadis.png create mode 100644 src/img/portraits/loverweel.png create mode 100644 src/img/portraits/mbijman.png create mode 100644 src/img/stakeholders/Developer.png create mode 100644 src/img/stakeholders/Manager.png create mode 100644 src/img/stakeholders/Researcher.png create mode 100644 src/img/stakeholders/Sales.png create mode 100644 src/img/stakeholders/Student.png create mode 100644 src/img/technologies/arrow.png create mode 100644 src/img/technologies/cogs-icon.png create mode 100644 src/img/technologies/database-icon.png create mode 100644 src/img/technologies/webserver-icon.png create mode 100644 src/img/technologies/www-icon.png create mode 100644 src/img/tudelfticon.png create mode 100644 src/index.html create mode 100644 src/navbar.html create mode 100644 src/profile.html create mode 100644 src/projects.html create mode 100644 src/robots.txt create mode 100644 src/scripts/colors.ts create mode 100644 src/scripts/controllers/connection/api.ts create mode 100644 src/scripts/controllers/connection/cache.ts create mode 100644 src/scripts/controllers/connection/socket.ts create mode 100644 src/scripts/controllers/mapcontroller.ts create mode 100644 src/scripts/controllers/modes/building.ts create mode 100644 src/scripts/controllers/modes/node.ts create mode 100644 src/scripts/controllers/modes/object.ts create mode 100644 src/scripts/controllers/modes/room.ts create mode 100644 src/scripts/controllers/scaleindicator.ts create mode 100644 src/scripts/controllers/simulation/chart.ts create mode 100644 src/scripts/controllers/simulation/statecache.ts create mode 100644 src/scripts/controllers/simulation/taskview.ts create mode 100644 src/scripts/controllers/simulation/timeline.ts create mode 100644 src/scripts/controllers/simulationcontroller.ts create mode 100644 src/scripts/definitions.ts create mode 100644 src/scripts/error404.entry.ts create mode 100644 src/scripts/main.entry.ts create mode 100644 src/scripts/profile.entry.ts create mode 100644 src/scripts/projects.entry.ts create mode 100644 src/scripts/serverconnection.ts create mode 100644 src/scripts/splash.entry.ts create mode 100644 src/scripts/tests/util.spec.ts create mode 100644 src/scripts/user.ts create mode 100644 src/scripts/util.ts create mode 100644 src/scripts/views/layers/dcobject.ts create mode 100644 src/scripts/views/layers/dcprogressbar.ts create mode 100644 src/scripts/views/layers/gray.ts create mode 100644 src/scripts/views/layers/grid.ts create mode 100644 src/scripts/views/layers/hover.ts create mode 100644 src/scripts/views/layers/layer.ts create mode 100644 src/scripts/views/layers/room.ts create mode 100644 src/scripts/views/layers/roomtext.ts create mode 100644 src/scripts/views/layers/wall.ts create mode 100644 src/scripts/views/mapview.ts create mode 100644 src/styles/404.less create mode 100644 src/styles/main.less create mode 100644 src/styles/navbar.less create mode 100644 src/styles/profile.less create mode 100644 src/styles/projects.less create mode 100644 src/styles/splash.less create mode 100644 src/unit-tests.html create mode 100644 tsconfig.json create mode 100644 tslint.json create mode 100644 typings.json diff --git a/.bowerrc b/.bowerrc new file mode 100644 index 00000000..0bee623f --- /dev/null +++ b/.bowerrc @@ -0,0 +1,3 @@ +{ + "directory": "build/bower_components" +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..28aa7add --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# NPM dependencies +node_modules/ + +# Generated assets +build/ + +# TypeScript specific file +src/scripts/.baseDir.ts + +# TypeScript definitions +typings/ + +# Yarn lockfile +yarn.lock \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..22a173ae --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# OpenDC Front End +## Initial setup +We use the NPM package repository to manage our third-party dependencies on the frontend. To fetch and install these dependencies, you'll need to have the [Node.js](https://nodejs.org/en/) environment installed. + +For easier fetching, we recommend the [Yarn Package Manager](https://yarnpkg.com), but the standard NPM tool will suffice, too. You can get your build setup installed by executing the following two commands: + + $ npm install -g yarn + $ npm install -g gulp + +You may need to prepend these commands with `sudo`, if you are on a Debian-based Linux machine. If you're having trouble giving NPM the necessary permissions on such a machine, have a look at [this NPM documentation page](https://docs.npmjs.com/getting-started/fixing-npm-permissions). + +## Building the project +Run the following commands from this directory to fetch dependencies and compile the code of the frontend side: + +``` +$ yarn +$ gulp +``` diff --git a/bower.json b/bower.json new file mode 100644 index 00000000..5f9eda2b --- /dev/null +++ b/bower.json @@ -0,0 +1,17 @@ +{ + "name": "open-dc", + "description": "Datacenter simulator", + "authors": [ + "Georgios Andreadis " + ], + "license": "UNLICENSED", + "homepage": "https://opendc.ewi.tudelft.nl", + "private": true, + "dependencies": { + "EaselJS": "^0.8.2", + "PreloadJS": "^0.6.2", + "TweenJS": "^0.6.2", + "bootstrap": "^3.3.6", + "c3": "^0.4.11" + } +} diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 00000000..612decf6 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,138 @@ +'use strict'; + +const gulp = require('gulp'); +const notify = require('gulp-notify'); +const source = require('vinyl-source-stream'); +const es = require('event-stream'); +const less = require('gulp-less'); +const browserify = require('browserify'); +const tsify = require('tsify'); +const gulpTypings = require("gulp-typings"); +const rename = require('gulp-rename'); +const processHTML = require('gulp-processhtml'); +const del = require('del'); +const bower = require('gulp-bower'); + + +/** + * STYLES + */ +const stylesRootDir = './src/styles/'; +const stylesDestDir = './build/styles/'; + +const styleFileNames = ['main', 'splash', 'projects', 'profile', 'navbar', '404']; +const styleFilePaths = styleFileNames.map(function (fileName) { + return stylesRootDir + fileName + '.less'; +}); + +gulp.task('styles', function () { + return gulp.src(styleFilePaths) + .pipe(less()) + .pipe(gulp.dest(stylesDestDir)) + .pipe(notify({message: 'Styles task complete', onLast: true})); +}); + + +/** + * SCRIPTS + */ +const scriptsRootDir = './src/scripts/'; +const scriptsDestDir = './build/scripts/'; + +const postfix = '.entry'; +const scriptsFileNames = ['splash', 'main', 'projects', 'profile', 'error404']; +const scriptsFilePaths = scriptsFileNames.map(function (fileName) { + return scriptsRootDir + fileName + postfix + '.ts'; +}); + +gulp.task('scripts', function () { + var tasks = scriptsFilePaths.map(function (entry, index) { + return browserify({entries: [entry]}) + .plugin(tsify, {insertGlobals: true}) + .bundle() + .pipe(source(scriptsFileNames[index] + postfix + '.js')) + .pipe(gulp.dest(scriptsDestDir)); + }); + return es.merge.apply(null, tasks) + .pipe(notify({message: 'Scripts task complete', onLast: true})); +}); + + +/** + * TYPESCRIPT DEFINITIONS + */ +gulp.task("typings", function () { + return gulp.src("./typings.json") + .pipe(gulpTypings()) + .pipe(notify({message: 'Typings task complete'})); +}); + + +/** + * HTML + */ +const htmlRootDir = './src/'; +const htmlDestDir = './build/'; + +const htmlFileNames = ['index', 'app', 'projects', 'profile', '404']; +const htmlFilePaths = htmlFileNames.map(function (fileName) { + return htmlRootDir + fileName + '.html'; +}); + +gulp.task('html', function () { + return gulp.src(htmlFilePaths) + .pipe(processHTML()) + .pipe(gulp.dest(htmlDestDir)) + .pipe(notify({message: 'HTML task complete', onLast: true})); +}); + + +/** + * IMAGES + */ +const imagesRootDir = './src/img/'; +const imagesDestDir = './build/img/'; + +const imagesFilePaths = [imagesRootDir + '**/*.png', imagesRootDir + '**/*.gif']; + +gulp.task('images', function () { + return gulp.src(imagesFilePaths) + .pipe(gulp.dest(imagesDestDir)) + .pipe(notify({message: 'Images task complete', onLast: true})); +}); + + +/** + * CLEAN + */ +gulp.task('clean', function () { + return del(['./build']); +}); + + +/** + * BOWER + */ +gulp.task('bower', function () { + return bower({cmd: 'install'}, ['--allow-root']) + .pipe(notify({message: 'Bower task complete', onLast: true})); +}); + + +/** + * DEFAULT TASK + */ +gulp.task('default', ['clean', 'typings'], function () { + gulp.start('styles', 'bower', 'scripts', 'html', 'images'); +}); + + +/** + * WATCH + */ +gulp.task('watch', ['default'], function () { + gulp.watch(stylesRootDir + '**/*.less', ['styles']); + gulp.watch(scriptsRootDir + '**/*.ts', ['scripts']); + gulp.watch(htmlRootDir + '**/*.html', ['html']); + gulp.watch(imagesRootDir + '**/*.png', ['images']); +}); diff --git a/package.json b/package.json new file mode 100644 index 00000000..c45fcd9e --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "name": "open-dc", + "version": "0.0.1", + "description": "Datacenter simulator", + "license": "UNLICENSED", + "repository": { + "type": "git", + "url": "https://github.com/leonoverweel/open-dc.git" + }, + "dependencies": { + "bower": "^1.7.9", + "browserify": "^13.1.1", + "c3": "^0.4.11", + "del": "^2.2.2", + "event-stream": "^3.3.4", + "file-loader": "^0.9.0", + "gulp": "^3.9.1", + "gulp-bower": "^0.0.13", + "gulp-less": "^3.3.0", + "gulp-notify": "^2.2.0", + "gulp-processhtml": "^1.1.0", + "gulp-rename": "^1.2.2", + "gulp-typings": "^2.0.4", + "jquery": "^3.1.0", + "jquery-mousewheel": "^3.1.13", + "jquery.easing": "^1.4.1", + "less": "^2.7.1", + "socket.io-client": "^1.4.8", + "tsify": "^2.0.2", + "tslint": "^3.10.2", + "typescript": "^2.1.4", + "typings": "^1.3.2", + "vinyl-source-stream": "^1.1.0" + }, + "devDependencies": { + "jasmine-core": "^2.4.1" + } +} diff --git a/src/404.html b/src/404.html new file mode 100644 index 00000000..a7c0771d --- /dev/null +++ b/src/404.html @@ -0,0 +1,26 @@ + + + + + 404 Error | OpenDC + + + + +
+
Terminal -- bash
+
+
$ status
+ opendc[4264]: segfault at 0000051497be459d1 err 12 in libopendc.9.0.4
+ opendc[4269]: segfault at 000004234855fc2db err 3 in libopendc.9.0.4
+ opendc[4270]: STDERR Page does not exist +
+
+
Got lost?_
+ GET ME BACK TO OPENDC +
+
+ + + + \ No newline at end of file diff --git a/src/app.html b/src/app.html new file mode 100644 index 00000000..c267a354 --- /dev/null +++ b/src/app.html @@ -0,0 +1,457 @@ + + + + + + + OpenDC + + + + + + + + + + + + +
+ + + Sorry, but it seems your browser does not support the HTML5 canvas. + + +
+ +
+ +
+ + + + + + +
+ +
+
+
Construction
+
Simulation
+
+
Save version
+ + +
+ +
+ + + +
+ + +
+
+ 0.5m +
+ +
+ + +
+ +
+ + +
+ Test Info +
+ + +
+
+ +
+

Loading your project...

+

Fetching the DC

+
+
+
+
+ + + +
+
+
+
+
Experiments
+
+
+ + + + +
+
+ + + + +
Save & Launch
+
+
+ Previous Experiments +
+
+
Name
+
Path
+
Trace
+
Scheduler
+
+
+
+
+
+
+ + No experiments here yet... Add some with the form above! +
+ +
+
+
+ + + + + + + + + + + + + + + diff --git a/src/favicon.ico b/src/favicon.ico new file mode 100644 index 00000000..c2f40a0d Binary files /dev/null and b/src/favicon.ico differ diff --git a/src/humans.txt b/src/humans.txt new file mode 100644 index 00000000..652f9cd2 --- /dev/null +++ b/src/humans.txt @@ -0,0 +1,27 @@ +/* TEAM */ +Benevolent Dictator for Life: Alexandru Iosup. +Site: http://www.ds.ewi.tudelft.nl/~iosup/ +Twitter: aiosup. +Location: Delft, Netherlands. + +Backend Engineer: Leon Overweel. +Site: http://leonoverweel.com/ +Twitter: layon_overwhale. +Location: Delft, Netherlands. + +Frontend Engineer: Georgios Andreadis. +Site: https://github.com/gandreadis +Location: Delft, Netherlands. + +Simulation Engineer: Matthijs Bijman. +Site: https://github.com/MDBijman +Location: Delft, Netherlands. + +/* THANKS */ +Executive Producer: Vincent van Beek. +Executive Producer: Tim Hegeman. + +/* SITE */ +Standards: HTML5, CSS3, ES5 +Components: jQuery, Bootstrap, CreateJS, c3.js +Software: WebStorm, Vim, Visual Studio \ No newline at end of file diff --git a/src/img/app/coolingitem.png b/src/img/app/coolingitem.png new file mode 100644 index 00000000..16c18be0 Binary files /dev/null and b/src/img/app/coolingitem.png differ diff --git a/src/img/app/loading.gif b/src/img/app/loading.gif new file mode 100644 index 00000000..c6394822 Binary files /dev/null and b/src/img/app/loading.gif differ diff --git a/src/img/app/node-cpu.png b/src/img/app/node-cpu.png new file mode 100644 index 00000000..07cfbd31 Binary files /dev/null and b/src/img/app/node-cpu.png differ diff --git a/src/img/app/node-gpu.png b/src/img/app/node-gpu.png new file mode 100644 index 00000000..55d4fb05 Binary files /dev/null and b/src/img/app/node-gpu.png differ diff --git a/src/img/app/node-memory.png b/src/img/app/node-memory.png new file mode 100644 index 00000000..36e8a44e Binary files /dev/null and b/src/img/app/node-memory.png differ diff --git a/src/img/app/node-network.png b/src/img/app/node-network.png new file mode 100644 index 00000000..795e173b Binary files /dev/null and b/src/img/app/node-network.png differ diff --git a/src/img/app/node-storage.png b/src/img/app/node-storage.png new file mode 100644 index 00000000..7a39cb6f Binary files /dev/null and b/src/img/app/node-storage.png differ diff --git a/src/img/app/psu.png b/src/img/app/psu.png new file mode 100644 index 00000000..471af6ee Binary files /dev/null and b/src/img/app/psu.png differ diff --git a/src/img/app/rack-energy.png b/src/img/app/rack-energy.png new file mode 100644 index 00000000..1088c61b Binary files /dev/null and b/src/img/app/rack-energy.png differ diff --git a/src/img/app/rack-space.png b/src/img/app/rack-space.png new file mode 100644 index 00000000..387d7ea6 Binary files /dev/null and b/src/img/app/rack-space.png differ diff --git a/src/img/datacenter-drawing.png b/src/img/datacenter-drawing.png new file mode 100644 index 00000000..401168e3 Binary files /dev/null and b/src/img/datacenter-drawing.png differ diff --git a/src/img/email-icon.png b/src/img/email-icon.png new file mode 100644 index 00000000..ced9e175 Binary files /dev/null and b/src/img/email-icon.png differ diff --git a/src/img/favicon.png b/src/img/favicon.png new file mode 100644 index 00000000..85d74964 Binary files /dev/null and b/src/img/favicon.png differ diff --git a/src/img/github-icon.png b/src/img/github-icon.png new file mode 100644 index 00000000..1e221600 Binary files /dev/null and b/src/img/github-icon.png differ diff --git a/src/img/logo.png b/src/img/logo.png new file mode 100644 index 00000000..d743038b Binary files /dev/null and b/src/img/logo.png differ diff --git a/src/img/mockups/construction-node.png b/src/img/mockups/construction-node.png new file mode 100644 index 00000000..78ad81e8 Binary files /dev/null and b/src/img/mockups/construction-node.png differ diff --git a/src/img/mockups/simulation-node.png b/src/img/mockups/simulation-node.png new file mode 100644 index 00000000..fc56f44a Binary files /dev/null and b/src/img/mockups/simulation-node.png differ diff --git a/src/img/mockups/simulation-room.png b/src/img/mockups/simulation-room.png new file mode 100644 index 00000000..f8f80623 Binary files /dev/null and b/src/img/mockups/simulation-room.png differ diff --git a/src/img/opendc-splash.png b/src/img/opendc-splash.png new file mode 100644 index 00000000..99fd8658 Binary files /dev/null and b/src/img/opendc-splash.png differ diff --git a/src/img/portraits/aiosup.png b/src/img/portraits/aiosup.png new file mode 100644 index 00000000..30de349c Binary files /dev/null and b/src/img/portraits/aiosup.png differ diff --git a/src/img/portraits/gandreadis.png b/src/img/portraits/gandreadis.png new file mode 100644 index 00000000..403870fa Binary files /dev/null and b/src/img/portraits/gandreadis.png differ diff --git a/src/img/portraits/loverweel.png b/src/img/portraits/loverweel.png new file mode 100644 index 00000000..d12a9e86 Binary files /dev/null and b/src/img/portraits/loverweel.png differ diff --git a/src/img/portraits/mbijman.png b/src/img/portraits/mbijman.png new file mode 100644 index 00000000..decf9fdd Binary files /dev/null and b/src/img/portraits/mbijman.png differ diff --git a/src/img/stakeholders/Developer.png b/src/img/stakeholders/Developer.png new file mode 100644 index 00000000..d2638e6c Binary files /dev/null and b/src/img/stakeholders/Developer.png differ diff --git a/src/img/stakeholders/Manager.png b/src/img/stakeholders/Manager.png new file mode 100644 index 00000000..92db7459 Binary files /dev/null and b/src/img/stakeholders/Manager.png differ diff --git a/src/img/stakeholders/Researcher.png b/src/img/stakeholders/Researcher.png new file mode 100644 index 00000000..d87edd39 Binary files /dev/null and b/src/img/stakeholders/Researcher.png differ diff --git a/src/img/stakeholders/Sales.png b/src/img/stakeholders/Sales.png new file mode 100644 index 00000000..5b7c3a72 Binary files /dev/null and b/src/img/stakeholders/Sales.png differ diff --git a/src/img/stakeholders/Student.png b/src/img/stakeholders/Student.png new file mode 100644 index 00000000..a4900303 Binary files /dev/null and b/src/img/stakeholders/Student.png differ diff --git a/src/img/technologies/arrow.png b/src/img/technologies/arrow.png new file mode 100644 index 00000000..374f78bf Binary files /dev/null and b/src/img/technologies/arrow.png differ diff --git a/src/img/technologies/cogs-icon.png b/src/img/technologies/cogs-icon.png new file mode 100644 index 00000000..d19e1c20 Binary files /dev/null and b/src/img/technologies/cogs-icon.png differ diff --git a/src/img/technologies/database-icon.png b/src/img/technologies/database-icon.png new file mode 100644 index 00000000..26738e76 Binary files /dev/null and b/src/img/technologies/database-icon.png differ diff --git a/src/img/technologies/webserver-icon.png b/src/img/technologies/webserver-icon.png new file mode 100644 index 00000000..c627106e Binary files /dev/null and b/src/img/technologies/webserver-icon.png differ diff --git a/src/img/technologies/www-icon.png b/src/img/technologies/www-icon.png new file mode 100644 index 00000000..e69a54f2 Binary files /dev/null and b/src/img/technologies/www-icon.png differ diff --git a/src/img/tudelfticon.png b/src/img/tudelfticon.png new file mode 100644 index 00000000..a7a2d56a Binary files /dev/null and b/src/img/tudelfticon.png differ diff --git a/src/index.html b/src/index.html new file mode 100644 index 00000000..554a21a1 --- /dev/null +++ b/src/index.html @@ -0,0 +1,411 @@ + + + + + OpenDC + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+
+
+

OpenDC

+

+ Collaborative Datacenter Simulation and Exploration for Everybody +

+
+
+
+ +
+
+
+
+
+

The datacenter (DC) industry...

+
    +
  • Is worth over $15 bn, and growing
  • +
  • Has many hard-to-grasp concepts
  • +
  • Needs to become accessible to many
  • +
+
+ +
+

OpenDC provides...

+
    +
  • Collaborative online DC modeling
  • +
  • Diverse and effective DC simulation
  • +
  • Exploratory DC performance feedback
  • +
+
+
+
+
+
+ +
+
+
+
+

Stakeholders

+
+
+ Managers +
+

Managers

+

Seeing is deciding

+
+
+
+ Sales +
+

Sales

+

Demo concepts

+
+
+
+ DevOps +
+

DevOps

+

Develop & tune

+
+
+
+ Researchers +
+

Researchers

+

Understand & design

+
+
+
+ Students +
+

Students

+

Grasp complex concepts

+
+
+
+
+
+
+
+ +
+
+
+
+

Datacenter Modeling

+
+
+ Collaboratively... +
    +
  • Model DC layout, and room locations and types
  • +
  • Place racks in rooms and nodes in racks
  • +
  • Add real-world CPU, GPU, memory, storage and network units to each node
  • +
  • Select from diverse scheduling policies
  • +
+
+ + +
+ Mockup of the datacenter construction interface +
+ Mockup of the datacenter construction interface +
+
+
+
+
+
+
+ +
+
+
+
+

Datacenter Simulation

+
+
+ Working with OpenDC: +
    +
  • Seamlessly switch between construction and simulation modes +
  • Choose one of several predefined workloads (Big Data, Bag of Tasks, + Hadoop, etc.) +
  • Play, pause, and skip around the informative simulation timeline +
  • Visualize and demo live +
+
+
+ Mockup of the datacenter simulation interface at room level +
+ Mockup of the datacenter simulation interface at room level +
+
+
+
+
+ Key features: +
    +
  • Live load or power use metrics on building, room, and rack levels +
  • Diverse scenarios from common operation to model-based failures +
  • Retrospective performance review of datacenter simulations +
  • Compare resource management practices +
+
+
+ Mockup of the same simulation at node level +
+ Mockup of the same simulation at node level +
+
+
+
+
+
+
+ +
+
+
+
+

Technologies

+
+
+ Web browser +
+

Browser

+

HTML5 canvas, CreateJS, TypeScript, SocketIO

+
+
+
+ Web Server +
+

Web Server

+

Python, Flask, FlaskSocketIO, OpenAPI

+
+
+
+ Database +
+

Database

+

SQLite

+
+
+
+ Simulator +
+

Simulator

+

C++

+
+
+
+
+
+
+
+ +
+
+
+
+

The Team

+
+
+ +
+

Prof. dr. ir. Alexandru Iosup

+
+ Project Lead +
+
+
+
+ +
+

Leon Overweel

+
+ Project Manager and Software Engineer responsible for the web server, database, and + API + specification +
+
+
+
+ +
+

Georgios Andreadis

+
+ Software Engineer responsible for the frontend web application and splash page +
+
+
+
+ +
+

Matthijs Bijman

+
+ Software Engineer responsible for the datacenter simulator +
+
+
+
+
+
+
+
+ +
+
+
+
+

Contact

+
+ TU Delft Logo +
+ +
+ Github Icon + +
+
+
+
+
+
+
+ + + + + + + + + +
+ + + diff --git a/src/navbar.html b/src/navbar.html new file mode 100644 index 00000000..92c79000 --- /dev/null +++ b/src/navbar.html @@ -0,0 +1,18 @@ + \ No newline at end of file diff --git a/src/profile.html b/src/profile.html new file mode 100644 index 00000000..23a1f5a3 --- /dev/null +++ b/src/profile.html @@ -0,0 +1,63 @@ + + + + + + + OpenDC - Profile + + + + + + + + + + + +
+
+

Profile Settings

+
Delete my account on OpenDC
+
This does not delete your Google account, it simply disconnects it from the OpenDC app + and deletes any datacenter info that is associated with you (simulation projects you own, and any + authorizations you may have on other projects). +
+ +
+
+ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/projects.html b/src/projects.html new file mode 100644 index 00000000..c829ae00 --- /dev/null +++ b/src/projects.html @@ -0,0 +1,94 @@ + + + + + + + OpenDC - Projects + + + + + + + + + + + + + +
+
+
+
+
All Projects
+
My Projects
+
Projects shared with me
+
+
+
+ + No projects here yet... Add some with the 'New Project' button! +
+
+
+
Project name
+
Last edited
+
Access rights
+
+
+
+
+
New Project
+
+
+ +
+
+
+
+
Edit project
+
+
+ + +
Save
+
+
+ Participants +
+
+
+
+ + +
Add
+
+
+ + +
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/robots.txt b/src/robots.txt new file mode 100644 index 00000000..2329e38e --- /dev/null +++ b/src/robots.txt @@ -0,0 +1,4 @@ +User-agent: * +Disallow: /app.html +Disallow: /profile.html +Disallow: /projects.html \ No newline at end of file diff --git a/src/scripts/colors.ts b/src/scripts/colors.ts new file mode 100644 index 00000000..559b7ee3 --- /dev/null +++ b/src/scripts/colors.ts @@ -0,0 +1,43 @@ +/** + * Class serving as a color palette for the application. + */ +export class Colors { + public static GRID_COLOR = "rgba(0, 0, 0, 0.5)"; + + public static WALL_COLOR = "rgba(0, 0, 0, 1)"; + + public static ROOM_DEFAULT = "rgba(150, 150, 150, 1)"; + public static ROOM_SELECTED = "rgba(51, 153, 255, 1)"; + public static ROOM_HOVER_VALID = "rgba(51, 153, 255, 0.5)"; + public static ROOM_HOVER_INVALID = "rgba(255, 102, 0, 0.5)"; + public static ROOM_NAME_COLOR = "rgba(245, 245, 245, 1)"; + public static ROOM_TYPE_COLOR = "rgba(245, 245, 245, 1)"; + + public static RACK_BACKGROUND = "rgba(170, 170, 170, 1)"; + public static RACK_BORDER = "rgba(0, 0, 0, 1)"; + public static RACK_SPACE_BAR_BACKGROUND = "rgba(222, 235, 247, 1)"; + public static RACK_SPACE_BAR_FILL = "rgba(91, 155, 213, 1)"; + public static RACK_ENERGY_BAR_BACKGROUND = "rgba(255, 242, 204, 1)"; + public static RACK_ENERGY_BAR_FILL = "rgba(255, 192, 0, 1)"; + + public static COOLING_ITEM_BACKGROUND = "rgba(40, 50, 230, 1)"; + public static COOLING_ITEM_BORDER = "rgba(0, 0, 0, 1)"; + + public static PSU_BACKGROUND = "rgba(230, 50, 60, 1)"; + public static PSU_BORDER = "rgba(0, 0, 0, 1)"; + + public static GRAYED_OUT_AREA = "rgba(0, 0, 0, 0.6)"; + + public static INFO_BALLOON_INFO = "rgba(40, 50, 230, 1)"; + public static INFO_BALLOON_WARNING = "rgba(230, 60, 70, 1)"; + + public static INFO_BALLOON_MAP = { + "info": Colors.INFO_BALLOON_INFO, + "warning": Colors.INFO_BALLOON_WARNING + }; + + public static SIM_LOW = "rgba(197, 224, 180, 1)"; + public static SIM_MID_LOW = "rgba(255, 230, 153, 1)"; + public static SIM_MID_HIGH = "rgba(248, 203, 173, 1)"; + public static SIM_HIGH = "rgba(249, 165, 165, 1)"; +} diff --git a/src/scripts/controllers/connection/api.ts b/src/scripts/controllers/connection/api.ts new file mode 100644 index 00000000..067e3ca0 --- /dev/null +++ b/src/scripts/controllers/connection/api.ts @@ -0,0 +1,1724 @@ +/// +/// +import {Util} from "../../util"; +import {ServerConnection} from "../../serverconnection"; + + +export class APIController { + constructor(onConnect: (api: APIController) => any) { + ServerConnection.connect(() => { + onConnect(this); + }); + } + + + /// + // PATH: /users + /// + + // METHOD: GET + public getUserByEmail(email: string): Promise { + return ServerConnection.send({ + path: "/users", + method: "GET", + parameters: { + body: {}, + path: {}, + query: { + email + } + } + }); + } + + // METHOD: POST + public addUser(user: IUser): Promise { + return ServerConnection.send({ + path: "/users", + method: "POST", + parameters: { + body: { + user: user + }, + path: {}, + query: {} + } + }); + } + + /// + // PATH: /users/{id} + /// + + // METHOD: GET + public getUser(userId: number): Promise { + return ServerConnection.send({ + path: "/users/{userId}", + method: "GET", + parameters: { + body: {}, + path: { + userId + }, + query: {} + } + }); + } + + // METHOD: PUT + public updateUser(userId: number, user: IUser): Promise { + return ServerConnection.send({ + path: "/users/{userId}", + method: "PUT", + parameters: { + body: { + user: { + givenName: user.givenName, + familyName: user.familyName + } + }, + path: { + userId + }, + query: {} + } + }); + } + + // METHOD: DELETE + public deleteUser(userId: number): Promise { + return ServerConnection.send({ + path: "/users/{userId}", + method: "DELETE", + parameters: { + body: {}, + path: { + userId + }, + query: {} + } + }); + } + + /// + // PATH: /users/{userId}/authorizations + /// + + // METHOD: GET + public getAuthorizationsByUser(userId: number): Promise { + let authorizations = []; + return ServerConnection.send({ + path: "/users/{userId}/authorizations", + method: "GET", + parameters: { + body: {}, + path: { + userId + }, + query: {} + } + }).then((data: any) => { + authorizations = data; + return this.getUser(userId); + }).then((userData: any) => { + let promises = []; + authorizations.forEach((authorization: IAuthorization) => { + authorization.user = userData; + promises.push(this.getSimulation(authorization.simulationId).then((simulationData: any) => { + authorization.simulation = simulationData; + })); + }); + return Promise.all(promises); + }).then((data: any) => { + return authorizations; + }); + } + + /// + // PATH: /simulations + /// + + // METHOD: POST + public addSimulation(simulation: ISimulation): Promise { + return ServerConnection.send({ + path: "/simulations", + method: "POST", + parameters: { + body: { + simulation: Util.packageForSending(simulation) + }, + path: {}, + query: {} + } + }).then((data: any) => { + this.parseSimulationTimestamps(data); + return data; + }); + } + + /// + // PATH: /simulations/{simulationId} + /// + + // METHOD: GET + public getSimulation(simulationId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}", + method: "GET", + parameters: { + body: {}, + path: { + simulationId + }, + query: {} + } + }).then((data: any) => { + this.parseSimulationTimestamps(data); + return data; + }); + } + + // METHOD: PUT + public updateSimulation(simulation: ISimulation): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}", + method: "PUT", + parameters: { + body: { + simulation: Util.packageForSending(simulation) + }, + path: { + simulationId: simulation.id + }, + query: {} + } + }).then((data: any) => { + this.parseSimulationTimestamps(data); + return data; + }); + } + + // METHOD: DELETE + public deleteSimulation(simulationId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}", + method: "DELETE", + parameters: { + body: {}, + path: { + simulationId + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/authorizations + /// + + // METHOD: GET + public getAuthorizationsBySimulation(simulationId: number): Promise { + let authorizations = []; + return ServerConnection.send({ + path: "/simulations/{simulationId}/authorizations", + method: "GET", + parameters: { + body: {}, + path: { + simulationId + }, + query: {} + } + }).then((data: any) => { + authorizations = data; + return this.getSimulation(simulationId); + }).then((simulationData: any) => { + let promises = []; + authorizations.forEach((authorization: IAuthorization) => { + authorization.simulation = simulationData; + promises.push(this.getUser(authorization.userId).then((userData: any) => { + authorization.user = userData; + })); + }); + return Promise.all(promises); + }).then((data: any) => { + return authorizations; + }); + } + + /// + // PATH: /simulations/{simulationId}/authorizations/{userId} + /// + + // METHOD: GET + // Not needed + + // METHOD: POST + public addAuthorization(authorization: IAuthorization): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/authorizations/{userId}", + method: "POST", + parameters: { + body: { + authorization: { + authorizationLevel: authorization.authorizationLevel + } + }, + path: { + simulationId: authorization.simulationId, + userId: authorization.userId + }, + query: {} + } + }); + } + + // METHOD: PUT + public updateAuthorization(authorization: IAuthorization): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/authorizations/{userId}", + method: "PUT", + parameters: { + body: { + authorization: { + authorizationLevel: authorization.authorizationLevel + } + }, + path: { + simulationId: authorization.simulationId, + userId: authorization.userId + }, + query: {} + } + }); + } + + // METHOD: DELETE + public deleteAuthorization(authorization: IAuthorization): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/authorizations/{userId}", + method: "DELETE", + parameters: { + body: {}, + path: { + simulationId: authorization.simulationId, + userId: authorization.userId + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId} + /// + + // METHOD: GET + public getDatacenter(simulationId: number, datacenterId: number): Promise { + let datacenter; + + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + datacenterId + }, + query: {} + } + }).then((data: any) => { + datacenter = data; + + return this.getRoomsByDatacenter(simulationId, datacenterId); + }).then((data: any) => { + datacenter.rooms = data; + return datacenter; + }); + } + + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms + /// + + // METHOD: GET + public getRoomsByDatacenter(simulationId: number, datacenterId: number): Promise { + let rooms; + + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + datacenterId + }, + query: {} + } + }).then((data: any) => { + rooms = data; + + let promises = []; + rooms.forEach((room: IRoom) => { + promises.push(this.loadRoomTiles(simulationId, datacenterId, room)); + }); + return Promise.all(promises).then((data: any) => { + return rooms; + }); + }); + } + + // METHOD: POST + public addRoomToDatacenter(simulationId: number, datacenterId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms", + method: "POST", + parameters: { + body: { + room: { + id: -1, + datacenterId, + roomType: "SERVER" + } + }, + path: { + simulationId, + datacenterId + }, + query: {} + } + }).then((data: any) => { + data.tiles = []; + return data; + }); + } + + /// + // PATH: /room-types + /// + + // METHOD: GET + public getAllRoomTypes(): Promise { + return ServerConnection.send({ + path: "/room-types", + method: "GET", + parameters: { + body: {}, + path: {}, + query: {} + } + }).then((data: any) => { + let result = []; + data.forEach((roomType: any) => { + result.push(roomType.name); + }); + return result; + }); + } + + /// + // PATH: /room-types/{name}/allowed-objects + /// + + // METHOD: GET + public getAllowedObjectsByRoomType(name: string): Promise { + return ServerConnection.send({ + path: "/room-types/{name}/allowed-objects", + method: "GET", + parameters: { + body: {}, + path: { + name + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId} + /// + + // METHOD: GET + public getRoom(simulationId: number, datacenterId: number, roomId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId + }, + query: {} + } + }).then((data: any) => { + return this.loadRoomTiles(simulationId, datacenterId, data); + }); + } + + // METHOD: PUT + public updateRoom(simulationId: number, datacenterId: number, room: IRoom): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}", + method: "PUT", + parameters: { + body: { + room: Util.packageForSending(room) + }, + path: { + simulationId, + datacenterId, + roomId: room.id + }, + query: {} + } + }).then((data: any) => { + return this.loadRoomTiles(simulationId, datacenterId, data); + }); + } + + // METHOD: DELETE + public deleteRoom(simulationId: number, datacenterId: number, roomId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}", + method: "DELETE", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles + /// + + // METHOD: GET + public getTilesByRoom(simulationId: number, datacenterId: number, roomId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId + }, + query: {} + } + }).then((data: any) => { + let promises = data.map((item) => { + return this.loadTileObject(simulationId, datacenterId, roomId, item); + }); + + return Promise.all(promises).then(() => { + return data; + }) + }); + } + + // METHOD: POST + public addTileToRoom(simulationId: number, datacenterId: number, roomId: number, tile: ITile): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles", + method: "POST", + parameters: { + body: { + tile: Util.packageForSending(tile) + }, + path: { + simulationId, + datacenterId, + roomId + }, + query: {} + } + }).then((data: any) => { + return this.loadTileObject(simulationId, datacenterId, roomId, data); + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId} + /// + + // METHOD: GET + // Not needed (yet) + + // METHOD: DELETE + public deleteTile(simulationId: number, datacenterId: number, roomId: number, tileId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}", + method: "DELETE", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/cooling-item + /// + + // METHOD: GET + public getCoolingItem(simulationId: number, datacenterId: number, roomId: number, + tileId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/cooling-item", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + return this.loadFailureModel(data); + }); + } + + // METHOD: POST + public addCoolingItem(simulationId: number, datacenterId: number, roomId: number, tileId: number, + coolingItem: ICoolingItem): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/cooling-item", + method: "POST", + parameters: { + body: { + coolingItem: Util.packageForSending(coolingItem) + }, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + return this.loadFailureModel(data); + }); + } + + // METHOD: PUT + // Not needed (yet) + + // METHOD: DELETE + public deleteCoolingItem(simulationId: number, datacenterId: number, roomId: number, + tileId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/cooling-item", + method: "DELETE", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/psu + /// + + // METHOD: GET + public getPSU(simulationId: number, datacenterId: number, roomId: number, tileId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/psu", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + return this.loadFailureModel(data); + }); + } + + // METHOD: POST + public addPSU(simulationId: number, datacenterId: number, roomId: number, tileId: number, + psu: IPSU): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/psu", + method: "POST", + parameters: { + body: { + psu: Util.packageForSending(psu) + }, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + return this.loadFailureModel(data); + }); + } + + // METHOD: PUT + // Not needed (yet) + + // METHOD: DELETE + public deletePSU(simulationId: number, datacenterId: number, roomId: number, + tileId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/psu", + method: "DELETE", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack + /// + + // METHOD: GET + public getRack(simulationId: number, datacenterId: number, roomId: number, + tileId: number): Promise { + let rack = {}; + + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + rack = data; + return this.getMachinesByRack(simulationId, datacenterId, roomId, tileId); + }).then((machines: any) => { + let promises = machines.map((machine) => { + return this.loadMachineUnits(machine); + }); + + + return Promise.all(promises).then(() => { + rack["machines"] = []; + + machines.forEach((machine: IMachine) => { + rack["machines"][machine.position] = machine; + }); + + for (let i = 0; i < rack["capacity"]; i++) { + if (rack["machines"][i] === undefined) { + rack["machines"][i] = null; + } + } + + return rack; + }); + }); + } + + // METHOD: POST + public addRack(simulationId: number, datacenterId: number, roomId: number, + tileId: number, rack: IRack): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack", + method: "POST", + parameters: { + body: { + rack: Util.packageForSending(rack) + }, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + data.machines = []; + + for (let i = 0; i < data.capacity; i++) { + data.machines.push(null); + } + + return data; + }); + } + + // METHOD: PUT + public updateRack(simulationId: number, datacenterId: number, roomId: number, + tileId: number, rack: IRack): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack", + method: "PUT", + parameters: { + body: { + rack + }, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + data.machines = rack.machines; + + return data; + }); + } + + // METHOD: DELETE + public deleteRack(simulationId: number, datacenterId: number, roomId: number, + tileId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack", + method: "DELETE", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack/machines + /// + + // METHOD: GET + public getMachinesByRack(simulationId: number, datacenterId: number, roomId: number, + tileId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack/machines", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + let promises = data.map((machine) => { + return this.loadMachineUnits(machine); + }); + + return Promise.all(promises).then(() => { + return data; + }); + }); + } + + // METHOD: POST + public addMachineToRack(simulationId: number, datacenterId: number, roomId: number, + tileId: number, machine: IMachine): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack/machines", + method: "POST", + parameters: { + body: { + machine: Util.packageForSending(machine) + }, + path: { + simulationId, + datacenterId, + roomId, + tileId + }, + query: {} + } + }).then((data: any) => { + return this.loadMachineUnits(data); + }); + } + + /// + // PATH: /simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack/machines/{position} + /// + + // METHOD: GET + // Not needed (yet) + + // METHOD: PUT + public updateMachine(simulationId: number, datacenterId: number, roomId: number, + tileId: number, machine: IMachine): Promise { + machine["tags"] = []; + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack/machines/{position}", + method: "PUT", + parameters: { + body: { + machine: Util.packageForSending(machine) + }, + path: { + simulationId, + datacenterId, + roomId, + tileId, + position: machine.position + }, + query: {} + } + }).then((data: any) => { + return this.loadMachineUnits(data); + }); + } + + // METHOD: DELETE + public deleteMachine(simulationId: number, datacenterId: number, roomId: number, + tileId: number, position: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/datacenters/{datacenterId}/rooms/{roomId}/tiles/{tileId}/rack/machines/{position}", + method: "DELETE", + parameters: { + body: {}, + path: { + simulationId, + datacenterId, + roomId, + tileId, + position + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/experiments + /// + + // METHOD: GET + public getExperimentsBySimulation(simulationId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments", + method: "GET", + parameters: { + body: {}, + path: { + simulationId + }, + query: {} + } + }).then((data: any) => { + let promises = data.map((item: any) => { + return this.getTrace(item.traceId).then((traceData: any) => { + item.trace = traceData; + }); + }); + return Promise.all(promises).then(() => { + return data; + }); + }); + } + + // METHOD: POST + public addExperimentToSimulation(simulationId: number, experiment: IExperiment): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments", + method: "POST", + parameters: { + body: { + experiment: Util.packageForSending(experiment) + }, + path: { + simulationId + }, + query: {} + } + }).then((data: any) => { + return this.getTrace(data.traceId).then((traceData: any) => { + data.trace = traceData; + + return data; + }); + }); + } + + /// + // PATH: /simulations/{simulationId}/experiments/{experimentId} + /// + + // METHOD: GET + // Not needed (yet) + + // METHOD: PUT + public updateExperiment(experiment: IExperiment): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments/{experimentId}", + method: "PUT", + parameters: { + body: { + experiment: Util.packageForSending(experiment) + }, + path: { + experimentId: experiment.id, + simulationId: experiment.simulationId + }, + query: {} + } + }).then((data: any) => { + return this.getTrace(data.traceId).then((traceData: any) => { + data.trace = traceData; + + return data; + }); + }); + } + + // METHOD: DELETE + public deleteExperiment(simulationId: number, experimentId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments/{experimentId}", + method: "DELETE", + parameters: { + body: {}, + path: { + experimentId, + simulationId + }, + query: {} + } + }); + } + + /// + // PATH: /simulations/{simulationId}/experiments/{experimentId}/last-simulated-tick + /// + + // METHOD: GET + public getLastSimulatedTickByExperiment(simulationId: number, experimentId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments/{experimentId}/last-simulated-tick", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + experimentId + }, + query: {} + } + }).then((data: any) => { + return data.lastSimulatedTick; + }); + } + + /// + // PATH: /simulations/{simulationId}/experiments/{experimentId}/machine-states + /// + + // METHOD: GET + public getMachineStatesByTick(simulationId: number, experimentId: number, tick: number, + machines: {[keys: number]: IMachine}): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments/{experimentId}/machine-states", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + experimentId + }, + query: { + tick + } + } + }).then((data: any) => { + data.forEach((item: any) => { + item.machine = machines[item.machineId]; + }); + + return data; + }); + } + + /// + // PATH: /simulations/{simulationId}/experiments/{experimentId}/rack-states + /// + + // METHOD: GET + public getRackStatesByTick(simulationId: number, experimentId: number, tick: number, + racks: {[keys: number]: IRack}): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments/{experimentId}/rack-states", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + experimentId + }, + query: { + tick + } + } + }).then((data: any) => { + let promises = data.map((item: any) => { + item.rack = racks[item.rackId]; + }); + + return Promise.all(promises).then(() => { + return data; + }); + }); + } + + /// + // PATH: /simulations/{simulationId}/experiments/{experimentId}/room-states + /// + + // METHOD: GET + public getRoomStatesByTick(simulationId: number, experimentId: number, tick: number, + rooms: {[keys: number]: IRoom}): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments/{experimentId}/room-states", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + experimentId + }, + query: { + tick + } + } + }).then((data: any) => { + let promises = data.map((item: any) => { + item.room = rooms[item.roomId]; + }); + + return Promise.all(promises).then(() => { + return data; + }); + }); + } + + /// + // PATH: /simulations/{simulationId}/experiments/{experimentId}/task-states + /// + + // METHOD: GET + public getTaskStatesByTick(simulationId: number, experimentId: number, tick: number, + tasks: {[keys: number]: ITask}): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/experiments/{experimentId}/task-states", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + experimentId + }, + query: { + tick + } + } + }).then((data: any) => { + let promises = data.map((item: any) => { + item.task = tasks[item.taskId]; + }); + + return Promise.all(promises).then(() => { + return data; + }); + }); + } + + /// + // PATH: /simulations/{simulationId}/paths + /// + + // METHOD: GET + public getPathsBySimulation(simulationId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/paths", + method: "GET", + parameters: { + body: {}, + path: { + simulationId + }, + query: {} + } + }).then((data: any) => { + let promises = data.map((item: any) => { + return this.getSectionsByPath(simulationId, item.id).then((sectionsData: any) => { + item.sections = sectionsData; + }); + }); + return Promise.all(promises).then(() => { + return data; + }); + }); + } + + /// + // PATH: /simulations/{simulationId}/paths/{pathId} + /// + + // METHOD: GET + public getPath(simulationId: number, pathId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/paths/{pathId}", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + pathId + }, + query: {} + } + }).then((data: any) => { + return this.getSectionsByPath(simulationId, pathId).then((sectionsData: any) => { + data.sections = sectionsData; + return data; + }); + }); + } + + /// + // PATH: /simulations/{simulationId}/paths/{pathId}/branches + /// + + // METHOD: GET + public getBranchesByPath(simulationId: number, pathId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/paths/{pathId}/branches", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + pathId + }, + query: {} + } + }).then((data: any) => { + let promises = data.map((item: any) => { + return this.getSectionsByPath(simulationId, item.id).then((sectionsData: any) => { + item.sections = sectionsData; + }); + }); + return Promise.all(promises).then(() => { + return data; + }); + }); + } + + // METHOD: POST + public branchFromPath(simulationId: number, pathId: number, startTick: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/paths/{pathId}/branches", + method: "POST", + parameters: { + body: { + section: { + startTick + } + }, + path: { + simulationId, + pathId + }, + query: {} + } + }).then((data: any) => { + return this.getSectionsByPath(simulationId, data.id).then((sectionsData: any) => { + data.sections = sectionsData; + return data; + }); + }); + } + + /// + // PATH: /simulations/{simulationId}/paths/{pathId}/sections + /// + + // METHOD: GET + public getSectionsByPath(simulationId: number, pathId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/paths/{pathId}/sections", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + pathId + }, + query: {} + } + }).then((data: any) => { + let promises = data.map((path: ISection) => { + return this.getDatacenter(simulationId, path.datacenterId).then((datacenter: any) => { + path.datacenter = datacenter; + }); + }); + return Promise.all(promises).then(() => { + return data; + }); + }); + } + + /// + // PATH: /simulations/{simulationId}/paths/{pathId}/sections/{sectionId} + /// + + // METHOD: GET + public getSection(simulationId: number, pathId: number, sectionId: number): Promise { + return ServerConnection.send({ + path: "/simulations/{simulationId}/paths/{pathId}/sections/{sectionId}", + method: "GET", + parameters: { + body: {}, + path: { + simulationId, + pathId, + sectionId + }, + query: {} + } + }).then((data: any) => { + return this.getDatacenter(simulationId, data.datacenterId).then((datacenter: any) => { + data.datacenter = datacenter; + return data; + }); + }); + } + + /// + // PATH: /specifications/psus + /// + + // METHOD: GET + public getAllPSUSpecs(): Promise { + let psus; + return ServerConnection.send({ + path: "/specifications/psus", + method: "GET", + parameters: { + body: {}, + path: {}, + query: {} + } + }).then((data: any) => { + psus = data; + + let promises = []; + data.forEach((psu: IPSU) => { + promises.push(this.getFailureModel(psu.failureModelId)); + }); + return Promise.all(promises); + }).then((data: any) => { + return psus; + }); + } + + /// + // PATH: /specifications/psus/{id} + /// + + // METHOD: GET + public getPSUSpec(id: number): Promise { + let psu; + + return ServerConnection.send({ + path: "/specifications/psus/{id}", + method: "GET", + parameters: { + body: {}, + path: { + id + }, + query: {} + } + }).then((data: any) => { + psu = data; + return this.getFailureModel(data.failureModelId); + }).then((data: any) => { + psu.failureModel = data; + return psu; + }); + } + + /// + // PATH: /specifications/cooling-items + /// + + // METHOD: GET + public getAllCoolingItemSpecs(): Promise { + let coolingItems; + + return ServerConnection.send({ + path: "/specifications/cooling-items", + method: "GET", + parameters: { + body: {}, + path: {}, + query: {} + } + }).then((data: any) => { + coolingItems = data; + + let promises = []; + data.forEach((item: ICoolingItem) => { + promises.push(this.getFailureModel(item.failureModelId)); + }); + return Promise.all(promises); + }).then((data: any) => { + return coolingItems; + }); + } + + /// + // PATH: /specifications/cooling-items/{id} + /// + + // METHOD: GET + public getCoolingItemSpec(id: number): Promise { + let coolingItem; + + return ServerConnection.send({ + path: "/specifications/cooling-items/{id}", + method: "GET", + parameters: { + body: {}, + path: { + id + }, + query: {} + } + }).then((data: any) => { + coolingItem = data; + return this.getFailureModel(data.failureModelId); + }).then((data: any) => { + coolingItem.failureModel = data; + return coolingItem; + }); + } + + /// + // PATH: /schedulers + /// + + // METHOD: GET + public getAllSchedulers(): Promise { + return ServerConnection.send({ + path: "/schedulers", + method: "GET", + parameters: { + body: {}, + path: {}, + query: {} + } + }); + } + + /// + // PATH: /traces + /// + + // METHOD: GET + public getAllTraces(): Promise { + return ServerConnection.send({ + path: "/traces", + method: "GET", + parameters: { + body: {}, + path: {}, + query: {} + } + }); + } + + /// + // PATH: /traces/{traceId} + /// + + // METHOD: GET + public getTrace(traceId: number): Promise { + let trace; + + return ServerConnection.send({ + path: "/traces/{traceId}", + method: "GET", + parameters: { + body: {}, + path: { + traceId + }, + query: {} + } + }).then((data: any) => { + trace = data; + return this.getTasksByTrace(traceId); + }).then((data: any) => { + trace.tasks = data; + return trace; + }); + } + + /// + // PATH: /traces/{traceId}/tasks + /// + + // METHOD: GET + public getTasksByTrace(traceId: number): Promise { + return ServerConnection.send({ + path: "/traces/{traceId}/tasks", + method: "GET", + parameters: { + body: {}, + path: { + traceId + }, + query: {} + } + }); + } + + /// + // PATH: /specifications/failure-models + /// + + // METHOD: GET + public getAllFailureModels(): Promise { + return ServerConnection.send({ + path: "/specifications/failure-models", + method: "GET", + parameters: { + body: {}, + path: {}, + query: {} + } + }); + } + + /// + // PATH: /specifications/failure-models/{id} + /// + + // METHOD: GET + public getFailureModel(id: number): Promise { + return ServerConnection.send({ + path: "/specifications/failure-models/{id}", + method: "GET", + parameters: { + body: {}, + path: { + id + }, + query: {} + } + }); + } + + /// + // PATH: /specifications/[units] + /// + + // METHOD: GET + public getAllSpecificationsOfType(typePlural: string): Promise { + let specs: any; + return ServerConnection.send({ + path: "/specifications/" + typePlural, + method: "GET", + parameters: { + body: {}, + path: {}, + query: {} + } + }).then((data: any) => { + specs = data; + + let promises = []; + data.forEach((unit: INodeUnit) => { + promises.push(this.getFailureModel(unit.failureModelId)); + }); + return Promise.all(promises); + }).then((data: any) => { + return specs; + }); + } + + /// + // PATH: /specifications/[units]/{id} + /// + + // METHOD: GET + public getSpecificationOfType(typePlural: string, id: number): Promise { + let spec; + + return ServerConnection.send({ + path: "/specifications/" + typePlural + "/{id}", + method: "GET", + parameters: { + body: {}, + path: { + id + }, + query: {} + } + }).then((data: any) => { + spec = data; + return this.getFailureModel(data.failureModelId); + }).then((data: any) => { + spec.failureModel = data; + return spec; + }); + } + + + /// + // HELPER METHODS + /// + + private loadRoomTiles(simulationId: number, datacenterId: number, room: IRoom): Promise { + return this.getTilesByRoom(simulationId, datacenterId, room.id).then((data: any) => { + room.tiles = data; + return room; + }); + } + + private loadTileObject(simulationId: number, datacenterId: number, roomId: number, tile: ITile): Promise { + let promise; + + switch (tile.objectType) { + case "RACK": + promise = this.getRack(simulationId, datacenterId, roomId, tile.id).then((data: IRack) => { + tile.object = data; + }); + break; + case "PSU": + promise = this.getPSU(simulationId, datacenterId, roomId, tile.id).then((data: IPSU) => { + tile.object = data; + }); + break; + case "COOLING_ITEM": + promise = this.getCoolingItem(simulationId, datacenterId, roomId, tile.id).then((data: ICoolingItem) => { + tile.object = data; + }); + break; + default: + promise = new Promise((resolve, reject) => { + resolve(undefined); + }); + } + + return promise.then(() => { + return tile; + }) + } + + private parseSimulationTimestamps(simulation: ISimulation): void { + simulation.datetimeCreatedParsed = Util.parseDateTime(simulation.datetimeCreated); + simulation.datetimeLastEditedParsed = Util.parseDateTime(simulation.datetimeLastEdited); + } + + private loadFailureModel(data: any): Promise { + return this.getFailureModel(data.failureModelId).then((failureModel: IFailureModel) => { + data.failureModel = failureModel; + return data; + }); + } + + private loadUnitsOfType(idListName: string, objectListName: string, machine: IMachine): Promise { + machine[objectListName] = []; + + let promises = machine[idListName].map((item) => { + return this.getSpecificationOfType(objectListName, item).then((data) => { + machine[objectListName].push(data); + }); + }); + + return Promise.all(promises).then(() => { + return machine; + }) + } + + private loadMachineUnits(machine: IMachine): Promise { + let listNames = [ + { + idListName: "cpuIds", + objectListName: "cpus" + }, { + idListName: "gpuIds", + objectListName: "gpus" + }, { + idListName: "memoryIds", + objectListName: "memories" + }, { + idListName: "storageIds", + objectListName: "storages" + } + ]; + + let promises = listNames.map((item: any) => { + return this.loadUnitsOfType(item.idListName, item.objectListName, machine); + }); + + return Promise.all(promises).then(() => { + return machine; + }); + } +} \ No newline at end of file diff --git a/src/scripts/controllers/connection/cache.ts b/src/scripts/controllers/connection/cache.ts new file mode 100644 index 00000000..15517519 --- /dev/null +++ b/src/scripts/controllers/connection/cache.ts @@ -0,0 +1,85 @@ +export enum CacheStatus { + MISS, + FETCHING, + HIT, + NOT_CACHABLE +} + + +interface ICachableObject { + status: CacheStatus; + object: any; + callbacks: any[]; +} + + +export class CacheController { + private static CACHABLE_ROUTES = [ + "/specifications/psus/{id}", + "/specifications/cooling-items/{id}", + "/specifications/cpus/{id}", + "/specifications/gpus/{id}", + "/specifications/memories/{id}", + "/specifications/storages/{id}", + "/specifications/failure-models/{id}", + ]; + + // Maps every route name to a map of IDs => objects + private routeCaches: { [keys: string]: { [keys: number]: ICachableObject } }; + + + constructor() { + this.routeCaches = {}; + + CacheController.CACHABLE_ROUTES.forEach((routeName: string) => { + this.routeCaches[routeName] = {}; + }) + } + + public checkCache(request: IRequest): CacheStatus { + if (request.method === "GET" && CacheController.CACHABLE_ROUTES.indexOf(request.path) !== -1) { + if (this.routeCaches[request.path][request.parameters.path["id"]] === undefined) { + this.routeCaches[request.path][request.parameters.path["id"]] = { + status: CacheStatus.MISS, + object: null, + callbacks: [] + }; + return CacheStatus.MISS; + } else { + return this.routeCaches[request.path][request.parameters.path["id"]].status; + } + } else { + return CacheStatus.NOT_CACHABLE; + } + } + + public fetchFromCache(request: IRequest): any { + return this.routeCaches[request.path][request.parameters.path["id"]].object; + } + + public setToFetching(request: IRequest): void { + this.routeCaches[request.path][request.parameters.path["id"]].status = CacheStatus.FETCHING; + } + + public onFetch(request: IRequest, response: IResponse): any { + let pathWithoutVersion = request.path.replace(/\/v\d+/, ""); + this.routeCaches[pathWithoutVersion][request.parameters.path["id"]].status = CacheStatus.HIT; + this.routeCaches[pathWithoutVersion][request.parameters.path["id"]].object = response.content; + + this.routeCaches[pathWithoutVersion][request.parameters.path["id"]].callbacks.forEach((callback) => { + callback({ + status: { + code: 200 + }, + content: response.content, + id: request.id + }); + }); + + this.routeCaches[pathWithoutVersion][request.parameters.path["id"]].callbacks = []; + } + + public registerCallback(request: IRequest, callback): any { + this.routeCaches[request.path][request.parameters.path["id"]].callbacks.push(callback); + } +} diff --git a/src/scripts/controllers/connection/socket.ts b/src/scripts/controllers/connection/socket.ts new file mode 100644 index 00000000..b38c303f --- /dev/null +++ b/src/scripts/controllers/connection/socket.ts @@ -0,0 +1,76 @@ +import {CacheController, CacheStatus} from "./cache"; +import * as io from "socket.io-client"; + + +export class SocketController { + private static id = 1; + private _socket: SocketIOClient.Socket; + private _cacheController: CacheController; + + // Mapping from request IDs to their registered callbacks + private callbacks: { [keys: number]: (response: IResponse) => any }; + + + constructor(onConnect: () => any) { + this.callbacks = {}; + this._cacheController = new CacheController(); + + this._socket = io.connect('https://opendc.ewi.tudelft.nl:443'); + this._socket.on('connect', onConnect); + + this._socket.on('response', (jsonResponse: string) => { + let response: IResponse = JSON.parse(jsonResponse); + console.log("Response, ID:", response.id, response); + this.callbacks[response.id](response); + delete this.callbacks[response.id]; + }); + } + + /** + * Sends a request to the server socket and registers the callback to be triggered on response. + * + * @param request The request instance to be sent + * @param callback A function to be called with the response object once the socket has received a response + */ + public sendRequest(request: IRequest, callback: (response: IResponse) => any): void { + // Check local cache, in case request is for cachable GET route + let cacheStatus = this._cacheController.checkCache(request); + + if (cacheStatus === CacheStatus.HIT) { + callback({ + status: { + code: 200 + }, + content: this._cacheController.fetchFromCache(request), + id: -1 + }); + } else if (cacheStatus === CacheStatus.FETCHING) { + this._cacheController.registerCallback(request, callback); + } else if (cacheStatus === CacheStatus.MISS || cacheStatus === CacheStatus.NOT_CACHABLE) { + if (!this._socket.connected) { + console.error("Socket not connected, sending request failed"); + } + + if (cacheStatus === CacheStatus.MISS) { + this._cacheController.setToFetching(request); + + this.callbacks[SocketController.id] = (response: IResponse) => { + this._cacheController.onFetch(request, response); + callback(response); + }; + } else { + this.callbacks[SocketController.id] = callback; + } + + // Setup request object + request.id = SocketController.id; + request.token = localStorage.getItem("googleToken"); + request.path = "/v1" + request.path; + + console.log("Request, ID:", request.id, request); + this._socket.emit("request", request); + + SocketController.id++; + } + } +} \ No newline at end of file diff --git a/src/scripts/controllers/mapcontroller.ts b/src/scripts/controllers/mapcontroller.ts new file mode 100644 index 00000000..d7458852 --- /dev/null +++ b/src/scripts/controllers/mapcontroller.ts @@ -0,0 +1,520 @@ +/// +/// +import * as $ from "jquery"; +import {Colors} from "../colors"; +import {Util} from "../util"; +import {SimulationController} from "./simulationcontroller"; +import {MapView} from "../views/mapview"; +import {APIController} from "./connection/api"; +import {BuildingModeController} from "./modes/building"; +import {RoomModeController, RoomInteractionMode} from "./modes/room"; +import {ObjectModeController} from "./modes/object"; +import {NodeModeController} from "./modes/node"; +import {ScaleIndicatorController} from "./scaleindicator"; + +export var CELL_SIZE = 50; + + +export enum AppMode { + CONSTRUCTION, + SIMULATION +} + + +/** + * The current level of datacenter hierarchy that is selected + */ +export enum InteractionLevel { + BUILDING, + ROOM, + OBJECT, + NODE +} + + +/** + * Possible states that the application can be in, in terms of interaction + */ +export enum InteractionMode { + DEFAULT, + SELECT_ROOM +} + + +/** + * Class responsible for handling user input in the map. + */ +export class MapController { + public stage: createjs.Stage; + public mapView: MapView; + + public appMode: AppMode; + public interactionLevel: InteractionLevel; + public interactionMode: InteractionMode; + + public buildingModeController: BuildingModeController; + public roomModeController: RoomModeController; + public objectModeController: ObjectModeController; + public nodeModeController: NodeModeController; + + public simulationController: SimulationController; + public api: APIController; + private scaleIndicatorController: ScaleIndicatorController; + + private canvas: JQuery; + private gridDragging: boolean; + + private infoTimeOut: any; + // Current mouse coordinates on the stage canvas (mainly for zooming purposes) + private currentStageMouseX: number; + + private currentStageMouseY: number; + // Keep start coordinates relative to the grid to compute dragging offset later + private gridDragBeginX: number; + + private gridDragBeginY: number; + // Keep start coordinates on stage to compute delta values + private stageDragBeginX: number; + private stageDragBeginY: number; + + private MAX_DELTA = 5; + + + /** + * Hides all side menus except for the active one. + * + * @param activeMenu An identifier (e.g. #room-menu) for the menu container + */ + public static hideAndShowMenus(activeMenu: string): void { + $(".menu-container.level-menu").each((index: number, elem: Element) => { + if ($(elem).is(activeMenu)) { + $(elem).removeClass("hidden"); + } else { + $(elem).addClass("hidden"); + } + }); + } + + constructor(mapView: MapView) { + this.mapView = mapView; + this.stage = this.mapView.stage; + + new APIController((apiInstance: APIController) => { + this.api = apiInstance; + + this.buildingModeController = new BuildingModeController(this); + this.roomModeController = new RoomModeController(this); + this.objectModeController = new ObjectModeController(this); + this.nodeModeController = new NodeModeController(this); + this.simulationController = new SimulationController(this); + + this.scaleIndicatorController = new ScaleIndicatorController(this); + + this.canvas = $("#main-canvas"); + + $(window).on("resize", () => { + this.onWindowResize(); + }); + + this.gridDragging = false; + + this.appMode = AppMode.CONSTRUCTION; + this.interactionLevel = InteractionLevel.BUILDING; + this.interactionMode = InteractionMode.DEFAULT; + + this.setAllMenuModes(); + + this.setupMapInteractionHandlers(); + this.setupEventListeners(); + this.buildingModeController.setupEventListeners(); + this.roomModeController.setupEventListeners(); + this.objectModeController.setupEventListeners(); + this.nodeModeController.setupEventListeners(); + + this.scaleIndicatorController.init($(".scale-indicator")); + this.scaleIndicatorController.update(); + + this.mapView.roomLayer.setClickable(true); + + this.matchUserAuthLevel(); + }); + } + + /** + * Hides and shows the menu bodies corresponding to the current mode (construction or simulation). + */ + public setAllMenuModes(): void { + $(".menu-body" + (this.appMode === AppMode.CONSTRUCTION ? ".construction" : ".simulation")).show(); + $(".menu-body" + (this.appMode === AppMode.CONSTRUCTION ? ".simulation" : ".construction")).hide(); + } + + /** + * Checks whether the mapContainer is still within its legal bounds. + * + * Resets, if necessary, to the most similar still legal position. + */ + public checkAndResetCanvasMovement(): void { + if (this.mapView.mapContainer.x + this.mapView.gridLayer.gridPixelSize * + this.mapView.mapContainer.scaleX < this.mapView.canvasWidth) { + this.mapView.mapContainer.x = this.mapView.canvasWidth - this.mapView.gridLayer.gridPixelSize * + this.mapView.mapContainer.scaleX; + } + if (this.mapView.mapContainer.x > 0) { + this.mapView.mapContainer.x = 0; + } + if (this.mapView.mapContainer.y + this.mapView.gridLayer.gridPixelSize * + this.mapView.mapContainer.scaleX < this.mapView.canvasHeight) { + this.mapView.mapContainer.y = this.mapView.canvasHeight - this.mapView.gridLayer.gridPixelSize * + this.mapView.mapContainer.scaleX; + } + if (this.mapView.mapContainer.y > 0) { + this.mapView.mapContainer.y = 0; + } + } + + /** + * Checks whether the mapContainer is still within its legal bounds and generates corrections if needed. + * + * Does not change the x and y coordinates, only returns. + */ + public checkCanvasMovement(x: number, y: number, scale: number): IGridPosition { + let result: IGridPosition = {x: x, y: y}; + if (x + this.mapView.gridLayer.gridPixelSize * scale < this.mapView.canvasWidth) { + result.x = this.mapView.canvasWidth - this.mapView.gridLayer.gridPixelSize * + this.mapView.mapContainer.scaleX; + } + if (x > 0) { + result.x = 0; + } + if (y + this.mapView.gridLayer.gridPixelSize * scale < this.mapView.canvasHeight) { + result.y = this.mapView.canvasHeight - this.mapView.gridLayer.gridPixelSize * + this.mapView.mapContainer.scaleX; + } + if (y > 0) { + result.y = 0; + } + + return result; + } + + /** + * Checks whether the current interaction mode is a hover mode (meaning that there is a hover item present). + * + * @returns {boolean} Whether it is in hover mode. + */ + public isInHoverMode(): boolean { + return this.roomModeController !== undefined && + (this.interactionMode === InteractionMode.SELECT_ROOM || + this.roomModeController.roomInteractionMode === RoomInteractionMode.ADD_RACK || + this.roomModeController.roomInteractionMode === RoomInteractionMode.ADD_PSU || + this.roomModeController.roomInteractionMode === RoomInteractionMode.ADD_COOLING_ITEM); + } + + public static showConfirmDeleteDialog(itemType: string, onConfirm: () => void): void { + let modalDialog = $("#confirm-delete"); + modalDialog.find(".modal-body").text("Are you sure you want to delete this " + itemType + "?"); + + let callback = () => { + onConfirm(); + modalDialog.modal("hide"); + modalDialog.find("button.confirm").first().off("click"); + $(document).off("keypress"); + }; + + $(document).on("keypress", (event: JQueryEventObject) => { + if (event.which === 13) { + callback(); + } else if (event.which === 27) { + modalDialog.modal("hide"); + $(document).off("keypress"); + modalDialog.find("button.confirm").first().off("click"); + } + }); + modalDialog.find("button.confirm").first().on("click", callback); + modalDialog.modal("show"); + } + + /** + * Shows an informational popup in a corner of the screen, communicating a certain event. + * + * @param message The message to be displayed in the body of the popup + * @param type The severity of the message; Currently supported: "info" and "warning" + */ + public showInfoBalloon(message: string, type: string): void { + let balloon = $(".info-balloon"); + balloon.html('' + message); + let callback = () => { + balloon.fadeOut(300); + + this.infoTimeOut = undefined; + }; + const DISPLAY_TIME = 3000; + + let balloonIcon = balloon.find("span").first(); + balloonIcon.removeClass(); + + balloon.css("background", Colors.INFO_BALLOON_MAP[type]); + balloonIcon.addClass("glyphicon"); + if (type === "info") { + balloonIcon.addClass("glyphicon-info-sign"); + } else if (type === "warning") { + balloonIcon.addClass("glyphicon-exclamation-sign"); + } + + if (this.infoTimeOut === undefined) { + balloon.fadeIn(300); + this.infoTimeOut = setTimeout(callback, DISPLAY_TIME); + } else { + clearTimeout(this.infoTimeOut); + this.infoTimeOut = setTimeout(callback, DISPLAY_TIME); + } + } + + private setupMapInteractionHandlers(): void { + this.stage.enableMouseOver(20); + + // Listen for mouse movement events to update hover positions + this.stage.on("stagemousemove", (event: createjs.MouseEvent) => { + this.currentStageMouseX = event.stageX; + this.currentStageMouseY = event.stageY; + + let gridPos = this.convertScreenCoordsToGridCoords([event.stageX, event.stageY]); + let tileX = gridPos.x; + let tileY = gridPos.y; + + // Check whether the coordinates of the hover location have changed since the last draw + if (this.mapView.hoverLayer.hoverTilePosition.x !== tileX) { + this.mapView.hoverLayer.hoverTilePosition.x = tileX; + this.mapView.updateScene = true; + } + if (this.mapView.hoverLayer.hoverTilePosition.y !== tileY) { + this.mapView.hoverLayer.hoverTilePosition.y = tileY; + this.mapView.updateScene = true; + } + }); + + // Handle mousedown interaction + this.stage.on("mousedown", (e: createjs.MouseEvent) => { + this.stageDragBeginX = e.stageX; + this.stageDragBeginY = e.stageY; + }); + + // Handle map dragging interaction + // Drag begin and progress handlers + this.mapView.mapContainer.on("pressmove", (e: createjs.MouseEvent) => { + if (!this.gridDragging) { + this.gridDragBeginX = e.stageX - this.mapView.mapContainer.x; + this.gridDragBeginY = e.stageY - this.mapView.mapContainer.y; + this.stageDragBeginX = e.stageX; + this.stageDragBeginY = e.stageY; + this.gridDragging = true; + } else { + this.mapView.mapContainer.x = e.stageX - this.gridDragBeginX; + this.mapView.mapContainer.y = e.stageY - this.gridDragBeginY; + + this.checkAndResetCanvasMovement(); + + this.mapView.updateScene = true; + } + }); + + // Drag exit handlers + this.mapView.mapContainer.on("pressup", (e: createjs.MouseEvent) => { + if (this.gridDragging) { + this.gridDragging = false; + } + + if (Math.abs(e.stageX - this.stageDragBeginX) < this.MAX_DELTA && + Math.abs(e.stageY - this.stageDragBeginY) < this.MAX_DELTA) { + this.handleCanvasMouseClick(e.stageX, e.stageY); + } + }); + + // Disable an ongoing drag action if the mouse leaves the canvas + this.mapView.stage.on("mouseleave", () => { + if (this.gridDragging) { + this.gridDragging = false; + } + }); + + // Relay scroll events to the MapView zoom handler + $("#main-canvas").on("mousewheel", (event: JQueryEventObject) => { + let originalEvent = (event.originalEvent); + this.mapView.zoom([this.currentStageMouseX, this.currentStageMouseY], -0.7 * originalEvent.deltaY); + this.scaleIndicatorController.update(); + }); + } + + /** + * Connects clickable UI elements to their respective event listeners. + */ + private setupEventListeners(): void { + // Zooming elements + $("#zoom-plus").on("click", () => { + this.mapView.zoom([ + this.mapView.canvasWidth / 2, + this.mapView.canvasHeight / 2 + ], 20); + }); + $("#zoom-minus").on("click", () => { + this.mapView.zoom([ + this.mapView.canvasWidth / 2, + this.mapView.canvasHeight / 2 + ], -20); + }); + + $(".export-canvas").click(() => { + this.exportCanvasToImage(); + }); + + // Menu panels + $(".menu-header-bar .menu-collapse").on("click", (event: JQueryEventObject) => { + let container = $(event.target).closest(".menu-container"); + if (this.appMode === AppMode.CONSTRUCTION) { + container.children(".menu-body.construction").first().slideToggle(300); + } else if (this.appMode === AppMode.SIMULATION) { + container.children(".menu-body.simulation").first().slideToggle(300); + } + + }); + + // Menu close button + $(".menu-header-bar .menu-exit").on("click", (event: JQueryEventObject) => { + let nearestMenuContainer = $(event.target).closest(".menu-container"); + if (nearestMenuContainer.is("#node-menu")) { + this.interactionLevel = InteractionLevel.OBJECT; + $(".node-element-overlay").addClass("hidden"); + } + nearestMenuContainer.addClass("hidden"); + }); + + // Handler for the construction mode switch + $("#construction-mode-switch").on("click", () => { + this.simulationController.exitMode(); + }); + + // Handler for the simulation mode switch + $("#simulation-mode-switch").on("click", () => { + this.simulationController.enterMode(); + }); + + // Handler for the version-save button + $("#save-version-btn").on("click", (event: JQueryEventObject) => { + let target = $(event.target); + + target.attr("data-saved", "false"); + let lastPath = this.mapView.simulation.paths[this.mapView.simulation.paths.length - 1]; + this.api.branchFromPath( + this.mapView.simulation.id, lastPath.id, lastPath.sections[lastPath.sections.length - 1].startTick + 1 + ).then((data: IPath) => { + this.mapView.simulation.paths.push(data); + this.mapView.currentDatacenter = data.sections[data.sections.length - 1].datacenter; + target.attr("data-saved", "true"); + }); + }); + + $(document).on("keydown", (event: JQueryKeyEventObject) => { + if ($(event.target).is('input')) { + return; + } + + if (event.which === 83) { + this.simulationController.enterMode(); + } else if (event.which === 67) { + this.simulationController.exitMode(); + } else if (event.which == 32) { + if (this.appMode === AppMode.SIMULATION) { + this.simulationController.timelineController.togglePlayback(); + } + } + }); + } + + /** + * Handles a simple mouse click (without drag) on the canvas. + * + * @param stageX The x coordinate of the location in pixels on the stage + * @param stageY The y coordinate of the location in pixels on the stage + */ + private handleCanvasMouseClick(stageX: number, stageY: number): void { + let gridPos = this.convertScreenCoordsToGridCoords([stageX, stageY]); + + if (this.interactionLevel === InteractionLevel.BUILDING) { + if (this.interactionMode === InteractionMode.DEFAULT) { + let roomIndex = Util.roomCollisionIndexOf(this.mapView.currentDatacenter.rooms, gridPos); + + if (roomIndex !== -1) { + this.interactionLevel = InteractionLevel.ROOM; + this.roomModeController.enterMode(this.mapView.currentDatacenter.rooms[roomIndex]); + } + } else if (this.interactionMode === InteractionMode.SELECT_ROOM) { + if (this.mapView.roomLayer.checkHoverTileValidity(gridPos)) { + this.buildingModeController.addSelectedTile(this.mapView.hoverLayer.hoverTilePosition); + } else if (Util.tileListContainsPosition(this.mapView.roomLayer.selectedTiles, gridPos)) { + this.buildingModeController.removeSelectedTile(this.mapView.hoverLayer.hoverTilePosition); + } + } + } else if (this.interactionLevel === InteractionLevel.ROOM) { + this.roomModeController.handleCanvasMouseClick(gridPos); + } else if (this.interactionLevel === InteractionLevel.OBJECT) { + if (gridPos.x !== this.mapView.grayLayer.currentObjectTile.position.x || + gridPos.y !== this.mapView.grayLayer.currentObjectTile.position.y) { + this.objectModeController.goToRoomMode(); + } + } else if (this.interactionLevel === InteractionLevel.NODE) { + this.interactionLevel = InteractionLevel.OBJECT; + this.nodeModeController.goToObjectMode(); + } + } + + /** + * Takes screen (stage) coordinates and returns the grid cell position they belong to. + * + * @param stagePosition The raw x and y coordinates of the wanted position + * @returns {Array} The corresponding grid cell coordinates + */ + private convertScreenCoordsToGridCoords(stagePosition: number[]): IGridPosition { + let result = {x: 0, y: 0}; + result.x = Math.floor((stagePosition[0] - this.mapView.mapContainer.x) / + (this.mapView.mapContainer.scaleX * CELL_SIZE)); + result.y = Math.floor((stagePosition[1] - this.mapView.mapContainer.y) / + (this.mapView.mapContainer.scaleY * CELL_SIZE)); + return result; + } + + /** + * Adjusts the canvas size to fit the window perfectly. + */ + private onWindowResize() { + let parent = this.canvas.parent(".app-content"); + parent.height($(window).height() - 50); + this.canvas.attr("width", parent.width()); + this.canvas.attr("height", parent.height()); + this.mapView.canvasWidth = parent.width(); + this.mapView.canvasHeight = parent.height(); + + if (this.interactionLevel === InteractionLevel.BUILDING) { + this.mapView.zoomOutOnDC(); + } else if (this.interactionLevel === InteractionLevel.ROOM) { + this.mapView.zoomInOnRoom(this.roomModeController.currentRoom); + } else { + this.mapView.zoomInOnRoom(this.roomModeController.currentRoom, true); + } + + this.mapView.updateScene = true; + } + + private matchUserAuthLevel() { + let authLevel = localStorage.getItem("simulationAuthLevel"); + if (authLevel === "VIEW") { + $(".side-menu-container.right-middle-side, .side-menu-container.right-side").hide(); + } + } + + private exportCanvasToImage() { + let canvasData = (this.canvas.get(0)).toDataURL("image/png"); + let newWindow = window.open('about:blank', 'OpenDC Canvas Export'); + newWindow.document.write("Canvas Image Export"); + newWindow.document.title = "OpenDC Canvas Export"; + } +} diff --git a/src/scripts/controllers/modes/building.ts b/src/scripts/controllers/modes/building.ts new file mode 100644 index 00000000..4d82f090 --- /dev/null +++ b/src/scripts/controllers/modes/building.ts @@ -0,0 +1,114 @@ +import {InteractionMode, MapController} from "../mapcontroller"; +import {MapView} from "../../views/mapview"; +import * as $ from "jquery"; + + +/** + * Class responsible for handling building mode interactions. + */ +export class BuildingModeController { + public newRoomId: number; + + private mapController: MapController; + private mapView: MapView; + + + constructor(mapController: MapController) { + this.mapController = mapController; + this.mapView = this.mapController.mapView; + } + + /** + * Connects all DOM event listeners to their respective element targets. + */ + public setupEventListeners() { + let resetConstructionButtons = () => { + this.mapController.interactionMode = InteractionMode.DEFAULT; + this.mapView.hoverLayer.setHoverTileVisibility(false); + $("#room-construction").text("Construct new room"); + $("#room-construction-cancel").slideToggle(300); + }; + + // Room construction button + $("#room-construction").on("click", (event: JQueryEventObject) => { + if (this.mapController.interactionMode === InteractionMode.DEFAULT) { + this.mapController.interactionMode = InteractionMode.SELECT_ROOM; + this.mapView.hoverLayer.setHoverTileVisibility(true); + this.mapController.api.addRoomToDatacenter(this.mapView.simulation.id, + this.mapView.currentDatacenter.id).then((room: IRoom) => { + this.newRoomId = room.id; + }); + $(event.target).text("Finalize room"); + $("#room-construction-cancel").slideToggle(300); + } else if (this.mapController.interactionMode === InteractionMode.SELECT_ROOM) { + resetConstructionButtons(); + this.finalizeRoom(); + } + }); + + // Cancel button for room construction + $("#room-construction-cancel").on("click", () => { + resetConstructionButtons(); + this.cancelRoomConstruction(); + }); + } + + /** + * Cancels room construction and deletes the temporary room created previously. + */ + public cancelRoomConstruction() { + this.mapController.api.deleteRoom(this.mapView.simulation.id, + this.mapView.currentDatacenter.id, this.newRoomId).then(() => { + this.mapView.roomLayer.cancelRoomConstruction(); + }); + } + + /** + * Finalizes room construction by triggering a redraw of the room layer with the new room added. + */ + public finalizeRoom() { + this.mapController.api.getRoom(this.mapView.simulation.id, + this.mapView.currentDatacenter.id, this.newRoomId).then((room: IRoom) => { + this.mapView.roomLayer.finalizeRoom(room); + }); + } + + /** + * Adds a newly selected tile to the list of selected tiles. + * + * @param position The new tile position to be added + */ + public addSelectedTile(position: IGridPosition): void { + let tile = { + id: -1, + roomId: this.newRoomId, + position: {x: position.x, y: position.y} + }; + this.mapController.api.addTileToRoom(this.mapView.simulation.id, + this.mapView.currentDatacenter.id, this.newRoomId, tile).then((tile: ITile) => { + this.mapView.roomLayer.addSelectedTile(tile); + }); + } + + /** + * Removes a previously selected tile. + * + * @param position The position of the tile to be removed + */ + public removeSelectedTile(position: IGridPosition): void { + let tile; + let objectIndex = -1; + + for (let i = 0; i < this.mapView.roomLayer.selectedTileObjects.length; i++) { + tile = this.mapView.roomLayer.selectedTileObjects[i]; + if (tile.position.x === position.x && tile.position.y === position.y) { + objectIndex = i; + } + } + this.mapController.api.deleteTile(this.mapView.simulation.id, + this.mapView.currentDatacenter.id, this.newRoomId, + this.mapView.roomLayer.selectedTileObjects[objectIndex].tileObject.id).then(() => { + this.mapView.roomLayer.removeSelectedTile(position, objectIndex); + }); + } +} \ No newline at end of file diff --git a/src/scripts/controllers/modes/node.ts b/src/scripts/controllers/modes/node.ts new file mode 100644 index 00000000..3b3f8a32 --- /dev/null +++ b/src/scripts/controllers/modes/node.ts @@ -0,0 +1,297 @@ +import {MapController, AppMode, InteractionLevel} from "../mapcontroller"; +import {MapView} from "../../views/mapview"; +import * as $ from "jquery"; + + +/** + * Class responsible for rendering node mode and handling UI interactions within it. + */ +export class NodeModeController { + public currentMachine: IMachine; + + private mapController: MapController; + private mapView: MapView; + + + constructor(mapController: MapController) { + this.mapController = mapController; + this.mapView = this.mapController.mapView; + + this.loadAddDropdowns(); + } + + /** + * Moves the UI model into node mode. + * + * @param machine The machine that was selected in rack mode + */ + public enterMode(machine: IMachine): void { + this.currentMachine = machine; + this.populateUnitLists(); + $("#node-menu").removeClass("hidden"); + + if (this.mapController.appMode === AppMode.SIMULATION) { + this.mapController.simulationController.transitionFromRackToNode(); + } + } + + /** + * Performs cleanup and closing actions before allowing transferal to rack mode. + */ + public goToObjectMode(): void { + $("#node-menu").addClass("hidden"); + $(".node-element-overlay").addClass("hidden"); + this.currentMachine = undefined; + this.mapController.interactionLevel = InteractionLevel.OBJECT; + + if (this.mapController.appMode === AppMode.SIMULATION) { + this.mapController.simulationController.transitionFromNodeToRack(); + } + } + + /** + * Connects all DOM event listeners to their respective element targets. + */ + public setupEventListeners(): void { + let nodeMenu = $("#node-menu"); + + nodeMenu.find(".panel-group").on("click", ".remove-unit", (event: JQueryEventObject) => { + MapController.showConfirmDeleteDialog("unit", () => { + let index = $(event.target).closest(".panel").index(); + + if (index === -1) { + return; + } + + let closestTabPane = $(event.target).closest(".panel-group"); + + let objectList, idList; + if (closestTabPane.is("#cpu-accordion")) { + objectList = this.currentMachine.cpus; + idList = this.currentMachine.cpuIds; + } else if (closestTabPane.is("#gpu-accordion")) { + objectList = this.currentMachine.gpus; + idList = this.currentMachine.gpuIds; + } else if (closestTabPane.is("#memory-accordion")) { + objectList = this.currentMachine.memories; + idList = this.currentMachine.memoryIds; + } else if (closestTabPane.is("#storage-accordion")) { + objectList = this.currentMachine.storages; + idList = this.currentMachine.storageIds; + } + + idList.splice(idList.indexOf(objectList[index]).id, 1); + objectList.splice(index, 1); + + this.mapController.api.updateMachine(this.mapView.simulation.id, + this.mapView.currentDatacenter.id, this.mapController.roomModeController.currentRoom.id, + this.mapController.objectModeController.currentObjectTile.id, this.currentMachine).then( + () => { + this.populateUnitLists(); + this.mapController.objectModeController.updateNodeComponentOverlays(); + }); + }); + }); + + nodeMenu.find(".add-unit").on("click", (event: JQueryEventObject) => { + let dropdown = $(event.target).closest(".input-group-btn").siblings("select").first(); + + let closestTabPane = $(event.target).closest(".input-group").siblings(".panel-group").first(); + let objectList, idList, typePlural; + if (closestTabPane.is("#cpu-accordion")) { + objectList = this.currentMachine.cpus; + idList = this.currentMachine.cpuIds; + typePlural = "cpus"; + } else if (closestTabPane.is("#gpu-accordion")) { + objectList = this.currentMachine.gpus; + idList = this.currentMachine.gpuIds; + typePlural = "gpus"; + } else if (closestTabPane.is("#memory-accordion")) { + objectList = this.currentMachine.memories; + idList = this.currentMachine.memoryIds; + typePlural = "memories"; + } else if (closestTabPane.is("#storage-accordion")) { + objectList = this.currentMachine.storages; + idList = this.currentMachine.storageIds; + typePlural = "storages"; + } + + if (idList.length + 1 > 4) { + this.mapController.showInfoBalloon("Machine has only 4 slots", "warning"); + return; + } + + let id = parseInt(dropdown.val(), 10); + idList.push(id); + this.mapController.api.getSpecificationOfType(typePlural, id).then((spec: INodeUnit) => { + objectList.push(spec); + + this.mapController.api.updateMachine(this.mapView.simulation.id, + this.mapView.currentDatacenter.id, this.mapController.roomModeController.currentRoom.id, + this.mapController.objectModeController.currentObjectTile.id, this.currentMachine).then( + () => { + this.populateUnitLists(); + this.mapController.objectModeController.updateNodeComponentOverlays(); + }); + }); + }); + } + + /** + * Populates the "add" dropdowns with all available unit options. + */ + private loadAddDropdowns(): void { + let unitTypes = [ + "cpus", "gpus", "memories", "storages" + ]; + let dropdowns = [ + $("#add-cpu-form").find("select"), + $("#add-gpu-form").find("select"), + $("#add-memory-form").find("select"), + $("#add-storage-form").find("select"), + ]; + + unitTypes.forEach((type: string, index: number) => { + this.mapController.api.getAllSpecificationsOfType(type).then((data: any) => { + data.forEach((option: INodeUnit) => { + dropdowns[index].append($("