diff options
| author | Georgios Andreadis <g.andreadis@student.tudelft.nl> | 2017-09-25 13:50:49 +0200 |
|---|---|---|
| committer | Georgios Andreadis <g.andreadis@student.tudelft.nl> | 2017-09-25 13:50:49 +0200 |
| commit | a1589e75358558eada7ffc2efc7e3fa7160d233e (patch) | |
| tree | 7889a2364292cd8b90fe996da7907bebf200d3dc /opendc | |
| parent | 1f34466d41ba01a3dd36b0866696367d397daf7e (diff) | |
Reformat codebase and fix spelling errors
Diffstat (limited to 'opendc')
83 files changed, 437 insertions, 375 deletions
diff --git a/opendc/api/v1/datacenters/datacenterId/endpoint.py b/opendc/api/v1/datacenters/datacenterId/endpoint.py index 75d0a9cf..9444fb80 100644 --- a/opendc/api/v1/datacenters/datacenterId/endpoint.py +++ b/opendc/api/v1/datacenters/datacenterId/endpoint.py @@ -1,7 +1,8 @@ from opendc.models.datacenter import Datacenter -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Datacenter.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'datacenterId': 'int' } ) diff --git a/opendc/api/v1/datacenters/datacenterId/rooms/endpoint.py b/opendc/api/v1/datacenters/datacenterId/rooms/endpoint.py index 31545a1e..cd96f97f 100644 --- a/opendc/api/v1/datacenters/datacenterId/rooms/endpoint.py +++ b/opendc/api/v1/datacenters/datacenterId/rooms/endpoint.py @@ -1,8 +1,9 @@ -from opendc.models.room import Room from opendc.models.datacenter import Datacenter -from opendc.util import database, exceptions +from opendc.models.room import Room +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Datacenter's Rooms.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'datacenterId': 'int' } ) @@ -41,6 +42,7 @@ def GET(request): [x.to_JSON() for x in rooms] ) + def POST(request): """Add a Room.""" @@ -48,10 +50,10 @@ def POST(request): try: request.check_required_parameters( - path = { + path={ 'datacenterId': 'int' }, - body = { + body={ 'room': { 'id': 'int', 'datacenterId': 'int', @@ -61,7 +63,7 @@ def POST(request): ) 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']: diff --git a/opendc/api/v1/experiments/experimentId/endpoint.py b/opendc/api/v1/experiments/experimentId/endpoint.py index 3bdd30d2..59e0e0fe 100644 --- a/opendc/api/v1/experiments/experimentId/endpoint.py +++ b/opendc/api/v1/experiments/experimentId/endpoint.py @@ -1,13 +1,14 @@ from opendc.models.experiment import Experiment -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Experiment.""" try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' } ) @@ -39,6 +40,7 @@ def GET(request): experiment.to_JSON() ) + def PUT(request): """Update this Experiment's Path, Trace, Scheduler, and/or name.""" @@ -46,10 +48,10 @@ def PUT(request): try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' }, - body = { + body={ 'experiment': { 'pathId': 'int', 'traceId': 'int', @@ -97,6 +99,7 @@ def PUT(request): experiment.to_JSON() ) + def DELETE(request): """Delete this Experiment.""" @@ -104,7 +107,7 @@ def DELETE(request): try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' } ) diff --git a/opendc/api/v1/experiments/experimentId/last-simulated-tick/endpoint.py b/opendc/api/v1/experiments/experimentId/last-simulated-tick/endpoint.py index 24eb8932..b4b19f59 100644 --- a/opendc/api/v1/experiments/experimentId/last-simulated-tick/endpoint.py +++ b/opendc/api/v1/experiments/experimentId/last-simulated-tick/endpoint.py @@ -1,7 +1,8 @@ from opendc.models.experiment import Experiment -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Experiment's last simulated tick.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' } ) @@ -21,7 +22,7 @@ def GET(request): experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) - # Make sure this Experiment exisits + # Make sure this Experiment exists if not experiment.exists(): return Response(404, '{} not found.'.format(experiment)) diff --git a/opendc/api/v1/experiments/experimentId/machine-states/endpoint.py b/opendc/api/v1/experiments/experimentId/machine-states/endpoint.py index 97113e4a..8ad588d2 100644 --- a/opendc/api/v1/experiments/experimentId/machine-states/endpoint.py +++ b/opendc/api/v1/experiments/experimentId/machine-states/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.experiment import Experiment from opendc.models.machine_state import MachineState -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Experiment's Machine States.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' } ) @@ -22,7 +23,7 @@ def GET(request): experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) - # Make sure this Experiment exisits + # Make sure this Experiment exists if not experiment.exists(): return Response(404, '{} not found.'.format(experiment)) diff --git a/opendc/api/v1/experiments/experimentId/rack-states/endpoint.py b/opendc/api/v1/experiments/experimentId/rack-states/endpoint.py index daed45c5..03570039 100644 --- a/opendc/api/v1/experiments/experimentId/rack-states/endpoint.py +++ b/opendc/api/v1/experiments/experimentId/rack-states/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.experiment import Experiment from opendc.models.rack_state import RackState -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Experiment's Tack States.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' } ) @@ -22,7 +23,7 @@ def GET(request): experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) - # Make sure this Experiment exisits + # Make sure this Experiment exists if not experiment.exists(): return Response(404, '{} not found.'.format(experiment)) diff --git a/opendc/api/v1/experiments/experimentId/room-states/endpoint.py b/opendc/api/v1/experiments/experimentId/room-states/endpoint.py index 9e283d34..2693dc89 100644 --- a/opendc/api/v1/experiments/experimentId/room-states/endpoint.py +++ b/opendc/api/v1/experiments/experimentId/room-states/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.experiment import Experiment from opendc.models.room_state import RoomState -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Experiment's Room States.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' } ) @@ -22,7 +23,7 @@ def GET(request): experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) - # Make sure this Experiment exisits + # Make sure this Experiment exists if not experiment.exists(): return Response(404, '{} not found.'.format(experiment)) diff --git a/opendc/api/v1/experiments/experimentId/statistics/task-durations/endpoint.py b/opendc/api/v1/experiments/experimentId/statistics/task-durations/endpoint.py index ad73daa7..b8311f08 100644 --- a/opendc/api/v1/experiments/experimentId/statistics/task-durations/endpoint.py +++ b/opendc/api/v1/experiments/experimentId/statistics/task-durations/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.experiment import Experiment from opendc.models.task_duration import TaskDuration -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Experiment's Task Durations.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' } ) @@ -22,7 +23,7 @@ def GET(request): experiment = Experiment.from_primary_key((request.params_path['experimentId'],)) - # Make sure this Experiment exisits + # Make sure this Experiment exists if not experiment.exists(): return Response(404, '{} not found.'.format(experiment)) diff --git a/opendc/api/v1/experiments/experimentId/task-states/endpoint.py b/opendc/api/v1/experiments/experimentId/task-states/endpoint.py index 805d86fb..0c3fae89 100644 --- a/opendc/api/v1/experiments/experimentId/task-states/endpoint.py +++ b/opendc/api/v1/experiments/experimentId/task-states/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.experiment import Experiment from opendc.models.task_state import TaskState -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Experiment's Task States.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'experimentId': 'int' } ) diff --git a/opendc/api/v1/jobs/jobId/endpoint.py b/opendc/api/v1/jobs/jobId/endpoint.py index 84b8f3c4..da4dcd9d 100644 --- a/opendc/api/v1/jobs/jobId/endpoint.py +++ b/opendc/api/v1/jobs/jobId/endpoint.py @@ -2,6 +2,7 @@ from opendc.models.job import Job from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Job.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'jobId': 'int' } ) diff --git a/opendc/api/v1/jobs/jobId/tasks/endpoint.py b/opendc/api/v1/jobs/jobId/tasks/endpoint.py index 9b6a1cab..04ac5b8c 100644 --- a/opendc/api/v1/jobs/jobId/tasks/endpoint.py +++ b/opendc/api/v1/jobs/jobId/tasks/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.job import Job from opendc.models.task import Task -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Job's Tasks.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'jobId': 'int' } ) diff --git a/opendc/api/v1/paths.json b/opendc/api/v1/paths.json index 79133968..bac7fc71 100644 --- a/opendc/api/v1/paths.json +++ b/opendc/api/v1/paths.json @@ -1,53 +1,53 @@ [ - "/users", - "/users/{userId}", - "/users/{userId}/authorizations", - "/simulations", - "/simulations/{simulationId}", - "/simulations/{simulationId}/authorizations", - "/simulations/{simulationId}/authorizations/{userId}", - "/datacenters/{datacenterId}", - "/datacenters/{datacenterId}/rooms", - "/rooms/{roomId}", - "/rooms/{roomId}/tiles", - "/tiles/{tileId}", - "/tiles/{tileId}/cooling-item", - "/tiles/{tileId}/psu", - "/tiles/{tileId}/rack", - "/tiles/{tileId}/rack/machines", - "/tiles/{tileId}/rack/machines/{position}", - "/simulations/{simulationId}/experiments", - "/experiments/{experimentId}", - "/experiments/{experimentId}/last-simulated-tick", - "/experiments/{experimentId}/machine-states", - "/experiments/{experimentId}/rack-states", - "/experiments/{experimentId}/room-states", - "/experiments/{experimentId}/task-states", - "/simulations/{simulationId}/paths", - "/paths/{pathId}", - "/paths/{pathId}/branches", - "/paths/{pathId}/sections", - "/sections/{sectionId}", - "/schedulers", - "/traces", - "/traces/{traceId}", - "/traces/{traceId}/jobs", - "/jobs/{jobId}", - "/jobs/{jobId}/tasks", - "/room-types", - "/room-types/{name}/allowed-objects", - "/specifications/cooling-items", - "/specifications/cooling-items/{id}", - "/specifications/cpus", - "/specifications/cpus/{id}", - "/specifications/failure-models", - "/specifications/failure-models/{id}", - "/specifications/gpus", - "/specifications/gpus/{id}", - "/specifications/memories", - "/specifications/memories/{id}", - "/specifications/psus", - "/specifications/psus/{id}", - "/specifications/storages", - "/specifications/storages/{id}" + "/users", + "/users/{userId}", + "/users/{userId}/authorizations", + "/simulations", + "/simulations/{simulationId}", + "/simulations/{simulationId}/authorizations", + "/simulations/{simulationId}/authorizations/{userId}", + "/datacenters/{datacenterId}", + "/datacenters/{datacenterId}/rooms", + "/rooms/{roomId}", + "/rooms/{roomId}/tiles", + "/tiles/{tileId}", + "/tiles/{tileId}/cooling-item", + "/tiles/{tileId}/psu", + "/tiles/{tileId}/rack", + "/tiles/{tileId}/rack/machines", + "/tiles/{tileId}/rack/machines/{position}", + "/simulations/{simulationId}/experiments", + "/experiments/{experimentId}", + "/experiments/{experimentId}/last-simulated-tick", + "/experiments/{experimentId}/machine-states", + "/experiments/{experimentId}/rack-states", + "/experiments/{experimentId}/room-states", + "/experiments/{experimentId}/task-states", + "/simulations/{simulationId}/paths", + "/paths/{pathId}", + "/paths/{pathId}/branches", + "/paths/{pathId}/sections", + "/sections/{sectionId}", + "/schedulers", + "/traces", + "/traces/{traceId}", + "/traces/{traceId}/jobs", + "/jobs/{jobId}", + "/jobs/{jobId}/tasks", + "/room-types", + "/room-types/{name}/allowed-objects", + "/specifications/cooling-items", + "/specifications/cooling-items/{id}", + "/specifications/cpus", + "/specifications/cpus/{id}", + "/specifications/failure-models", + "/specifications/failure-models/{id}", + "/specifications/gpus", + "/specifications/gpus/{id}", + "/specifications/memories", + "/specifications/memories/{id}", + "/specifications/psus", + "/specifications/psus/{id}", + "/specifications/storages", + "/specifications/storages/{id}" ]
\ No newline at end of file diff --git a/opendc/api/v1/paths/pathId/branches/endpoint.py b/opendc/api/v1/paths/pathId/branches/endpoint.py index 2ac4236a..1f330472 100644 --- a/opendc/api/v1/paths/pathId/branches/endpoint.py +++ b/opendc/api/v1/paths/pathId/branches/endpoint.py @@ -11,6 +11,7 @@ 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.""" @@ -18,10 +19,10 @@ def POST(request): try: request.check_required_parameters( - path = { + path={ 'pathId': 'int' }, - body = { + body={ 'section': { 'startTick': 'int' } @@ -48,8 +49,8 @@ def POST(request): # Create the new Path new_path = Path( - simulation_id = current_path.simulation_id, - datetime_created = database.datetime_to_string(datetime.now()) + simulation_id=current_path.simulation_id, + datetime_created=database.datetime_to_string(datetime.now()) ) new_path.insert() @@ -62,11 +63,10 @@ def POST(request): 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 + path_id=new_path.id, + datacenter_id=current_section.datacenter_id, + start_tick=current_section.start_tick ) new_section.insert() @@ -92,9 +92,9 @@ def POST(request): 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'] + path_id=new_path.id, + datacenter_id=path_parameters['datacenterId'], + start_tick=request.params_body['section']['startTick'] ) new_section.insert() @@ -113,7 +113,7 @@ def POST(request): message = old_room.generate_api_call(path_parameters, request.token) response = Request(message).process() - + path_parameters['roomId'] = response.content['id'] # ... then the Tiles, ... @@ -147,10 +147,9 @@ def POST(request): 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() diff --git a/opendc/api/v1/paths/pathId/endpoint.py b/opendc/api/v1/paths/pathId/endpoint.py index 470063d2..7ade19ce 100644 --- a/opendc/api/v1/paths/pathId/endpoint.py +++ b/opendc/api/v1/paths/pathId/endpoint.py @@ -1,8 +1,8 @@ from opendc.models.path import Path -from opendc.models.simulation import Simulation -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Path.""" @@ -10,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'pathId': 'int' } ) diff --git a/opendc/api/v1/paths/pathId/sections/endpoint.py b/opendc/api/v1/paths/pathId/sections/endpoint.py index 5b08863b..d4161839 100644 --- a/opendc/api/v1/paths/pathId/sections/endpoint.py +++ b/opendc/api/v1/paths/pathId/sections/endpoint.py @@ -1,8 +1,9 @@ -from opendc.models.section import Section from opendc.models.path import Path -from opendc.util import database, exceptions +from opendc.models.section import Section +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Path's Sections.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'pathId': 'int' } ) diff --git a/opendc/api/v1/room-types/endpoint.py b/opendc/api/v1/room-types/endpoint.py index 2030b538..fe00f226 100644 --- a/opendc/api/v1/room-types/endpoint.py +++ b/opendc/api/v1/room-types/endpoint.py @@ -1,6 +1,7 @@ from opendc.models.room_type import RoomType from opendc.util.rest import Response + def GET(request): """Get all available room types.""" diff --git a/opendc/api/v1/room-types/name/allowed-objects/endpoint.py b/opendc/api/v1/room-types/name/allowed-objects/endpoint.py index 76b863f1..a574591c 100644 --- a/opendc/api/v1/room-types/name/allowed-objects/endpoint.py +++ b/opendc/api/v1/room-types/name/allowed-objects/endpoint.py @@ -2,6 +2,7 @@ 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.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'name': 'string' } ) @@ -27,4 +28,4 @@ def GET(request): 200, 'Successfully retrieved AllowedObjects.', [x.to_JSON() for x in allowed_objects] - ) + ) diff --git a/opendc/api/v1/rooms/roomId/endpoint.py b/opendc/api/v1/rooms/roomId/endpoint.py index 6d7ab261..1dfc32cc 100644 --- a/opendc/api/v1/rooms/roomId/endpoint.py +++ b/opendc/api/v1/rooms/roomId/endpoint.py @@ -1,7 +1,8 @@ from opendc.models.room import Room -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Room.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'roomId': 'int' } ) @@ -41,24 +42,25 @@ def GET(request): 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 = { + path={ 'roomId': 'int' }, - body = { + body={ 'room': { 'name': 'string', 'roomType': 'string' } } ) - + except exceptions.ParameterError as e: return Response(400, e.message) @@ -94,6 +96,7 @@ def PUT(request): room.to_JSON() ) + def DELETE(request): """Delete this Room.""" @@ -101,7 +104,7 @@ def DELETE(request): try: request.check_required_parameters( - path = { + path={ 'roomId': 'int' } ) @@ -129,6 +132,6 @@ def DELETE(request): return Response( 200, - 'Sucessfully deleted {}.'.format(room), + 'Successfully deleted {}.'.format(room), room.to_JSON() ) diff --git a/opendc/api/v1/rooms/roomId/tiles/endpoint.py b/opendc/api/v1/rooms/roomId/tiles/endpoint.py index 9d17c644..a4ef51e7 100644 --- a/opendc/api/v1/rooms/roomId/tiles/endpoint.py +++ b/opendc/api/v1/rooms/roomId/tiles/endpoint.py @@ -1,8 +1,9 @@ -from opendc.models.tile import Tile from opendc.models.room import Room -from opendc.util import database, exceptions +from opendc.models.tile import Tile +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Room's Tiles.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'roomId': 'int' } ) @@ -45,6 +46,7 @@ def GET(request): [x.to_JSON() for x in tiles] ) + def POST(request): """Add a Tile.""" @@ -52,10 +54,10 @@ def POST(request): try: request.check_required_parameters( - path = { + path={ 'roomId': 'int' }, - body = { + body={ 'tile': { 'roomId': 'int', 'positionX': 'int', @@ -104,7 +106,7 @@ def POST(request): 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).') diff --git a/opendc/api/v1/schedulers/endpoint.py b/opendc/api/v1/schedulers/endpoint.py index 206c7cb9..36537764 100644 --- a/opendc/api/v1/schedulers/endpoint.py +++ b/opendc/api/v1/schedulers/endpoint.py @@ -1,6 +1,7 @@ from opendc.models.scheduler import Scheduler from opendc.util.rest import Response + def GET(request): """Get all available Schedulers.""" diff --git a/opendc/api/v1/sections/sectionId/endpoint.py b/opendc/api/v1/sections/sectionId/endpoint.py index 48e724bd..94c81d37 100644 --- a/opendc/api/v1/sections/sectionId/endpoint.py +++ b/opendc/api/v1/sections/sectionId/endpoint.py @@ -1,7 +1,8 @@ from opendc.models.section import Section -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Path's Sections.""" @@ -9,14 +10,13 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ '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'],)) @@ -34,7 +34,7 @@ def GET(request): # Return the Section section.read() - + return Response( 200, 'Successfully retrieved {}.'.format(section), diff --git a/opendc/api/v1/simulations/endpoint.py b/opendc/api/v1/simulations/endpoint.py index ff669290..a8637728 100644 --- a/opendc/api/v1/simulations/endpoint.py +++ b/opendc/api/v1/simulations/endpoint.py @@ -9,6 +9,7 @@ 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.""" @@ -16,7 +17,7 @@ def POST(request): try: request.check_required_parameters( - body = { + body={ 'simulation': { 'name': 'string' } @@ -42,9 +43,9 @@ def POST(request): # 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' + user_id=User.from_google_id(request.google_id).id, + simulation_id=simulation.id, + authorization_level='OWN' ) authorization.insert() @@ -52,8 +53,8 @@ def POST(request): # Instantiate a Path and insert it into the database path = Path( - simulation_id = simulation.id, - datetime_created = database.datetime_to_string(datetime.now()) + simulation_id=simulation.id, + datetime_created=database.datetime_to_string(datetime.now()) ) path.insert() @@ -61,8 +62,8 @@ def POST(request): # Instantiate a Datacenter and insert it into the database datacenter = Datacenter( - starred = 0, - simulation_id = simulation.id + starred=0, + simulation_id=simulation.id ) datacenter.insert() @@ -70,9 +71,9 @@ def POST(request): # Instantiate a Section and insert it into the database section = Section( - path_id = path.id, - datacenter_id = datacenter.id, - start_tick = 0 + path_id=path.id, + datacenter_id=datacenter.id, + start_tick=0 ) section.insert() diff --git a/opendc/api/v1/simulations/simulationId/authorizations/endpoint.py b/opendc/api/v1/simulations/simulationId/authorizations/endpoint.py index d880564e..1d6b494e 100644 --- a/opendc/api/v1/simulations/simulationId/authorizations/endpoint.py +++ b/opendc/api/v1/simulations/simulationId/authorizations/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.authorization import Authorization from opendc.models.simulation import Simulation -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Find all authorizations for a Simulation.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'simulationId': 'int' } ) diff --git a/opendc/api/v1/simulations/simulationId/authorizations/userId/endpoint.py b/opendc/api/v1/simulations/simulationId/authorizations/userId/endpoint.py index c3e599cf..46458ffc 100644 --- a/opendc/api/v1/simulations/simulationId/authorizations/userId/endpoint.py +++ b/opendc/api/v1/simulations/simulationId/authorizations/userId/endpoint.py @@ -1,9 +1,10 @@ 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 import exceptions from opendc.util.rest import Response + def DELETE(request): """Delete a user's authorization level over a simulation.""" @@ -11,7 +12,7 @@ def DELETE(request): try: request.check_required_parameters( - path = { + path={ 'simulationId': 'int', 'userId': 'int' } @@ -21,7 +22,7 @@ def DELETE(request): return Response(400, e.message) # Instantiate an Authorization - + authorization = Authorization.from_primary_key(( request.params_path['userId'], request.params_path['simulationId'] @@ -30,7 +31,7 @@ def DELETE(request): # Make sure this Authorization exists in the database if not authorization.exists(): - return Response (404, '{} not found.'.format(authorization)) + return Response(404, '{} not found.'.format(authorization)) # Make sure this User is allowed to delete this Authorization @@ -47,14 +48,15 @@ def DELETE(request): 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 = { + path={ 'simulationId': 'int', 'userId': 'int' } @@ -62,7 +64,7 @@ def GET(request): except exceptions.ParameterError as e: return Response(400, e.message) - + # Instantiate an Authorization authorization = Authorization.from_primary_key(( @@ -87,6 +89,7 @@ def GET(request): authorization.to_JSON() ) + def POST(request): """Add an authorization for a user's access to a simulation.""" @@ -94,11 +97,11 @@ def POST(request): try: request.check_required_parameters( - path = { + path={ 'userId': 'int', 'simulationId': 'int' }, - body = { + body={ 'authorization': { 'authorizationLevel': 'string' } @@ -143,7 +146,7 @@ def POST(request): except exceptions.ForeignKeyError: return Response(400, 'Invalid authorizationLevel') - + # Return this Authorization return Response( @@ -152,6 +155,7 @@ def POST(request): authorization.to_JSON() ) + def PUT(request): """Change a user's authorization level over a simulation.""" @@ -159,11 +163,11 @@ def PUT(request): try: request.check_required_parameters( - path = { + path={ 'simulationId': 'int', 'userId': 'int' }, - body = { + body={ 'authorization': { 'authorizationLevel': 'string' } @@ -192,7 +196,7 @@ def PUT(request): return Response(403, 'Forbidden from updating {}.'.format(authorization)) # Try to update this Authorization - + try: authorization.update() @@ -200,7 +204,7 @@ def PUT(request): return Response(400, 'Invalid authorization level.') # Return this Authorization - + return Response( 200, 'Successfully updated {}.'.format(authorization), diff --git a/opendc/api/v1/simulations/simulationId/datacenters/endpoint.py b/opendc/api/v1/simulations/simulationId/datacenters/endpoint.py index d53cd1c8..e28402e4 100644 --- a/opendc/api/v1/simulations/simulationId/datacenters/endpoint.py +++ b/opendc/api/v1/simulations/simulationId/datacenters/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.datacenter import Datacenter from opendc.models.simulation import Simulation -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def POST(request): """Add a new Datacenter to this Simulation.""" @@ -10,10 +11,10 @@ def POST(request): try: request.check_required_parameters( - path = { + path={ 'simulationId': 'int' }, - body = { + body={ 'datacenter': { 'starred': 'int', 'simulationId': 'int' diff --git a/opendc/api/v1/simulations/simulationId/endpoint.py b/opendc/api/v1/simulations/simulationId/endpoint.py index 01623973..5e595740 100644 --- a/opendc/api/v1/simulations/simulationId/endpoint.py +++ b/opendc/api/v1/simulations/simulationId/endpoint.py @@ -1,11 +1,10 @@ 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.""" @@ -13,14 +12,14 @@ def DELETE(request): try: request.check_required_parameters( - path = { + 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'],)) @@ -45,6 +44,7 @@ def DELETE(request): simulation.to_JSON() ) + def GET(request): """Get this Simulation.""" @@ -52,7 +52,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'simulationId': 'int' } ) @@ -82,6 +82,7 @@ def GET(request): simulation.to_JSON() ) + def PUT(request): """Update a simulation's name.""" @@ -89,12 +90,12 @@ def PUT(request): try: request.check_required_parameters( - body = { + body={ 'simulation': { 'name': 'name' } }, - path = { + path={ 'simulationId': 'int' } ) @@ -115,7 +116,7 @@ def PUT(request): return Response(403, 'Forbidden from editing {}.'.format(simulation)) # Update this Simulation in the database - + simulation.read() simulation.name = request.params_body['simulation']['name'] diff --git a/opendc/api/v1/simulations/simulationId/experiments/endpoint.py b/opendc/api/v1/simulations/simulationId/experiments/endpoint.py index 034e82a1..86fadb24 100644 --- a/opendc/api/v1/simulations/simulationId/experiments/endpoint.py +++ b/opendc/api/v1/simulations/simulationId/experiments/endpoint.py @@ -1,9 +1,9 @@ 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 import exceptions from opendc.util.rest import Response + def GET(request): """Get this Simulation's Experiments.""" @@ -11,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'simulationId': 'int' } ) @@ -43,6 +43,7 @@ def GET(request): [x.to_JSON() for x in experiments] ) + def POST(request): """Add a new Experiment for this Simulation.""" @@ -50,10 +51,10 @@ def POST(request): try: request.check_required_parameters( - path = { + path={ 'simulationId': 'int' }, - body = { + body={ 'experiment': { 'simulationId': 'int', 'pathId': 'int', @@ -96,12 +97,12 @@ def POST(request): try: experiment.insert() - + except exceptions.ForeignKeyError as e: return Response(400, 'Foreign key constraint not met.' + e.message) # Return this Experiment - + experiment.read() return Response( diff --git a/opendc/api/v1/simulations/simulationId/paths/endpoint.py b/opendc/api/v1/simulations/simulationId/paths/endpoint.py index e74c8d22..e4aab427 100644 --- a/opendc/api/v1/simulations/simulationId/paths/endpoint.py +++ b/opendc/api/v1/simulations/simulationId/paths/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.path import Path from opendc.models.simulation import Simulation -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Simulation's Paths.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'simulationId': 'int' } ) diff --git a/opendc/api/v1/specifications/cpus/endpoint.py b/opendc/api/v1/specifications/cpus/endpoint.py index 5c856255..5cdbb9ec 100644 --- a/opendc/api/v1/specifications/cpus/endpoint.py +++ b/opendc/api/v1/specifications/cpus/endpoint.py @@ -1,6 +1,7 @@ from opendc.models.cpu import CPU from opendc.util.rest import Response + def GET(request): """Get a list of the specifications of all CPUs.""" diff --git a/opendc/api/v1/specifications/cpus/id/endpoint.py b/opendc/api/v1/specifications/cpus/id/endpoint.py index 158576cb..c2453e51 100644 --- a/opendc/api/v1/specifications/cpus/id/endpoint.py +++ b/opendc/api/v1/specifications/cpus/id/endpoint.py @@ -2,6 +2,7 @@ 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.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'id': 'int' } ) diff --git a/opendc/api/v1/specifications/failure-models/endpoint.py b/opendc/api/v1/specifications/failure-models/endpoint.py index 2530d032..fff668c0 100644 --- a/opendc/api/v1/specifications/failure-models/endpoint.py +++ b/opendc/api/v1/specifications/failure-models/endpoint.py @@ -1,6 +1,7 @@ from opendc.models.failure_model import FailureModel from opendc.util.rest import Response + def GET(request): """Get all Failure Models.""" diff --git a/opendc/api/v1/specifications/failure-models/id/endpoint.py b/opendc/api/v1/specifications/failure-models/id/endpoint.py index 8a7d2e1d..0797c9c9 100644 --- a/opendc/api/v1/specifications/failure-models/id/endpoint.py +++ b/opendc/api/v1/specifications/failure-models/id/endpoint.py @@ -2,6 +2,7 @@ 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.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'id': 'int' } ) diff --git a/opendc/api/v1/specifications/gpus/endpoint.py b/opendc/api/v1/specifications/gpus/endpoint.py index 8728d203..5676f62b 100644 --- a/opendc/api/v1/specifications/gpus/endpoint.py +++ b/opendc/api/v1/specifications/gpus/endpoint.py @@ -1,6 +1,7 @@ from opendc.models.gpu import GPU from opendc.util.rest import Response + def GET(request): """Get a list of the specifications of all GPUs.""" diff --git a/opendc/api/v1/specifications/gpus/id/endpoint.py b/opendc/api/v1/specifications/gpus/id/endpoint.py index 41b5a9e4..81113dc3 100644 --- a/opendc/api/v1/specifications/gpus/id/endpoint.py +++ b/opendc/api/v1/specifications/gpus/id/endpoint.py @@ -2,6 +2,7 @@ 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.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'id': 'int' } ) diff --git a/opendc/api/v1/specifications/memories/endpoint.py b/opendc/api/v1/specifications/memories/endpoint.py index b275b6f0..271824b3 100644 --- a/opendc/api/v1/specifications/memories/endpoint.py +++ b/opendc/api/v1/specifications/memories/endpoint.py @@ -1,6 +1,7 @@ from opendc.models.memory import Memory from opendc.util.rest import Response + def GET(request): """Get a list of the specifications of all Memories.""" diff --git a/opendc/api/v1/specifications/memories/id/endpoint.py b/opendc/api/v1/specifications/memories/id/endpoint.py index 3132efab..863099ca 100644 --- a/opendc/api/v1/specifications/memories/id/endpoint.py +++ b/opendc/api/v1/specifications/memories/id/endpoint.py @@ -2,6 +2,7 @@ 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.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'id': 'int' } ) diff --git a/opendc/api/v1/specifications/storages/endpoint.py b/opendc/api/v1/specifications/storages/endpoint.py index 875ed987..28f33177 100644 --- a/opendc/api/v1/specifications/storages/endpoint.py +++ b/opendc/api/v1/specifications/storages/endpoint.py @@ -1,6 +1,7 @@ from opendc.models.storage import Storage from opendc.util.rest import Response + def GET(request): """Get a list of the specifications of all Storages.""" diff --git a/opendc/api/v1/specifications/storages/id/endpoint.py b/opendc/api/v1/specifications/storages/id/endpoint.py index b0d254a4..ebe65857 100644 --- a/opendc/api/v1/specifications/storages/id/endpoint.py +++ b/opendc/api/v1/specifications/storages/id/endpoint.py @@ -2,6 +2,7 @@ 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.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'id': 'int' } ) diff --git a/opendc/api/v1/tiles/tileId/endpoint.py b/opendc/api/v1/tiles/tileId/endpoint.py index deb76195..5ccc9cd7 100644 --- a/opendc/api/v1/tiles/tileId/endpoint.py +++ b/opendc/api/v1/tiles/tileId/endpoint.py @@ -1,7 +1,8 @@ from opendc.models.tile import Tile -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Tile.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int' } ) @@ -41,6 +42,7 @@ def GET(request): tile.to_JSON() ) + def DELETE(request): """Delete this Tile.""" @@ -48,7 +50,7 @@ def DELETE(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int' } ) diff --git a/opendc/api/v1/tiles/tileId/rack/endpoint.py b/opendc/api/v1/tiles/tileId/rack/endpoint.py index 59338e9a..64245856 100644 --- a/opendc/api/v1/tiles/tileId/rack/endpoint.py +++ b/opendc/api/v1/tiles/tileId/rack/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.rack import Rack from opendc.models.tile import Tile -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Tile's Rack.""" @@ -10,11 +11,11 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int' }, ) - + except exceptions.ParameterError as e: return Response(400, e.message) @@ -51,6 +52,7 @@ def GET(request): rack.to_JSON() ) + def POST(request): """Add a Rack to this Tile if it is empty.""" @@ -58,10 +60,10 @@ def POST(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int' }, - body = { + body={ 'rack': { 'name': 'string', 'capacity': 'int', @@ -69,7 +71,7 @@ def POST(request): } } ) - + except exceptions.ParameterError as e: return Response(400, e.message) @@ -93,7 +95,7 @@ def POST(request): 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() @@ -112,7 +114,8 @@ def POST(request): 'Successfully added {}.'.format(rack), rack.to_JSON() ) - + + def PUT(request): """Update the Rack on this Tile.""" @@ -120,10 +123,10 @@ def PUT(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int' }, - body = { + body={ 'rack': { 'name': 'string', 'capacity': 'int', @@ -131,7 +134,7 @@ def PUT(request): } } ) - + except exceptions.ParameterError as e: return Response(400, e.message) @@ -175,6 +178,7 @@ def PUT(request): rack.to_JSON() ) + def DELETE(request): """Delete this Tile's Rack.""" @@ -182,11 +186,11 @@ def DELETE(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int' }, ) - + except exceptions.ParameterError as e: return Response(400, e.message) @@ -217,7 +221,7 @@ def DELETE(request): tile.object_id = None tile.object_type = None - + tile.update() # Delete this Rack diff --git a/opendc/api/v1/tiles/tileId/rack/machines/endpoint.py b/opendc/api/v1/tiles/tileId/rack/machines/endpoint.py index 2d160713..5272c117 100644 --- a/opendc/api/v1/tiles/tileId/rack/machines/endpoint.py +++ b/opendc/api/v1/tiles/tileId/rack/machines/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.machine import Machine from opendc.models.rack import Rack -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Rack's Machines.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int' } ) @@ -45,6 +46,7 @@ def GET(request): [x.to_JSON() for x in machines] ) + def POST(request): """Add a Machine to this rack.""" @@ -52,10 +54,10 @@ def POST(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int' }, - body = { + body={ 'machine': { 'rackId': 'int', 'position': 'int', @@ -91,14 +93,14 @@ def POST(request): 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.') diff --git a/opendc/api/v1/tiles/tileId/rack/machines/position/endpoint.py b/opendc/api/v1/tiles/tileId/rack/machines/position/endpoint.py index 15e6cf96..99011fa4 100644 --- a/opendc/api/v1/tiles/tileId/rack/machines/position/endpoint.py +++ b/opendc/api/v1/tiles/tileId/rack/machines/position/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.machine import Machine from opendc.models.rack import Rack -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get the Machine at this location in this Rack.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int', 'position': 'int' } @@ -43,16 +44,17 @@ def GET(request): machine.to_JSON() ) + def PUT(request): """Update the Machine at this location in this Rack.""" try: request.check_required_parameters( - path = { + path={ 'tileId': 'int', 'position': 'int' }, - body = { + body={ 'machine': { 'rackId': 'int', 'position': 'int', @@ -91,7 +93,7 @@ def PUT(request): # Update this Machine - machine.positoin = request.params_body['machine']['position'] + machine.position = 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'] @@ -100,7 +102,7 @@ def PUT(request): try: machine.update() - + except exceptions.ForeignKeyError: return Response(409, 'Rack position occupied.') @@ -118,6 +120,7 @@ def PUT(request): machine.to_JSON() ) + def DELETE(request): """Delete the Machine at this location in this Rack.""" @@ -125,7 +128,7 @@ def DELETE(request): try: request.check_required_parameters( - path = { + path={ 'tileId': 'int', 'position': 'int' } diff --git a/opendc/api/v1/traces/endpoint.py b/opendc/api/v1/traces/endpoint.py index 05d6fd48..78930b0f 100644 --- a/opendc/api/v1/traces/endpoint.py +++ b/opendc/api/v1/traces/endpoint.py @@ -1,6 +1,7 @@ from opendc.models.trace import Trace from opendc.util.rest import Response + def GET(request): """Get all available Traces.""" diff --git a/opendc/api/v1/traces/traceId/endpoint.py b/opendc/api/v1/traces/traceId/endpoint.py index eabb23a4..50993c41 100644 --- a/opendc/api/v1/traces/traceId/endpoint.py +++ b/opendc/api/v1/traces/traceId/endpoint.py @@ -2,6 +2,7 @@ from opendc.models.trace import Trace from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Trace.""" @@ -9,7 +10,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'traceId': 'int' } ) diff --git a/opendc/api/v1/traces/traceId/jobs/endpoint.py b/opendc/api/v1/traces/traceId/jobs/endpoint.py index 2f271c9e..bd2c6eb0 100644 --- a/opendc/api/v1/traces/traceId/jobs/endpoint.py +++ b/opendc/api/v1/traces/traceId/jobs/endpoint.py @@ -1,8 +1,9 @@ -from opendc.models.trace import Trace from opendc.models.job import Job -from opendc.util import database, exceptions +from opendc.models.trace import Trace +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this Trace's Jobs.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'traceId': 'int' } ) diff --git a/opendc/api/v1/users/endpoint.py b/opendc/api/v1/users/endpoint.py index 1c971b56..abd54f27 100644 --- a/opendc/api/v1/users/endpoint.py +++ b/opendc/api/v1/users/endpoint.py @@ -1,7 +1,8 @@ from opendc.models.user import User -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Search for a User using their email address.""" @@ -9,14 +10,14 @@ def GET(request): try: request.check_required_parameters( - query = { + 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']) @@ -34,6 +35,7 @@ def GET(request): user.to_JSON() ) + def POST(request): """Add a new User.""" @@ -41,7 +43,7 @@ def POST(request): try: request.check_required_parameters( - body = { + body={ 'user': { 'email': 'string' } @@ -52,12 +54,12 @@ def POST(request): return Response(400, e.message) # Instantiate a User - + request.params_body['user']['googleId'] = request.google_id 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)) @@ -65,7 +67,7 @@ def POST(request): # 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.') + return Response(403, 'Forbidden from creating this User.') # Insert the User @@ -74,7 +76,7 @@ def POST(request): # Return a JSON representation of the User return Response( - 200, - 'Successfully created {}'.format(user), + 200, + 'Successfully created {}'.format(user), user.to_JSON() ) diff --git a/opendc/api/v1/users/userId/authorizations/endpoint.py b/opendc/api/v1/users/userId/authorizations/endpoint.py index 2320456f..46ca12ba 100644 --- a/opendc/api/v1/users/userId/authorizations/endpoint.py +++ b/opendc/api/v1/users/userId/authorizations/endpoint.py @@ -1,8 +1,9 @@ from opendc.models.authorization import Authorization from opendc.models.user import User -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def GET(request): """Get this User's Authorizations.""" @@ -10,7 +11,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'userId': 'int' } ) diff --git a/opendc/api/v1/users/userId/endpoint.py b/opendc/api/v1/users/userId/endpoint.py index e4edc107..767c5d13 100644 --- a/opendc/api/v1/users/userId/endpoint.py +++ b/opendc/api/v1/users/userId/endpoint.py @@ -1,7 +1,8 @@ from opendc.models.user import User -from opendc.util import database, exceptions +from opendc.util import exceptions from opendc.util.rest import Response + def DELETE(request): """Delete this user.""" @@ -9,7 +10,7 @@ def DELETE(request): try: request.check_required_parameters( - path = { + path={ 'userId': 'int' } ) @@ -37,10 +38,11 @@ def DELETE(request): return Response( 200, - 'Succesfully deleted {}'.format(user), + 'Successfully deleted {}'.format(user), user.to_JSON() ) + def GET(request): """Get this User.""" @@ -48,7 +50,7 @@ def GET(request): try: request.check_required_parameters( - path = { + path={ 'userId': 'int' } ) @@ -71,6 +73,7 @@ def GET(request): user.to_JSON(), ) + def PUT(request): """Update this User's given name and/ or family name.""" @@ -78,13 +81,13 @@ def PUT(request): try: request.check_required_parameters( - body = { + body={ 'user': { 'givenName': 'string', 'familyName': 'string' } }, - path = { + path={ 'userId': 'int' } ) @@ -103,9 +106,9 @@ def PUT(request): 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'] @@ -118,4 +121,3 @@ def PUT(request): 'Successfully updated {}.'.format(user), user.to_JSON() ) - diff --git a/opendc/models/allowed_object.py b/opendc/models/allowed_object.py index acd58e94..7ff742fe 100644 --- a/opendc/models/allowed_object.py +++ b/opendc/models/allowed_object.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class AllowedObject(Model): +class AllowedObject(Model): JSON_TO_PYTHON_DICT = { 'AllowedObject': { 'roomType': 'room_type', diff --git a/opendc/models/authorization.py b/opendc/models/authorization.py index 90c7d399..82d37b76 100644 --- a/opendc/models/authorization.py +++ b/opendc/models/authorization.py @@ -1,10 +1,8 @@ -import json - from opendc.models.model import Model from opendc.models.user import User -class Authorization(Model): +class Authorization(Model): JSON_TO_PYTHON_DICT = { 'Authorization': { 'userId': 'user_id', @@ -26,12 +24,12 @@ class Authorization(Model): 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.""" @@ -41,7 +39,7 @@ class Authorization(Model): authorization_levels = ['VIEW', 'EDIT', 'OWN'] try: - index_actual = authorization_levels.index(self.authorization_level) + index_actual = authorization_levels.index(self.authorization_level) index_required = authorization_levels.index(required_level) except: return False @@ -50,4 +48,3 @@ class Authorization(Model): return True else: return False - diff --git a/opendc/models/cpu.py b/opendc/models/cpu.py index a2a0e79f..5b9b44fb 100644 --- a/opendc/models/cpu.py +++ b/opendc/models/cpu.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class CPU(Model): +class CPU(Model): JSON_TO_PYTHON_DICT = { 'CPU': { 'id': 'id', diff --git a/opendc/models/datacenter.py b/opendc/models/datacenter.py index 32ce1d49..aeb9b3ad 100644 --- a/opendc/models/datacenter.py +++ b/opendc/models/datacenter.py @@ -1,11 +1,8 @@ -import json - from opendc.models.model import Model from opendc.models.section import Section -from opendc.util import database, exceptions -class Datacenter(Model): +class Datacenter(Model): JSON_TO_PYTHON_DICT = { 'datacenter': { 'id': 'id', diff --git a/opendc/models/experiment.py b/opendc/models/experiment.py index c7381084..e875f8d1 100644 --- a/opendc/models/experiment.py +++ b/opendc/models/experiment.py @@ -1,9 +1,9 @@ from opendc.models.model import Model from opendc.models.simulation import Simulation -from opendc.util import database, exceptions +from opendc.util import exceptions -class Experiment(Model): +class Experiment(Model): JSON_TO_PYTHON_DICT = { 'Experiment': { 'id': 'id', diff --git a/opendc/models/failure_model.py b/opendc/models/failure_model.py index 8dd16d6c..ff6459e9 100644 --- a/opendc/models/failure_model.py +++ b/opendc/models/failure_model.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class FailureModel(Model): +class FailureModel(Model): JSON_TO_PYTHON_DICT = { 'FailureModel': { 'id': 'id', diff --git a/opendc/models/gpu.py b/opendc/models/gpu.py index d9978ec7..37de235c 100644 --- a/opendc/models/gpu.py +++ b/opendc/models/gpu.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class GPU(Model): +class GPU(Model): JSON_TO_PYTHON_DICT = { 'GPU': { 'id': 'id', diff --git a/opendc/models/job.py b/opendc/models/job.py index fb133a72..e013b991 100644 --- a/opendc/models/job.py +++ b/opendc/models/job.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class Job(Model): +class Job(Model): JSON_TO_PYTHON_DICT = { 'Job': { 'id': 'id', diff --git a/opendc/models/machine.py b/opendc/models/machine.py index 90945ef1..0d9fbd54 100644 --- a/opendc/models/machine.py +++ b/opendc/models/machine.py @@ -4,8 +4,8 @@ from opendc.models.model import Model from opendc.models.rack import Rack from opendc.util import database, exceptions -class Machine(Model): +class Machine(Model): JSON_TO_PYTHON_DICT = { 'machine': { 'id': 'id', @@ -34,7 +34,7 @@ class Machine(Model): 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 @@ -48,15 +48,14 @@ class Machine(Model): 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]): + for device_id in getattr(before_insert, before_insert.device_table_to_attribute[device_table]): statement = 'INSERT INTO machine_{} (machine_id, {}) VALUES (%s, %s)'.format( device_table, before_insert.device_table_to_attribute[device_table][:-1] ) - - database.execute(statement, (before_insert.id, device_id)) + + database.execute(statement, (before_insert.id, device_id)) @classmethod def from_tile_id_and_rack_position(cls, tile_id, position): @@ -65,13 +64,13 @@ class Machine(Model): try: rack = Rack.from_tile_id(tile_id) except: - return cls(id = -1) - + return cls(id=-1) + try: statement = 'SELECT id FROM machines WHERE rack_id = %s AND position = %s' machine_id = database.fetchone(statement, (rack.id, position))[0] except: - return cls(id = -1) + return cls(id=-1) return cls.from_primary_key((machine_id,)) @@ -93,7 +92,7 @@ class Machine(Model): """Insert this Machine by also updating its devices.""" before_insert = copy.deepcopy(self) - + super(Machine, self).insert() before_insert.id = self.id @@ -101,21 +100,21 @@ class Machine(Model): 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 = %s'.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): diff --git a/opendc/models/machine_state.py b/opendc/models/machine_state.py index 693b57d2..7f19ba01 100644 --- a/opendc/models/machine_state.py +++ b/opendc/models/machine_state.py @@ -1,8 +1,8 @@ from opendc.models.model import Model from opendc.util import database -class MachineState(Model): +class MachineState(Model): JSON_TO_PYTHON_DICT = { 'MachineState': { 'taskId': 'task_id', @@ -15,21 +15,22 @@ class MachineState(Model): } TABLE_NAME = 'machine_states' - COLUMNS = ['id', 'task_id', 'machine_id', 'experiment_id', 'tick', 'temperature_c', 'in_use_memory_mb', 'load_fraction'] + COLUMNS = ['id', 'task_id', 'machine_id', 'experiment_id', 'tick', 'temperature_c', 'in_use_memory_mb', + 'load_fraction'] - COLUMNS_PRIMARY_KEY= ['id'] + 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] + 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 @@ -37,11 +38,11 @@ class MachineState(Model): """Query MachineStates by their Experiment id.""" machine_states = [] - + statement = 'SELECT * FROM machine_states WHERE experiment_id = %s' results = database.fetchall(statement, (experiment_id,)) - - for row in results: + + for row in results: machine_states.append(cls._from_database_row(row)) return machine_states @@ -51,11 +52,11 @@ class MachineState(Model): """Query MachineStates by their Experiment id and tick.""" machine_states = [] - + statement = 'SELECT * FROM machine_states WHERE experiment_id = %s AND machine_states.tick = %s' results = database.fetchall(statement, (experiment_id, tick)) - - for row in results: + + for row in results: machine_states.append(cls._from_database_row(row)) return machine_states diff --git a/opendc/models/memory.py b/opendc/models/memory.py index 56497bd4..961c0479 100644 --- a/opendc/models/memory.py +++ b/opendc/models/memory.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class Memory(Model): +class Memory(Model): JSON_TO_PYTHON_DICT = { 'Memory': { 'id': 'id', diff --git a/opendc/models/model.py b/opendc/models/model.py index 18ea61f4..30da9c67 100644 --- a/opendc/models/model.py +++ b/opendc/models/model.py @@ -1,7 +1,7 @@ from opendc.util import database, exceptions -class Model(object): +class Model(object): # MUST OVERRIDE IN DERIVED CLASS JSON_TO_PYTHON_DICT = { @@ -9,14 +9,14 @@ class Model(object): 'jsonParameterName': 'python_parameter_name' } } - + PATH = '' PATH_PARAMETERS = {} TABLE_NAME = '' COLUMNS = [] COLUMNS_PRIMARY_KEY = [] - + # INITIALIZATION def __init__(self, **kwargs): @@ -50,7 +50,7 @@ class Model(object): 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) @@ -71,12 +71,11 @@ class Model(object): if hasattr(self, python_name): parameters[json_name] = getattr(self, python_name) - + else: parameters[json_name] = None return parameters - # API CALL GENERATION @@ -114,7 +113,7 @@ class Model(object): @classmethod def _generate_primary_key_string(cls): """Generate the SQLite primary key string for this Model.""" - + return ' AND '.join(['{} = %s'.format(x) for x in cls.COLUMNS_PRIMARY_KEY]) @classmethod @@ -199,7 +198,7 @@ class Model(object): parameters = {} for i, column in enumerate(cls.COLUMNS_PRIMARY_KEY): parameters[column] = primary_key_tuple[i] - + return cls(**parameters) @classmethod @@ -209,7 +208,7 @@ class Model(object): if column_name is not None and value is not None: statement = 'SELECT * FROM {} WHERE {} = %s'.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) @@ -288,7 +287,7 @@ class Model(object): ) values = self._generate_insert_columns_tuple() - + try: last_row_id = database.execute(statement, values) except Exception as e: diff --git a/opendc/models/object.py b/opendc/models/object.py index 4103107a..f9990d81 100644 --- a/opendc/models/object.py +++ b/opendc/models/object.py @@ -1,8 +1,7 @@ from opendc.models.model import Model -from opendc.util import database, exceptions -class Object(Model): +class Object(Model): JSON_TO_PYTHON_DICT = { 'Object': { 'id': 'id', @@ -16,5 +15,5 @@ class Object(Model): 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 index 6ce29b9b..09651a66 100644 --- a/opendc/models/path.py +++ b/opendc/models/path.py @@ -1,10 +1,10 @@ from opendc.models.authorization import Authorization from opendc.models.model import Model from opendc.models.user import User -from opendc.util import database, exceptions +from opendc.util import exceptions -class Path(Model): +class Path(Model): JSON_TO_PYTHON_DICT = { 'Path': { 'id': 'id', diff --git a/opendc/models/queued_experiment.py b/opendc/models/queued_experiment.py index fbaed9cb..1cb52c49 100644 --- a/opendc/models/queued_experiment.py +++ b/opendc/models/queued_experiment.py @@ -1,9 +1,7 @@ from opendc.models.model import Model -from opendc.models.experiment import Experiment -from opendc.util import database, exceptions -class QueuedExperiment(Model): +class QueuedExperiment(Model): JSON_TO_PYTHON_DICT = { 'QueuedExperiment': { 'experimentId': 'experiment_id' diff --git a/opendc/models/rack.py b/opendc/models/rack.py index da965849..74104fcb 100644 --- a/opendc/models/rack.py +++ b/opendc/models/rack.py @@ -1,10 +1,9 @@ from opendc.models.model import Model -from opendc.models.tile import Tile from opendc.models.object import Object -from opendc.util import database, exceptions +from opendc.models.tile import Tile -class Rack(Model): +class Rack(Model): JSON_TO_PYTHON_DICT = { 'rack': { 'id': 'id', @@ -27,7 +26,7 @@ class Rack(Model): tile = Tile.from_primary_key((tile_id,)) if not tile.exists(): - return Rack(id = -1) + return Rack(id=-1) return cls.from_primary_key((tile.object_id,)) @@ -48,7 +47,7 @@ class Rack(Model): def insert(self): """Insert a Rack by first inserting an object.""" - obj = Object(type = 'RACK') + obj = Object(type='RACK') obj.insert() self.id = obj.id diff --git a/opendc/models/rack_state.py b/opendc/models/rack_state.py index e43dc940..c0f0ff6c 100644 --- a/opendc/models/rack_state.py +++ b/opendc/models/rack_state.py @@ -1,8 +1,8 @@ from opendc.models.model import Model from opendc.util import database -class RackState(Model): +class RackState(Model): JSON_TO_PYTHON_DICT = { 'RackState': { 'rackId': 'rack_id', @@ -16,9 +16,9 @@ class RackState(Model): """Instantiate a RackState from a database row.""" return cls( - rack_id = row[0], - load_fraction = row[1], - tick = row[2] + rack_id=row[0], + load_fraction=row[1], + tick=row[2] ) @classmethod @@ -63,7 +63,6 @@ class RackState(Model): 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.""" diff --git a/opendc/models/room.py b/opendc/models/room.py index 76f9f7b3..66346bb2 100644 --- a/opendc/models/room.py +++ b/opendc/models/room.py @@ -1,9 +1,9 @@ -from opendc.models.model import Model from opendc.models.datacenter import Datacenter -from opendc.util import database, exceptions +from opendc.models.model import Model +from opendc.util import exceptions -class Room(Model): +class Room(Model): JSON_TO_PYTHON_DICT = { 'room': { 'id': 'id', diff --git a/opendc/models/room_state.py b/opendc/models/room_state.py index 169aaa55..2729407f 100644 --- a/opendc/models/room_state.py +++ b/opendc/models/room_state.py @@ -1,8 +1,8 @@ from opendc.models.model import Model from opendc.util import database -class RoomState(Model): +class RoomState(Model): JSON_TO_PYTHON_DICT = { 'RoomState': { 'roomId': 'room_id', @@ -16,9 +16,9 @@ class RoomState(Model): """Instantiate a RoomState from a database row.""" return cls( - room_id = row[0], - load_fraction = row[1], - tick = row[2] + room_id=row[0], + load_fraction=row[1], + tick=row[2] ) @classmethod @@ -71,7 +71,6 @@ class RoomState(Model): 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.""" diff --git a/opendc/models/room_type.py b/opendc/models/room_type.py index 73b06cc1..1d107e95 100644 --- a/opendc/models/room_type.py +++ b/opendc/models/room_type.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class RoomType(Model): +class RoomType(Model): JSON_TO_PYTHON_DICT = { 'RoomType': { 'name': 'name' diff --git a/opendc/models/scheduler.py b/opendc/models/scheduler.py index 9d78ec6f..b70830ab 100644 --- a/opendc/models/scheduler.py +++ b/opendc/models/scheduler.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class Scheduler(Model): +class Scheduler(Model): JSON_TO_PYTHON_DICT = { 'Scheduler': { 'name': 'name' diff --git a/opendc/models/section.py b/opendc/models/section.py index 5434cdfb..4e953eae 100644 --- a/opendc/models/section.py +++ b/opendc/models/section.py @@ -1,9 +1,9 @@ from opendc.models.model import Model from opendc.models.path import Path -from opendc.util import database, exceptions +from opendc.util import exceptions -class Section(Model): +class Section(Model): JSON_TO_PYTHON_DICT = { 'Section': { 'id': 'id', @@ -23,7 +23,7 @@ class Section(Model): # Get the Path try: - path = Path.from_primary_key((self.path_id,)) + path = Path.from_primary_key((self.path_id,)) except exceptions.RowNotFoundError: return False diff --git a/opendc/models/simulation.py b/opendc/models/simulation.py index b698867c..8c3726c8 100644 --- a/opendc/models/simulation.py +++ b/opendc/models/simulation.py @@ -1,12 +1,10 @@ -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 +from opendc.util import exceptions -class Simulation(Model): +class Simulation(Model): JSON_TO_PYTHON_DICT = { 'Simulation': { 'id': 'id', @@ -22,7 +20,7 @@ class Simulation(Model): 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: diff --git a/opendc/models/storage.py b/opendc/models/storage.py index e82fa0b3..02c568fb 100644 --- a/opendc/models/storage.py +++ b/opendc/models/storage.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class Storage(Model): +class Storage(Model): JSON_TO_PYTHON_DICT = { 'Storage': { 'id': 'id', diff --git a/opendc/models/task.py b/opendc/models/task.py index da0f5785..4e6485fb 100644 --- a/opendc/models/task.py +++ b/opendc/models/task.py @@ -1,7 +1,7 @@ from opendc.models.model import Model + class Task(Model): - JSON_TO_PYTHON_DICT = { 'Task': { 'id': 'id', diff --git a/opendc/models/task_duration.py b/opendc/models/task_duration.py index 0d3432e3..1dc3ca01 100644 --- a/opendc/models/task_duration.py +++ b/opendc/models/task_duration.py @@ -1,8 +1,8 @@ from opendc.models.model import Model from opendc.util import database -class TaskDuration(Model): +class TaskDuration(Model): JSON_TO_PYTHON_DICT = { 'TaskDuration': { 'taskId': 'task_id', @@ -15,8 +15,8 @@ class TaskDuration(Model): """Instantiate a RoomState from a database row.""" return cls( - task_id = row[0], - duration = row[1] + task_id=row[0], + duration=row[1] ) @classmethod diff --git a/opendc/models/task_state.py b/opendc/models/task_state.py index 7d216aa0..8dca2d03 100644 --- a/opendc/models/task_state.py +++ b/opendc/models/task_state.py @@ -1,8 +1,8 @@ from opendc.models.model import Model from opendc.util import database -class TaskState(Model): +class TaskState(Model): JSON_TO_PYTHON_DICT = { 'TaskState': { 'id': 'id', @@ -31,18 +31,18 @@ class TaskState(Model): 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] + 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.""" + """Return True if the User has at least the given auth level over this TaskState.""" if authorization_level in ['EDIT', 'OWN']: return False diff --git a/opendc/models/tile.py b/opendc/models/tile.py index 748c76c5..344b6135 100644 --- a/opendc/models/tile.py +++ b/opendc/models/tile.py @@ -1,10 +1,10 @@ from opendc.models.model import Model -from opendc.models.room import Room from opendc.models.object import Object -from opendc.util import database, exceptions +from opendc.models.room import Room +from opendc.util import exceptions -class Tile(Model): +class Tile(Model): JSON_TO_PYTHON_DICT = { 'tile': { 'id': 'id', @@ -42,6 +42,5 @@ class Tile(Model): 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 index ce8d4923..99245ac3 100644 --- a/opendc/models/trace.py +++ b/opendc/models/trace.py @@ -1,7 +1,7 @@ from opendc.models.model import Model -class Trace(Model): +class Trace(Model): JSON_TO_PYTHON_DICT = { 'Trace': { 'id': 'id', diff --git a/opendc/models/user.py b/opendc/models/user.py index 885170d0..fde45b0c 100644 --- a/opendc/models/user.py +++ b/opendc/models/user.py @@ -1,9 +1,7 @@ -import json - from opendc.models.model import Model -class User(Model): +class User(Model): JSON_TO_PYTHON_DICT = { 'User': { 'id': 'id', diff --git a/opendc/util/database.py b/opendc/util/database.py index 32aa947c..e4c257d5 100644 --- a/opendc/util/database.py +++ b/opendc/util/database.py @@ -1,7 +1,6 @@ -from datetime import datetime import json -import sqlite3 import sys +from datetime import datetime from mysql.connector.pooling import MySQLConnectionPool @@ -12,10 +11,12 @@ with open(sys.argv[1]) as file: DATETIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S' CONNECTION_POOL = None + def init_connection_pool(user, password, database, host, port): global CONNECTION_POOL - CONNECTION_POOL = MySQLConnectionPool(pool_name = "opendcpool", pool_size = 5, - user=user, password=password, database=database, host=host, port=port) + CONNECTION_POOL = MySQLConnectionPool(pool_name="opendcpool", pool_size=5, + user=user, password=password, database=database, host=host, port=port) + def execute(statement, t): """Open a database connection and execute the statement.""" @@ -23,7 +24,7 @@ def execute(statement, t): # Connect to the database connection = CONNECTION_POOL.get_connection() cursor = connection.cursor() - + # Execute the statement cursor.execute(statement, t) @@ -38,6 +39,7 @@ def execute(statement, t): # Return the id return row_id + def fetchone(statement, t=None): """Open a database connection and return the first row matched by the SELECT statement.""" @@ -58,6 +60,7 @@ def fetchone(statement, t=None): connection.close() return value + def fetchall(statement, t=None): """Open a database connection and return all rows matched by the SELECT statement.""" @@ -66,7 +69,7 @@ def fetchall(statement, t=None): cursor = connection.cursor() # Execute the SELECT statement - + if t is not None: cursor.execute(statement, t) else: @@ -78,11 +81,13 @@ def fetchall(statement, t=None): 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.""" diff --git a/opendc/util/exceptions.py b/opendc/util/exceptions.py index 56a04ab9..8eea268a 100644 --- a/opendc/util/exceptions.py +++ b/opendc/util/exceptions.py @@ -1,24 +1,30 @@ 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.""" @@ -29,8 +35,10 @@ class RowNotFoundError(Exception): self.table_name = table_name + class ParameterError(Exception): - """Raised when a paramter is either missing or incorrectly typed.""" + """Raised when a parameter is either missing or incorrectly typed.""" + class IncorrectParameterError(ParameterError): """Raised when a parameter is of the wrong type.""" @@ -46,6 +54,7 @@ class IncorrectParameterError(ParameterError): self.parameter_name = parameter_name self.parameter_location = parameter_location + class MissingParameterError(ParameterError): """Raised when a parameter is missing.""" diff --git a/opendc/util/parameter_checker.py b/opendc/util/parameter_checker.py index 32cd6777..5188e56a 100644 --- a/opendc/util/parameter_checker.py +++ b/opendc/util/parameter_checker.py @@ -1,21 +1,22 @@ 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) + param_actual = params_actual.get(param_name) if isinstance(param_required, dict): - + param_missing = _missing_parameter( - param_required, - param_actual, + param_required, + param_actual, param_name ) @@ -24,13 +25,14 @@ def _missing_parameter(params_required, params_actual, parent=''): 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) + param_actual = params_actual.get(param_name) if isinstance(param_required, dict): @@ -60,6 +62,7 @@ def _incorrect_parameter(params_required, params_actual, parent=''): 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.""" @@ -67,11 +70,12 @@ def _format_parameter(parameter): 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) @@ -79,7 +83,7 @@ def check(request, **kwargs): raise exceptions.MissingParameterError( _format_parameter(missing_parameter), location - ) + ) incorrect_parameter = _incorrect_parameter(params_required, params_actual) if incorrect_parameter is not None: @@ -87,4 +91,3 @@ def check(request, **kwargs): _format_parameter(incorrect_parameter), location ) - diff --git a/opendc/util/path_parser.py b/opendc/util/path_parser.py index 292b747b..7948ee1b 100644 --- a/opendc/util/path_parser.py +++ b/opendc/util/path_parser.py @@ -1,6 +1,6 @@ import json -import sys, os -import re +import os + def parse(version, endpoint_path): """Map an HTTP endpoint path to an API path""" diff --git a/opendc/util/rest.py b/opendc/util/rest.py index ad53f084..7cf2d0b3 100644 --- a/opendc/util/rest.py +++ b/opendc/util/rest.py @@ -1,6 +1,5 @@ import importlib import json -import os import sys from oauth2client import client, crypt @@ -10,6 +9,7 @@ from opendc.util import exceptions, parameter_checker with open(sys.argv[1]) as file: KEYS = json.load(file) + class Request(object): """WebSocket message to REST request mapping.""" @@ -23,16 +23,16 @@ class Request(object): 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: @@ -40,9 +40,9 @@ class Request(object): # Parse the path and import the appropriate module - try: + try: self.path = message['path'].encode('ascii', 'ignore').strip('/') - + module_base = 'opendc.api.{}.endpoint' module_path = self.path.translate(None, '{}').replace('/', '.') @@ -62,10 +62,11 @@ class Request(object): 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)) + raise exceptions.UnsupportedMethodError( + 'Unimplemented method at endpoint {}: {}'.format(self.path, self.method)) # Verify the user - + try: self.google_id = self._verify_token(self.token) @@ -87,7 +88,7 @@ class Request(object): raise crypt.AppIdentityError('Unrecognized client.') if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: - raise crypt.AppIdentityError('Wrong issuer.') + raise crypt.AppIdentityError('Wrong issuer.') return idinfo['sub'] @@ -114,6 +115,7 @@ class Request(object): return json.dumps(self.message) + class Response(object): """Response to websocket mapping""" @@ -125,7 +127,7 @@ class Response(object): 'description': status_description } self.content = content - + def to_JSON(self): """"Return a JSON representation of this Response""" |
