From ff31029e732dd56743690dc608f535163a0548ff Mon Sep 17 00:00:00 2001 From: Georgios Andreadis Date: Thu, 25 Jun 2020 14:48:24 +0200 Subject: Experiment --- main.py | 2 +- opendc/api/v2/datacenters/datacenterId/endpoint.py | 2 +- .../v2/datacenters/datacenterId/rooms/endpoint.py | 4 +- opendc/api/v2/experiments/experimentId/endpoint.py | 2 +- .../experimentId/last-simulated-tick/endpoint.py | 2 +- .../experimentId/machine-states/endpoint.py | 4 +- .../experimentId/rack-states/endpoint.py | 4 +- .../experimentId/room-states/endpoint.py | 4 +- .../statistics/task-durations/endpoint.py | 4 +- .../experimentId/task-states/endpoint.py | 4 +- opendc/api/v2/jobs/jobId/endpoint.py | 2 +- opendc/api/v2/jobs/jobId/tasks/endpoint.py | 4 +- opendc/api/v2/paths/pathId/branches/endpoint.py | 16 +- opendc/api/v2/paths/pathId/endpoint.py | 2 +- opendc/api/v2/paths/pathId/sections/endpoint.py | 4 +- opendc/api/v2/room-types/endpoint.py | 2 +- .../v2/room-types/name/allowed-objects/endpoint.py | 2 +- opendc/api/v2/rooms/roomId/endpoint.py | 2 +- opendc/api/v2/rooms/roomId/tiles/endpoint.py | 4 +- opendc/api/v2/schedulers/endpoint.py | 2 +- opendc/api/v2/sections/sectionId/endpoint.py | 2 +- opendc/api/v2/simulations/endpoint.py | 12 +- .../simulationId/authorizations/endpoint.py | 4 +- .../simulationId/authorizations/userId/endpoint.py | 6 +- .../simulationId/datacenters/endpoint.py | 4 +- opendc/api/v2/simulations/simulationId/endpoint.py | 2 +- .../simulationId/experiments/endpoint.py | 4 +- .../v2/simulations/simulationId/paths/endpoint.py | 4 +- opendc/api/v2/specifications/cpus/endpoint.py | 2 +- opendc/api/v2/specifications/cpus/id/endpoint.py | 2 +- .../v2/specifications/failure-models/endpoint.py | 2 +- .../specifications/failure-models/id/endpoint.py | 2 +- opendc/api/v2/specifications/gpus/endpoint.py | 2 +- opendc/api/v2/specifications/gpus/id/endpoint.py | 2 +- opendc/api/v2/specifications/memories/endpoint.py | 2 +- .../api/v2/specifications/memories/id/endpoint.py | 2 +- opendc/api/v2/specifications/storages/endpoint.py | 2 +- .../api/v2/specifications/storages/id/endpoint.py | 2 +- opendc/api/v2/tiles/tileId/endpoint.py | 2 +- opendc/api/v2/tiles/tileId/rack/endpoint.py | 4 +- .../api/v2/tiles/tileId/rack/machines/endpoint.py | 4 +- .../tileId/rack/machines/position/endpoint.py | 4 +- opendc/api/v2/traces/endpoint.py | 2 +- opendc/api/v2/traces/traceId/endpoint.py | 2 +- opendc/api/v2/traces/traceId/jobs/endpoint.py | 4 +- opendc/api/v2/users/userId/endpoint.py | 48 ++-- opendc/models/allowed_object.py | 22 -- opendc/models/authorization.py | 45 --- opendc/models/cpu.py | 34 --- opendc/models/datacenter.py | 27 -- opendc/models/experiment.py | 36 --- opendc/models/failure_model.py | 17 -- opendc/models/gpu.py | 34 --- opendc/models/job.py | 14 - opendc/models/machine.py | 122 --------- opendc/models/machine_state.py | 71 ----- opendc/models/memory.py | 34 --- opendc/models/model.py | 303 --------------------- opendc/models/object.py | 14 - opendc/models/path.py | 35 --- opendc/models/queued_experiment.py | 9 - opendc/models/rack.py | 61 ----- opendc/models/rack_state.py | 63 ----- opendc/models/room.py | 35 --- opendc/models/room_state.py | 71 ----- opendc/models/room_type.py | 17 -- opendc/models/scheduler.py | 14 - opendc/models/section.py | 32 --- opendc/models/simulation.py | 39 --- opendc/models/storage.py | 34 --- opendc/models/task.py | 22 -- opendc/models/task_duration.py | 39 --- opendc/models/task_state.py | 42 --- opendc/models/tile.py | 47 ---- opendc/models/trace.py | 14 - opendc/models/user.py | 57 ++-- opendc/models_old/__init__.py | 0 opendc/models_old/allowed_object.py | 22 ++ opendc/models_old/authorization.py | 45 +++ opendc/models_old/cpu.py | 34 +++ opendc/models_old/datacenter.py | 27 ++ opendc/models_old/experiment.py | 36 +++ opendc/models_old/failure_model.py | 17 ++ opendc/models_old/gpu.py | 34 +++ opendc/models_old/job.py | 14 + opendc/models_old/machine.py | 122 +++++++++ opendc/models_old/machine_state.py | 71 +++++ opendc/models_old/memory.py | 34 +++ opendc/models_old/model.py | 303 +++++++++++++++++++++ opendc/models_old/object.py | 14 + opendc/models_old/path.py | 35 +++ opendc/models_old/queued_experiment.py | 9 + opendc/models_old/rack.py | 61 +++++ opendc/models_old/rack_state.py | 63 +++++ opendc/models_old/room.py | 35 +++ opendc/models_old/room_state.py | 71 +++++ opendc/models_old/room_type.py | 17 ++ opendc/models_old/scheduler.py | 14 + opendc/models_old/section.py | 32 +++ opendc/models_old/simulation.py | 39 +++ opendc/models_old/storage.py | 34 +++ opendc/models_old/task.py | 22 ++ opendc/models_old/task_duration.py | 39 +++ opendc/models_old/task_state.py | 42 +++ opendc/models_old/tile.py | 47 ++++ opendc/models_old/trace.py | 14 + opendc/models_old/user.py | 47 ++++ 107 files changed, 1509 insertions(+), 1489 deletions(-) delete mode 100644 opendc/models/allowed_object.py delete mode 100644 opendc/models/authorization.py delete mode 100644 opendc/models/cpu.py delete mode 100644 opendc/models/datacenter.py delete mode 100644 opendc/models/experiment.py delete mode 100644 opendc/models/failure_model.py delete mode 100644 opendc/models/gpu.py delete mode 100644 opendc/models/job.py delete mode 100644 opendc/models/machine.py delete mode 100644 opendc/models/machine_state.py delete mode 100644 opendc/models/memory.py delete mode 100644 opendc/models/model.py delete mode 100644 opendc/models/object.py delete mode 100644 opendc/models/path.py delete mode 100644 opendc/models/queued_experiment.py delete mode 100644 opendc/models/rack.py delete mode 100644 opendc/models/rack_state.py delete mode 100644 opendc/models/room.py delete mode 100644 opendc/models/room_state.py delete mode 100644 opendc/models/room_type.py delete mode 100644 opendc/models/scheduler.py delete mode 100644 opendc/models/section.py delete mode 100644 opendc/models/simulation.py delete mode 100644 opendc/models/storage.py delete mode 100644 opendc/models/task.py delete mode 100644 opendc/models/task_duration.py delete mode 100644 opendc/models/task_state.py delete mode 100644 opendc/models/tile.py delete mode 100644 opendc/models/trace.py create mode 100644 opendc/models_old/__init__.py create mode 100644 opendc/models_old/allowed_object.py create mode 100644 opendc/models_old/authorization.py create mode 100644 opendc/models_old/cpu.py create mode 100644 opendc/models_old/datacenter.py create mode 100644 opendc/models_old/experiment.py create mode 100644 opendc/models_old/failure_model.py create mode 100644 opendc/models_old/gpu.py create mode 100644 opendc/models_old/job.py create mode 100644 opendc/models_old/machine.py create mode 100644 opendc/models_old/machine_state.py create mode 100644 opendc/models_old/memory.py create mode 100644 opendc/models_old/model.py create mode 100644 opendc/models_old/object.py create mode 100644 opendc/models_old/path.py create mode 100644 opendc/models_old/queued_experiment.py create mode 100644 opendc/models_old/rack.py create mode 100644 opendc/models_old/rack_state.py create mode 100644 opendc/models_old/room.py create mode 100644 opendc/models_old/room_state.py create mode 100644 opendc/models_old/room_type.py create mode 100644 opendc/models_old/scheduler.py create mode 100644 opendc/models_old/section.py create mode 100644 opendc/models_old/simulation.py create mode 100644 opendc/models_old/storage.py create mode 100644 opendc/models_old/task.py create mode 100644 opendc/models_old/task_duration.py create mode 100644 opendc/models_old/task_state.py create mode 100644 opendc/models_old/tile.py create mode 100644 opendc/models_old/trace.py create mode 100644 opendc/models_old/user.py diff --git a/main.py b/main.py index 9d0a58cc..cd9394d5 100644 --- a/main.py +++ b/main.py @@ -9,7 +9,7 @@ from flask_compress import Compress from oauth2client import client, crypt from flask_cors import CORS -from opendc.models.user import User +from opendc.models_old.user import User from opendc.util import rest, path_parser, database from opendc.util.exceptions import AuthorizationTokenError, RequestInitializationError diff --git a/opendc/api/v2/datacenters/datacenterId/endpoint.py b/opendc/api/v2/datacenters/datacenterId/endpoint.py index 3265abb2..67fbfcd8 100644 --- a/opendc/api/v2/datacenters/datacenterId/endpoint.py +++ b/opendc/api/v2/datacenters/datacenterId/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.datacenter import Datacenter +from opendc.models_old.datacenter import Datacenter from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/datacenters/datacenterId/rooms/endpoint.py b/opendc/api/v2/datacenters/datacenterId/rooms/endpoint.py index 593b38a7..96ee7028 100644 --- a/opendc/api/v2/datacenters/datacenterId/rooms/endpoint.py +++ b/opendc/api/v2/datacenters/datacenterId/rooms/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.datacenter import Datacenter -from opendc.models.room import Room +from opendc.models_old.datacenter import Datacenter +from opendc.models_old.room import Room from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/experiments/experimentId/endpoint.py b/opendc/api/v2/experiments/experimentId/endpoint.py index 4ae4abf2..bc2b139e 100644 --- a/opendc/api/v2/experiments/experimentId/endpoint.py +++ b/opendc/api/v2/experiments/experimentId/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.experiment import Experiment +from opendc.models_old.experiment import Experiment from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/experiments/experimentId/last-simulated-tick/endpoint.py b/opendc/api/v2/experiments/experimentId/last-simulated-tick/endpoint.py index 554c03b5..3309502c 100644 --- a/opendc/api/v2/experiments/experimentId/last-simulated-tick/endpoint.py +++ b/opendc/api/v2/experiments/experimentId/last-simulated-tick/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.experiment import Experiment +from opendc.models_old.experiment import Experiment from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/experiments/experimentId/machine-states/endpoint.py b/opendc/api/v2/experiments/experimentId/machine-states/endpoint.py index e903e691..c7dcad9a 100644 --- a/opendc/api/v2/experiments/experimentId/machine-states/endpoint.py +++ b/opendc/api/v2/experiments/experimentId/machine-states/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.experiment import Experiment -from opendc.models.machine_state import MachineState +from opendc.models_old.experiment import Experiment +from opendc.models_old.machine_state import MachineState from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/experiments/experimentId/rack-states/endpoint.py b/opendc/api/v2/experiments/experimentId/rack-states/endpoint.py index a1841bf0..f3acf56a 100644 --- a/opendc/api/v2/experiments/experimentId/rack-states/endpoint.py +++ b/opendc/api/v2/experiments/experimentId/rack-states/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.experiment import Experiment -from opendc.models.rack_state import RackState +from opendc.models_old.experiment import Experiment +from opendc.models_old.rack_state import RackState from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/experiments/experimentId/room-states/endpoint.py b/opendc/api/v2/experiments/experimentId/room-states/endpoint.py index 19ecec22..db3f8b14 100644 --- a/opendc/api/v2/experiments/experimentId/room-states/endpoint.py +++ b/opendc/api/v2/experiments/experimentId/room-states/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.experiment import Experiment -from opendc.models.room_state import RoomState +from opendc.models_old.experiment import Experiment +from opendc.models_old.room_state import RoomState from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/experiments/experimentId/statistics/task-durations/endpoint.py b/opendc/api/v2/experiments/experimentId/statistics/task-durations/endpoint.py index 6bc0d4bd..498db239 100644 --- a/opendc/api/v2/experiments/experimentId/statistics/task-durations/endpoint.py +++ b/opendc/api/v2/experiments/experimentId/statistics/task-durations/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.experiment import Experiment -from opendc.models.task_duration import TaskDuration +from opendc.models_old.experiment import Experiment +from opendc.models_old.task_duration import TaskDuration from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/experiments/experimentId/task-states/endpoint.py b/opendc/api/v2/experiments/experimentId/task-states/endpoint.py index b4d8a702..c0ae47fc 100644 --- a/opendc/api/v2/experiments/experimentId/task-states/endpoint.py +++ b/opendc/api/v2/experiments/experimentId/task-states/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.experiment import Experiment -from opendc.models.task_state import TaskState +from opendc.models_old.experiment import Experiment +from opendc.models_old.task_state import TaskState from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/jobs/jobId/endpoint.py b/opendc/api/v2/jobs/jobId/endpoint.py index 4dc43728..45eedf3f 100644 --- a/opendc/api/v2/jobs/jobId/endpoint.py +++ b/opendc/api/v2/jobs/jobId/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.job import Job +from opendc.models_old.job import Job from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/jobs/jobId/tasks/endpoint.py b/opendc/api/v2/jobs/jobId/tasks/endpoint.py index f2cb3384..cae5ac90 100644 --- a/opendc/api/v2/jobs/jobId/tasks/endpoint.py +++ b/opendc/api/v2/jobs/jobId/tasks/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.job import Job -from opendc.models.task import Task +from opendc.models_old.job import Job +from opendc.models_old.task import Task from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/paths/pathId/branches/endpoint.py b/opendc/api/v2/paths/pathId/branches/endpoint.py index d3256e8c..6b0eebbd 100644 --- a/opendc/api/v2/paths/pathId/branches/endpoint.py +++ b/opendc/api/v2/paths/pathId/branches/endpoint.py @@ -1,13 +1,13 @@ 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.models_old.datacenter import Datacenter +from opendc.models_old.machine import Machine +from opendc.models_old.object import Object +from opendc.models_old.path import Path +from opendc.models_old.rack import Rack +from opendc.models_old.room import Room +from opendc.models_old.section import Section +from opendc.models_old.tile import Tile from opendc.util import database, exceptions from opendc.util.rest import Request, Response diff --git a/opendc/api/v2/paths/pathId/endpoint.py b/opendc/api/v2/paths/pathId/endpoint.py index 42357fc5..a3348618 100644 --- a/opendc/api/v2/paths/pathId/endpoint.py +++ b/opendc/api/v2/paths/pathId/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.path import Path +from opendc.models_old.path import Path from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/paths/pathId/sections/endpoint.py b/opendc/api/v2/paths/pathId/sections/endpoint.py index a983ff1f..8f3e270b 100644 --- a/opendc/api/v2/paths/pathId/sections/endpoint.py +++ b/opendc/api/v2/paths/pathId/sections/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.path import Path -from opendc.models.section import Section +from opendc.models_old.path import Path +from opendc.models_old.section import Section from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/room-types/endpoint.py b/opendc/api/v2/room-types/endpoint.py index 14675c86..71efc75d 100644 --- a/opendc/api/v2/room-types/endpoint.py +++ b/opendc/api/v2/room-types/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.room_type import RoomType +from opendc.models_old.room_type import RoomType from opendc.util.rest import Response diff --git a/opendc/api/v2/room-types/name/allowed-objects/endpoint.py b/opendc/api/v2/room-types/name/allowed-objects/endpoint.py index 166781e8..7b605c2b 100644 --- a/opendc/api/v2/room-types/name/allowed-objects/endpoint.py +++ b/opendc/api/v2/room-types/name/allowed-objects/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.allowed_object import AllowedObject +from opendc.models_old.allowed_object import AllowedObject from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/rooms/roomId/endpoint.py b/opendc/api/v2/rooms/roomId/endpoint.py index 90bcdfd6..663760aa 100644 --- a/opendc/api/v2/rooms/roomId/endpoint.py +++ b/opendc/api/v2/rooms/roomId/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.room import Room +from opendc.models_old.room import Room from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/rooms/roomId/tiles/endpoint.py b/opendc/api/v2/rooms/roomId/tiles/endpoint.py index 971514ec..3385dd36 100644 --- a/opendc/api/v2/rooms/roomId/tiles/endpoint.py +++ b/opendc/api/v2/rooms/roomId/tiles/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.room import Room -from opendc.models.tile import Tile +from opendc.models_old.room import Room +from opendc.models_old.tile import Tile from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/schedulers/endpoint.py b/opendc/api/v2/schedulers/endpoint.py index 224ecfb8..4f3948a9 100644 --- a/opendc/api/v2/schedulers/endpoint.py +++ b/opendc/api/v2/schedulers/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.scheduler import Scheduler +from opendc.models_old.scheduler import Scheduler from opendc.util.rest import Response diff --git a/opendc/api/v2/sections/sectionId/endpoint.py b/opendc/api/v2/sections/sectionId/endpoint.py index 80e15328..58af44b5 100644 --- a/opendc/api/v2/sections/sectionId/endpoint.py +++ b/opendc/api/v2/sections/sectionId/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.section import Section +from opendc.models_old.section import Section from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/simulations/endpoint.py b/opendc/api/v2/simulations/endpoint.py index 3eb7e903..7ef90e97 100644 --- a/opendc/api/v2/simulations/endpoint.py +++ b/opendc/api/v2/simulations/endpoint.py @@ -1,11 +1,11 @@ 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.models_old.authorization import Authorization +from opendc.models_old.datacenter import Datacenter +from opendc.models_old.path import Path +from opendc.models_old.section import Section +from opendc.models_old.simulation import Simulation +from opendc.models_old.user import User from opendc.util import database, exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py b/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py index b0a54524..bc1a7dc3 100644 --- a/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py +++ b/opendc/api/v2/simulations/simulationId/authorizations/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.authorization import Authorization -from opendc.models.simulation import Simulation +from opendc.models_old.authorization import Authorization +from opendc.models_old.simulation import Simulation from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/simulations/simulationId/authorizations/userId/endpoint.py b/opendc/api/v2/simulations/simulationId/authorizations/userId/endpoint.py index 19d13a65..d132b1dd 100644 --- a/opendc/api/v2/simulations/simulationId/authorizations/userId/endpoint.py +++ b/opendc/api/v2/simulations/simulationId/authorizations/userId/endpoint.py @@ -1,6 +1,6 @@ -from opendc.models.authorization import Authorization -from opendc.models.simulation import Simulation -from opendc.models.user import User +from opendc.models_old.authorization import Authorization +from opendc.models_old.simulation import Simulation +from opendc.models_old.user import User from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/simulations/simulationId/datacenters/endpoint.py b/opendc/api/v2/simulations/simulationId/datacenters/endpoint.py index c1d49228..dbef2e8f 100644 --- a/opendc/api/v2/simulations/simulationId/datacenters/endpoint.py +++ b/opendc/api/v2/simulations/simulationId/datacenters/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.datacenter import Datacenter -from opendc.models.simulation import Simulation +from opendc.models_old.datacenter import Datacenter +from opendc.models_old.simulation import Simulation from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/simulations/simulationId/endpoint.py b/opendc/api/v2/simulations/simulationId/endpoint.py index 4aa33c7a..09714560 100644 --- a/opendc/api/v2/simulations/simulationId/endpoint.py +++ b/opendc/api/v2/simulations/simulationId/endpoint.py @@ -1,6 +1,6 @@ from datetime import datetime -from opendc.models.simulation import Simulation +from opendc.models_old.simulation import Simulation from opendc.util import database, exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/simulations/simulationId/experiments/endpoint.py b/opendc/api/v2/simulations/simulationId/experiments/endpoint.py index 07305690..5ecaffb7 100644 --- a/opendc/api/v2/simulations/simulationId/experiments/endpoint.py +++ b/opendc/api/v2/simulations/simulationId/experiments/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.experiment import Experiment -from opendc.models.simulation import Simulation +from opendc.models_old.experiment import Experiment +from opendc.models_old.simulation import Simulation from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/simulations/simulationId/paths/endpoint.py b/opendc/api/v2/simulations/simulationId/paths/endpoint.py index 69a302ba..4e4a1ec7 100644 --- a/opendc/api/v2/simulations/simulationId/paths/endpoint.py +++ b/opendc/api/v2/simulations/simulationId/paths/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.path import Path -from opendc.models.simulation import Simulation +from opendc.models_old.path import Path +from opendc.models_old.simulation import Simulation from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/cpus/endpoint.py b/opendc/api/v2/specifications/cpus/endpoint.py index 87975221..b2ec36f4 100644 --- a/opendc/api/v2/specifications/cpus/endpoint.py +++ b/opendc/api/v2/specifications/cpus/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.cpu import CPU +from opendc.models_old.cpu import CPU from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/cpus/id/endpoint.py b/opendc/api/v2/specifications/cpus/id/endpoint.py index 205b61c5..83cda92d 100644 --- a/opendc/api/v2/specifications/cpus/id/endpoint.py +++ b/opendc/api/v2/specifications/cpus/id/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.cpu import CPU +from opendc.models_old.cpu import CPU from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/failure-models/endpoint.py b/opendc/api/v2/specifications/failure-models/endpoint.py index 6397e27e..63807ed2 100644 --- a/opendc/api/v2/specifications/failure-models/endpoint.py +++ b/opendc/api/v2/specifications/failure-models/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.failure_model import FailureModel +from opendc.models_old.failure_model import FailureModel from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/failure-models/id/endpoint.py b/opendc/api/v2/specifications/failure-models/id/endpoint.py index db450f70..bfba4f16 100644 --- a/opendc/api/v2/specifications/failure-models/id/endpoint.py +++ b/opendc/api/v2/specifications/failure-models/id/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.failure_model import FailureModel +from opendc.models_old.failure_model import FailureModel from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/gpus/endpoint.py b/opendc/api/v2/specifications/gpus/endpoint.py index 24beb873..d536ba47 100644 --- a/opendc/api/v2/specifications/gpus/endpoint.py +++ b/opendc/api/v2/specifications/gpus/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.gpu import GPU +from opendc.models_old.gpu import GPU from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/gpus/id/endpoint.py b/opendc/api/v2/specifications/gpus/id/endpoint.py index 489b7e8d..9a0c0f75 100644 --- a/opendc/api/v2/specifications/gpus/id/endpoint.py +++ b/opendc/api/v2/specifications/gpus/id/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.gpu import GPU +from opendc.models_old.gpu import GPU from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/memories/endpoint.py b/opendc/api/v2/specifications/memories/endpoint.py index 95025418..7a8f6a7a 100644 --- a/opendc/api/v2/specifications/memories/endpoint.py +++ b/opendc/api/v2/specifications/memories/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.memory import Memory +from opendc.models_old.memory import Memory from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/memories/id/endpoint.py b/opendc/api/v2/specifications/memories/id/endpoint.py index f34ca36f..f8922833 100644 --- a/opendc/api/v2/specifications/memories/id/endpoint.py +++ b/opendc/api/v2/specifications/memories/id/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.memory import Memory +from opendc.models_old.memory import Memory from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/storages/endpoint.py b/opendc/api/v2/specifications/storages/endpoint.py index 945b89b2..20b9b794 100644 --- a/opendc/api/v2/specifications/storages/endpoint.py +++ b/opendc/api/v2/specifications/storages/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.storage import Storage +from opendc.models_old.storage import Storage from opendc.util.rest import Response diff --git a/opendc/api/v2/specifications/storages/id/endpoint.py b/opendc/api/v2/specifications/storages/id/endpoint.py index 1b7a5ac7..39c20fef 100644 --- a/opendc/api/v2/specifications/storages/id/endpoint.py +++ b/opendc/api/v2/specifications/storages/id/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.storage import Storage +from opendc.models_old.storage import Storage from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/tiles/tileId/endpoint.py b/opendc/api/v2/tiles/tileId/endpoint.py index 4a1a5447..e1efda77 100644 --- a/opendc/api/v2/tiles/tileId/endpoint.py +++ b/opendc/api/v2/tiles/tileId/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.tile import Tile +from opendc.models_old.tile import Tile from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/tiles/tileId/rack/endpoint.py b/opendc/api/v2/tiles/tileId/rack/endpoint.py index 2a5803e4..b5c7fde6 100644 --- a/opendc/api/v2/tiles/tileId/rack/endpoint.py +++ b/opendc/api/v2/tiles/tileId/rack/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.rack import Rack -from opendc.models.tile import Tile +from opendc.models_old.rack import Rack +from opendc.models_old.tile import Tile from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/tiles/tileId/rack/machines/endpoint.py b/opendc/api/v2/tiles/tileId/rack/machines/endpoint.py index 34d3866e..7980d676 100644 --- a/opendc/api/v2/tiles/tileId/rack/machines/endpoint.py +++ b/opendc/api/v2/tiles/tileId/rack/machines/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.machine import Machine -from opendc.models.rack import Rack +from opendc.models_old.machine import Machine +from opendc.models_old.rack import Rack from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/tiles/tileId/rack/machines/position/endpoint.py b/opendc/api/v2/tiles/tileId/rack/machines/position/endpoint.py index 72fd44d5..dc598162 100644 --- a/opendc/api/v2/tiles/tileId/rack/machines/position/endpoint.py +++ b/opendc/api/v2/tiles/tileId/rack/machines/position/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.machine import Machine -from opendc.models.rack import Rack +from opendc.models_old.machine import Machine +from opendc.models_old.rack import Rack from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/traces/endpoint.py b/opendc/api/v2/traces/endpoint.py index 610be73e..58cc6153 100644 --- a/opendc/api/v2/traces/endpoint.py +++ b/opendc/api/v2/traces/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.trace import Trace +from opendc.models_old.trace import Trace from opendc.util.rest import Response diff --git a/opendc/api/v2/traces/traceId/endpoint.py b/opendc/api/v2/traces/traceId/endpoint.py index 720d3fd0..f6442a31 100644 --- a/opendc/api/v2/traces/traceId/endpoint.py +++ b/opendc/api/v2/traces/traceId/endpoint.py @@ -1,4 +1,4 @@ -from opendc.models.trace import Trace +from opendc.models_old.trace import Trace from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/traces/traceId/jobs/endpoint.py b/opendc/api/v2/traces/traceId/jobs/endpoint.py index eec52b56..af681b70 100644 --- a/opendc/api/v2/traces/traceId/jobs/endpoint.py +++ b/opendc/api/v2/traces/traceId/jobs/endpoint.py @@ -1,5 +1,5 @@ -from opendc.models.job import Job -from opendc.models.trace import Trace +from opendc.models_old.job import Job +from opendc.models_old.trace import Trace from opendc.util import exceptions from opendc.util.rest import Response diff --git a/opendc/api/v2/users/userId/endpoint.py b/opendc/api/v2/users/userId/endpoint.py index 6de26e64..9418f70a 100644 --- a/opendc/api/v2/users/userId/endpoint.py +++ b/opendc/api/v2/users/userId/endpoint.py @@ -1,5 +1,5 @@ +from opendc.models.user import User from opendc.util import exceptions -from opendc.util.database import DB from opendc.util.rest import Response @@ -11,12 +11,13 @@ def GET(request): except exceptions.ParameterError as e: return Response(400, str(e)) - user = DB.fetch_one({'_id': request.params_path['userId']}, 'users') + user = User(request.params_path['userId']) - if user is None: - return Response(404, f'User with ID {request.params_path["userId"]} not found.') - - return Response(200, f'Successfully retrieved {user}.', user) + validation_error = user.validate() + if validation_error is None: + return Response(200, f'Successfully retrieved {user}.', user.obj) + else: + return validation_error def PUT(request): @@ -31,22 +32,18 @@ def PUT(request): except exceptions.ParameterError as e: return Response(400, str(e)) - user_id = request.params_path['userId'] - user = DB.fetch_one({'_id': user_id}, 'users') - - if user is None: - return Response(404, f'User with ID {user_id} not found.') + user = User(request.params_path['userId']) - print(user['googleId'], request.google_id) - if user['googleId'] != request.google_id: - return Response(403, f'Forbidden from editing {user}.') + validation_error = user.validate(request.google_id) + if validation_error is not None: + return validation_error - user['givenName'] = request.params_body['user']['givenName'] - user['familyName'] = request.params_body['user']['familyName'] + user.set_property('givenName', request.params_body['user']['givenName']) + user.set_property('familyName', request.params_body['user']['familyName']) - DB.update(user_id, user, 'users') + user.update() - return Response(200, f'Successfully updated {user}.', user) + return Response(200, f'Successfully updated {user}.', user.obj) def DELETE(request): @@ -57,15 +54,12 @@ def DELETE(request): except exceptions.ParameterError as e: return Response(400, str(e)) - user_id = request.params_path['userId'] - user = DB.fetch_one({'_id': user_id}, 'users') - - if user is None: - return Response(404, f'User with ID {user_id} not found.') + user = User(request.params_path['userId']) - if user['googleId'] != request.google_id: - return Response(403, f'Forbidden from editing {user}.') + validation_error = user.validate(request.google_id) + if validation_error is not None: + return validation_error - DB.delete_one({'_id': user_id}, 'users') + user.delete() - return Response(200, f'Successfully deleted {user}.', user) + return Response(200, f'Successfully deleted {user}.', user.obj) diff --git a/opendc/models/allowed_object.py b/opendc/models/allowed_object.py deleted file mode 100644 index 48f2abd5..00000000 --- a/opendc/models/allowed_object.py +++ /dev/null @@ -1,22 +0,0 @@ -from opendc.models.model import Model - - -class AllowedObject(Model): - JSON_TO_PYTHON_DICT = {'AllowedObject': {'roomType': 'room_type', 'objectType': 'object_type'}} - - COLLECTION_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 deleted file mode 100644 index 7ec88e78..00000000 --- a/opendc/models/authorization.py +++ /dev/null @@ -1,45 +0,0 @@ -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' - } - } - - COLLECTION_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 deleted file mode 100644 index 034a86fe..00000000 --- a/opendc/models/cpu.py +++ /dev/null @@ -1,34 +0,0 @@ -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' - } - } - - COLLECTION_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 deleted file mode 100644 index d4cbf811..00000000 --- a/opendc/models/datacenter.py +++ /dev/null @@ -1,27 +0,0 @@ -from opendc.models.model import Model -from opendc.models.section import Section - - -class Datacenter(Model): - JSON_TO_PYTHON_DICT = {'datacenter': {'id': 'id', 'starred': 'starred', 'simulationId': 'simulation_id'}} - - PATH = '/v1/simulations/{simulationId}/datacenters' - - COLLECTION_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: - 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 deleted file mode 100644 index 1f33fa3b..00000000 --- a/opendc/models/experiment.py +++ /dev/null @@ -1,36 +0,0 @@ -from opendc.models.model import Model -from opendc.models.simulation import Simulation -from opendc.util import 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', - 'state': 'state', - 'lastSimulatedTick': 'last_simulated_tick' - } - } - - COLLECTION_NAME = 'experiments' - COLUMNS = ['id', 'simulation_id', 'path_id', 'trace_id', 'scheduler_name', 'name', 'state', 'last_simulated_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 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 deleted file mode 100644 index f5c4909d..00000000 --- a/opendc/models/failure_model.py +++ /dev/null @@ -1,17 +0,0 @@ -from opendc.models.model import Model - - -class FailureModel(Model): - JSON_TO_PYTHON_DICT = {'FailureModel': {'id': 'id', 'name': 'name', 'rate': 'rate'}} - - COLLECTION_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 deleted file mode 100644 index 672df6fa..00000000 --- a/opendc/models/gpu.py +++ /dev/null @@ -1,34 +0,0 @@ -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' - } - } - - COLLECTION_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/job.py b/opendc/models/job.py deleted file mode 100644 index 81354952..00000000 --- a/opendc/models/job.py +++ /dev/null @@ -1,14 +0,0 @@ -from opendc.models.model import Model - - -class Job(Model): - JSON_TO_PYTHON_DICT = {'Job': {'id': 'id', 'name': 'name'}} - - COLLECTION_NAME = 'jobs' - 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 Job.""" - - return authorization_level not in ['EDIT', 'OWN'] diff --git a/opendc/models/machine.py b/opendc/models/machine.py deleted file mode 100644 index 1b853bf9..00000000 --- a/opendc/models/machine.py +++ /dev/null @@ -1,122 +0,0 @@ -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', - 'topologyId': 'topology_id' - } - } - - PATH = '/v1/tiles/{tileId}/rack/machines' - - COLLECTION_NAME = 'machines' - COLUMNS = ['id', 'rack_id', 'position', 'topology_id'] - 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, delete current machine-device links - - statement = 'DELETE FROM machine_{} WHERE machine_id = %s'.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 (%s, %s)'.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 = %s AND position = %s' - machine_id = database.fetch_one(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 = %s'.format(device_table) - results = database.fetch_all(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 deleted file mode 100644 index 3418f66e..00000000 --- a/opendc/models/machine_state.py +++ /dev/null @@ -1,71 +0,0 @@ -from opendc.models.model import Model -from opendc.util import database - - -class MachineState(Model): - JSON_TO_PYTHON_DICT = { - 'MachineState': { - 'machineId': 'machine_id', - 'temperatureC': 'temperature_c', - 'inUseMemoryMb': 'in_use_memory_mb', - 'loadFraction': 'load_fraction', - 'tick': 'tick' - } - } - - COLLECTION_NAME = 'machine_states' - COLUMNS = ['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(machine_id=row[1], temperature_c=row[4], in_use_memory_mb=row[5], load_fraction=row[6], tick=row[3]) - - @classmethod - def from_experiment_id(cls, experiment_id): - """Query MachineStates by their Experiment id.""" - - machine_states = [] - - statement = 'SELECT * FROM machine_states WHERE experiment_id = %s' - results = database.fetch_all(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 = %s AND machine_states.tick = %s' - results = database.fetch_all(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 = %s' - result = database.fetch_one(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 deleted file mode 100644 index 17a79e14..00000000 --- a/opendc/models/memory.py +++ /dev/null @@ -1,34 +0,0 @@ -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' - } - } - - COLLECTION_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 deleted file mode 100644 index 73eabd26..00000000 --- a/opendc/models/model.py +++ /dev/null @@ -1,303 +0,0 @@ -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 = {} - - COLLECTION_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.COLLECTION_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(['%s'] * len(cls.COLUMNS)) - - @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 - def _generate_update_columns_string(cls): - """Generate a SQLite updatable columns string for this Model.""" - - return ', '.join(['{} = %s'.format(x) for x in cls.COLUMNS if x not 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 x not 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.fetch_one(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.COLLECTION_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 {} = %s'.format(cls.COLLECTION_NAME, column_name) - database_models = database.fetch_all(statement, (value, )) - - else: - statement = 'SELECT * FROM {}'.format(cls.COLLECTION_NAME) - database_models = database.fetch_all(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.COLLECTION_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.COLLECTION_NAME, self._generate_primary_key_string()) - values = self._generate_primary_key_tuple() - - else: - query = query.format(self.COLLECTION_NAME, '{} = %s'.format(column)) - values = (getattr(self, column), ) - - return database.fetch_one(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, is_auto_generated=True): - """Insert this Model into the database without removing its id.""" - - statement = 'INSERT INTO {} ({}) VALUES ({})'.format(self.COLLECTION_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: - print(e) - raise exceptions.ForeignKeyError(e) - - if 'id' in self.COLUMNS_PRIMARY_KEY: - if is_auto_generated: - 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.COLLECTION_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.COLLECTION_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) diff --git a/opendc/models/object.py b/opendc/models/object.py deleted file mode 100644 index 2ce079af..00000000 --- a/opendc/models/object.py +++ /dev/null @@ -1,14 +0,0 @@ -from opendc.models.model import Model - - -class Object(Model): - JSON_TO_PYTHON_DICT = {'Object': {'id': 'id', 'type': 'type'}} - - COLLECTION_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 deleted file mode 100644 index 093c9346..00000000 --- a/opendc/models/path.py +++ /dev/null @@ -1,35 +0,0 @@ -from opendc.models.authorization import Authorization -from opendc.models.model import Model -from opendc.models.user import User -from opendc.util import exceptions - - -class Path(Model): - JSON_TO_PYTHON_DICT = { - 'Path': { - 'id': 'id', - 'simulationId': 'simulation_id', - 'name': 'name', - 'datetimeCreated': 'datetime_created' - } - } - - COLLECTION_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 deleted file mode 100644 index b59cfedc..00000000 --- a/opendc/models/queued_experiment.py +++ /dev/null @@ -1,9 +0,0 @@ -from opendc.models.model import Model - - -class QueuedExperiment(Model): - JSON_TO_PYTHON_DICT = {'QueuedExperiment': {'experimentId': 'experiment_id'}} - - COLLECTION_NAME = 'queued_experiments' - COLUMNS = ['experiment_id'] - COLUMNS_PRIMARY_KEY = ['experiment_id'] diff --git a/opendc/models/rack.py b/opendc/models/rack.py deleted file mode 100644 index 52cb0ffe..00000000 --- a/opendc/models/rack.py +++ /dev/null @@ -1,61 +0,0 @@ -from opendc.models.model import Model -from opendc.models.object import Object -from opendc.models.tile import Tile - - -class Rack(Model): - JSON_TO_PYTHON_DICT = { - 'rack': { - 'id': 'id', - 'name': 'name', - 'capacity': 'capacity', - 'powerCapacityW': 'power_capacity_w', - 'topologyId': 'topology_id' - } - } - - PATH = '/v1/tiles/{tileId}/rack' - - COLLECTION_NAME = 'racks' - COLUMNS = ['id', 'name', 'capacity', 'power_capacity_w', 'topology_id'] - 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(is_auto_generated=False) - - 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 deleted file mode 100644 index a261fce0..00000000 --- a/opendc/models/rack_state.py +++ /dev/null @@ -1,63 +0,0 @@ -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 = %s - GROUP BY machine_states.tick, racks.id - ''' - results = database.fetch_all(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 = %s - AND machine_states.tick = %s - GROUP BY machine_states.tick, racks.id - ''' - results = database.fetch_all(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 deleted file mode 100644 index 6a7627f5..00000000 --- a/opendc/models/room.py +++ /dev/null @@ -1,35 +0,0 @@ -from opendc.models.datacenter import Datacenter -from opendc.models.model import Model -from opendc.util import exceptions - - -class Room(Model): - JSON_TO_PYTHON_DICT = { - 'room': { - 'id': 'id', - 'datacenterId': 'datacenter_id', - 'name': 'name', - 'roomType': 'type', - 'topologyId': 'topology_id' - } - } - - PATH = '/v1/datacenters/{datacenterId}/rooms' - - COLLECTION_NAME = 'rooms' - COLUMNS = ['id', 'name', 'datacenter_id', 'type', 'topology_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 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 deleted file mode 100644 index 4326a32b..00000000 --- a/opendc/models/room_state.py +++ /dev/null @@ -1,71 +0,0 @@ -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 = %s - GROUP BY machine_states.tick, rooms.id - ''' - results = database.fetch_all(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 = %s - AND machine_states.tick = %s - GROUP BY rooms.id - ''' - results = database.fetch_all(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 deleted file mode 100644 index b91c1e67..00000000 --- a/opendc/models/room_type.py +++ /dev/null @@ -1,17 +0,0 @@ -from opendc.models.model import Model - - -class RoomType(Model): - JSON_TO_PYTHON_DICT = {'RoomType': {'name': 'name'}} - - COLLECTION_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 deleted file mode 100644 index c3c98b7a..00000000 --- a/opendc/models/scheduler.py +++ /dev/null @@ -1,14 +0,0 @@ -from opendc.models.model import Model - - -class Scheduler(Model): - JSON_TO_PYTHON_DICT = {'Scheduler': {'name': 'name'}} - - COLLECTION_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 deleted file mode 100644 index 2fd71068..00000000 --- a/opendc/models/section.py +++ /dev/null @@ -1,32 +0,0 @@ -from opendc.models.model import Model -from opendc.models.path import Path -from opendc.util import exceptions - - -class Section(Model): - JSON_TO_PYTHON_DICT = { - 'Section': { - 'id': 'id', - 'pathId': 'path_id', - 'datacenterId': 'datacenter_id', - 'startTick': 'start_tick' - } - } - - COLLECTION_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 deleted file mode 100644 index af47b4c5..00000000 --- a/opendc/models/simulation.py +++ /dev/null @@ -1,39 +0,0 @@ -from opendc.models.authorization import Authorization -from opendc.models.model import Model -from opendc.models.user import User -from opendc.util import exceptions - - -class Simulation(Model): - JSON_TO_PYTHON_DICT = { - 'Simulation': { - 'id': 'id', - 'name': 'name', - 'datetimeCreated': 'datetime_created', - 'datetimeLastEdited': 'datetime_last_edited' - } - } - - COLLECTION_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 deleted file mode 100644 index 93cc8b68..00000000 --- a/opendc/models/storage.py +++ /dev/null @@ -1,34 +0,0 @@ -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' - } - } - - COLLECTION_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 deleted file mode 100644 index 411405c2..00000000 --- a/opendc/models/task.py +++ /dev/null @@ -1,22 +0,0 @@ -from opendc.models.model import Model - - -class Task(Model): - JSON_TO_PYTHON_DICT = { - 'Task': { - 'id': 'id', - 'startTick': 'start_tick', - 'totalFlopCount': 'total_flop_count', - 'coreCount': 'core_count', - 'jobId': 'job_id', - } - } - - COLLECTION_NAME = 'tasks' - COLUMNS = ['id', 'start_tick', 'total_flop_count', 'job_id', 'core_count'] - 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 deleted file mode 100644 index ad6459ab..00000000 --- a/opendc/models/task_duration.py +++ /dev/null @@ -1,39 +0,0 @@ -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 = %s - GROUP BY task_id - ''' - - results = database.fetch_all(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 deleted file mode 100644 index 2cef20ee..00000000 --- a/opendc/models/task_state.py +++ /dev/null @@ -1,42 +0,0 @@ -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', - 'coresUsed': 'cores_used' - } - } - - COLLECTION_NAME = 'task_states' - - COLUMNS = ['id', 'task_id', 'experiment_id', 'tick', 'flops_left', 'cores_used'] - 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 = %s AND tick = %s' - results = database.fetch_all(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 User has 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 deleted file mode 100644 index a945564f..00000000 --- a/opendc/models/tile.py +++ /dev/null @@ -1,47 +0,0 @@ -from opendc.models.model import Model -from opendc.models.object import Object -from opendc.models.room import Room -from opendc.util import 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', - 'topologyId': 'topology_id' - } - } - - PATH = '/v1/rooms/{roomId}/tiles' - - COLLECTION_NAME = 'tiles' - COLUMNS = ['id', 'position_x', 'position_y', 'room_id', 'object_id', 'topology_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 deleted file mode 100644 index f6d2e1c1..00000000 --- a/opendc/models/trace.py +++ /dev/null @@ -1,14 +0,0 @@ -from opendc.models.model import Model - - -class Trace(Model): - JSON_TO_PYTHON_DICT = {'Trace': {'id': 'id', 'name': 'name'}} - - COLLECTION_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 index df3a4e76..39437025 100644 --- a/opendc/models/user.py +++ b/opendc/models/user.py @@ -1,47 +1,26 @@ -from opendc.models.model import Model +from opendc.util.database import DB +from opendc.util.rest import Response -class User(Model): - JSON_TO_PYTHON_DICT = { - 'User': { - 'id': 'id', - 'googleId': 'google_id', - 'email': 'email', - 'givenName': 'given_name', - 'familyName': 'family_name' - } - } +class User: + def __init__(self, obj_id): + self.obj_id = obj_id + self.obj = DB.fetch_one({'_id': obj_id}, 'users') - COLLECTION_NAME = 'users' - COLUMNS = ['id', 'google_id', 'email', 'given_name', 'family_name'] - COLUMNS_PRIMARY_KEY = ['id'] + def validate(self, request_google_id=None): + if self.obj is None: + return Response(404, f'User with ID {self.obj_id} not found.') - @classmethod - def from_google_id(cls, google_id): - """Initialize a User by fetching them by their google id.""" + if request_google_id is not None and self.obj['googleId'] != request_google_id: + return Response(403, f'Forbidden from editing user with ID {self.obj_id}.') - user = cls._from_database('SELECT * FROM users WHERE google_id = %s', (google_id, )) + return None - if user is not None: - return user + def set_property(self, key, value): + self.obj[key] = value - return User() + def update(self): + DB.update(self.obj_id, self.obj, 'users') - @classmethod - def from_email(cls, email): - """Initialize a User by fetching them by their email.""" - - user = cls._from_database('SELECT * FROM users WHERE email = %s', (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 + def delete(self): + DB.delete_one({'_id': self.obj_id}, 'users') diff --git a/opendc/models_old/__init__.py b/opendc/models_old/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/opendc/models_old/allowed_object.py b/opendc/models_old/allowed_object.py new file mode 100644 index 00000000..bcadf025 --- /dev/null +++ b/opendc/models_old/allowed_object.py @@ -0,0 +1,22 @@ +from opendc.models_old.model import Model + + +class AllowedObject(Model): + JSON_TO_PYTHON_DICT = {'AllowedObject': {'roomType': 'room_type', 'objectType': 'object_type'}} + + COLLECTION_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_old/authorization.py b/opendc/models_old/authorization.py new file mode 100644 index 00000000..43d784e9 --- /dev/null +++ b/opendc/models_old/authorization.py @@ -0,0 +1,45 @@ +from opendc.models_old.model import Model +from opendc.models_old.user import User + + +class Authorization(Model): + JSON_TO_PYTHON_DICT = { + 'Authorization': { + 'userId': 'user_id', + 'simulationId': 'simulation_id', + 'authorizationLevel': 'authorization_level' + } + } + + COLLECTION_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_old/cpu.py b/opendc/models_old/cpu.py new file mode 100644 index 00000000..0f50ce1c --- /dev/null +++ b/opendc/models_old/cpu.py @@ -0,0 +1,34 @@ +from opendc.models_old.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' + } + } + + COLLECTION_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_old/datacenter.py b/opendc/models_old/datacenter.py new file mode 100644 index 00000000..b1ed2eee --- /dev/null +++ b/opendc/models_old/datacenter.py @@ -0,0 +1,27 @@ +from opendc.models_old.model import Model +from opendc.models_old.section import Section + + +class Datacenter(Model): + JSON_TO_PYTHON_DICT = {'datacenter': {'id': 'id', 'starred': 'starred', 'simulationId': 'simulation_id'}} + + PATH = '/v1/simulations/{simulationId}/datacenters' + + COLLECTION_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: + return False + + # Check the Section's Authorization + + return section.google_id_has_at_least(google_id, authorization_level) diff --git a/opendc/models_old/experiment.py b/opendc/models_old/experiment.py new file mode 100644 index 00000000..64b99212 --- /dev/null +++ b/opendc/models_old/experiment.py @@ -0,0 +1,36 @@ +from opendc.models_old.model import Model +from opendc.models_old.simulation import Simulation +from opendc.util import 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', + 'state': 'state', + 'lastSimulatedTick': 'last_simulated_tick' + } + } + + COLLECTION_NAME = 'experiments' + COLUMNS = ['id', 'simulation_id', 'path_id', 'trace_id', 'scheduler_name', 'name', 'state', 'last_simulated_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 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_old/failure_model.py b/opendc/models_old/failure_model.py new file mode 100644 index 00000000..d1a8c1cc --- /dev/null +++ b/opendc/models_old/failure_model.py @@ -0,0 +1,17 @@ +from opendc.models_old.model import Model + + +class FailureModel(Model): + JSON_TO_PYTHON_DICT = {'FailureModel': {'id': 'id', 'name': 'name', 'rate': 'rate'}} + + COLLECTION_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_old/gpu.py b/opendc/models_old/gpu.py new file mode 100644 index 00000000..31b3b6b1 --- /dev/null +++ b/opendc/models_old/gpu.py @@ -0,0 +1,34 @@ +from opendc.models_old.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' + } + } + + COLLECTION_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_old/job.py b/opendc/models_old/job.py new file mode 100644 index 00000000..9cb7cd7e --- /dev/null +++ b/opendc/models_old/job.py @@ -0,0 +1,14 @@ +from opendc.models_old.model import Model + + +class Job(Model): + JSON_TO_PYTHON_DICT = {'Job': {'id': 'id', 'name': 'name'}} + + COLLECTION_NAME = 'jobs' + 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 Job.""" + + return authorization_level not in ['EDIT', 'OWN'] diff --git a/opendc/models_old/machine.py b/opendc/models_old/machine.py new file mode 100644 index 00000000..8e5ccb44 --- /dev/null +++ b/opendc/models_old/machine.py @@ -0,0 +1,122 @@ +import copy + +from opendc.models_old.model import Model +from opendc.models_old.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', + 'topologyId': 'topology_id' + } + } + + PATH = '/v1/tiles/{tileId}/rack/machines' + + COLLECTION_NAME = 'machines' + COLUMNS = ['id', 'rack_id', 'position', 'topology_id'] + 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, delete current machine-device links + + statement = 'DELETE FROM machine_{} WHERE machine_id = %s'.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 (%s, %s)'.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 = %s AND position = %s' + machine_id = database.fetch_one(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 = %s'.format(device_table) + results = database.fetch_all(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_old/machine_state.py b/opendc/models_old/machine_state.py new file mode 100644 index 00000000..0e9f7dad --- /dev/null +++ b/opendc/models_old/machine_state.py @@ -0,0 +1,71 @@ +from opendc.models_old.model import Model +from opendc.util import database + + +class MachineState(Model): + JSON_TO_PYTHON_DICT = { + 'MachineState': { + 'machineId': 'machine_id', + 'temperatureC': 'temperature_c', + 'inUseMemoryMb': 'in_use_memory_mb', + 'loadFraction': 'load_fraction', + 'tick': 'tick' + } + } + + COLLECTION_NAME = 'machine_states' + COLUMNS = ['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(machine_id=row[1], temperature_c=row[4], in_use_memory_mb=row[5], load_fraction=row[6], tick=row[3]) + + @classmethod + def from_experiment_id(cls, experiment_id): + """Query MachineStates by their Experiment id.""" + + machine_states = [] + + statement = 'SELECT * FROM machine_states WHERE experiment_id = %s' + results = database.fetch_all(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 = %s AND machine_states.tick = %s' + results = database.fetch_all(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 = %s' + result = database.fetch_one(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_old/memory.py b/opendc/models_old/memory.py new file mode 100644 index 00000000..8edf8f5d --- /dev/null +++ b/opendc/models_old/memory.py @@ -0,0 +1,34 @@ +from opendc.models_old.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' + } + } + + COLLECTION_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_old/model.py b/opendc/models_old/model.py new file mode 100644 index 00000000..73eabd26 --- /dev/null +++ b/opendc/models_old/model.py @@ -0,0 +1,303 @@ +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 = {} + + COLLECTION_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.COLLECTION_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(['%s'] * len(cls.COLUMNS)) + + @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 + def _generate_update_columns_string(cls): + """Generate a SQLite updatable columns string for this Model.""" + + return ', '.join(['{} = %s'.format(x) for x in cls.COLUMNS if x not 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 x not 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.fetch_one(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.COLLECTION_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 {} = %s'.format(cls.COLLECTION_NAME, column_name) + database_models = database.fetch_all(statement, (value, )) + + else: + statement = 'SELECT * FROM {}'.format(cls.COLLECTION_NAME) + database_models = database.fetch_all(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.COLLECTION_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.COLLECTION_NAME, self._generate_primary_key_string()) + values = self._generate_primary_key_tuple() + + else: + query = query.format(self.COLLECTION_NAME, '{} = %s'.format(column)) + values = (getattr(self, column), ) + + return database.fetch_one(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, is_auto_generated=True): + """Insert this Model into the database without removing its id.""" + + statement = 'INSERT INTO {} ({}) VALUES ({})'.format(self.COLLECTION_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: + print(e) + raise exceptions.ForeignKeyError(e) + + if 'id' in self.COLUMNS_PRIMARY_KEY: + if is_auto_generated: + 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.COLLECTION_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.COLLECTION_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) diff --git a/opendc/models_old/object.py b/opendc/models_old/object.py new file mode 100644 index 00000000..8f2e308b --- /dev/null +++ b/opendc/models_old/object.py @@ -0,0 +1,14 @@ +from opendc.models_old.model import Model + + +class Object(Model): + JSON_TO_PYTHON_DICT = {'Object': {'id': 'id', 'type': 'type'}} + + COLLECTION_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_old/path.py b/opendc/models_old/path.py new file mode 100644 index 00000000..4d07b2d5 --- /dev/null +++ b/opendc/models_old/path.py @@ -0,0 +1,35 @@ +from opendc.models_old.authorization import Authorization +from opendc.models_old.model import Model +from opendc.models_old.user import User +from opendc.util import exceptions + + +class Path(Model): + JSON_TO_PYTHON_DICT = { + 'Path': { + 'id': 'id', + 'simulationId': 'simulation_id', + 'name': 'name', + 'datetimeCreated': 'datetime_created' + } + } + + COLLECTION_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_old/queued_experiment.py b/opendc/models_old/queued_experiment.py new file mode 100644 index 00000000..b474dc31 --- /dev/null +++ b/opendc/models_old/queued_experiment.py @@ -0,0 +1,9 @@ +from opendc.models_old.model import Model + + +class QueuedExperiment(Model): + JSON_TO_PYTHON_DICT = {'QueuedExperiment': {'experimentId': 'experiment_id'}} + + COLLECTION_NAME = 'queued_experiments' + COLUMNS = ['experiment_id'] + COLUMNS_PRIMARY_KEY = ['experiment_id'] diff --git a/opendc/models_old/rack.py b/opendc/models_old/rack.py new file mode 100644 index 00000000..dc08eb6a --- /dev/null +++ b/opendc/models_old/rack.py @@ -0,0 +1,61 @@ +from opendc.models_old.model import Model +from opendc.models_old.object import Object +from opendc.models_old.tile import Tile + + +class Rack(Model): + JSON_TO_PYTHON_DICT = { + 'rack': { + 'id': 'id', + 'name': 'name', + 'capacity': 'capacity', + 'powerCapacityW': 'power_capacity_w', + 'topologyId': 'topology_id' + } + } + + PATH = '/v1/tiles/{tileId}/rack' + + COLLECTION_NAME = 'racks' + COLUMNS = ['id', 'name', 'capacity', 'power_capacity_w', 'topology_id'] + 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(is_auto_generated=False) + + 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_old/rack_state.py b/opendc/models_old/rack_state.py new file mode 100644 index 00000000..12e0f931 --- /dev/null +++ b/opendc/models_old/rack_state.py @@ -0,0 +1,63 @@ +from opendc.models_old.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 = %s + GROUP BY machine_states.tick, racks.id + ''' + results = database.fetch_all(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 = %s + AND machine_states.tick = %s + GROUP BY machine_states.tick, racks.id + ''' + results = database.fetch_all(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_old/room.py b/opendc/models_old/room.py new file mode 100644 index 00000000..e0eb7c2f --- /dev/null +++ b/opendc/models_old/room.py @@ -0,0 +1,35 @@ +from opendc.models_old.datacenter import Datacenter +from opendc.models_old.model import Model +from opendc.util import exceptions + + +class Room(Model): + JSON_TO_PYTHON_DICT = { + 'room': { + 'id': 'id', + 'datacenterId': 'datacenter_id', + 'name': 'name', + 'roomType': 'type', + 'topologyId': 'topology_id' + } + } + + PATH = '/v1/datacenters/{datacenterId}/rooms' + + COLLECTION_NAME = 'rooms' + COLUMNS = ['id', 'name', 'datacenter_id', 'type', 'topology_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 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_old/room_state.py b/opendc/models_old/room_state.py new file mode 100644 index 00000000..c6635649 --- /dev/null +++ b/opendc/models_old/room_state.py @@ -0,0 +1,71 @@ +from opendc.models_old.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 = %s + GROUP BY machine_states.tick, rooms.id + ''' + results = database.fetch_all(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 = %s + AND machine_states.tick = %s + GROUP BY rooms.id + ''' + results = database.fetch_all(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_old/room_type.py b/opendc/models_old/room_type.py new file mode 100644 index 00000000..755572f8 --- /dev/null +++ b/opendc/models_old/room_type.py @@ -0,0 +1,17 @@ +from opendc.models_old.model import Model + + +class RoomType(Model): + JSON_TO_PYTHON_DICT = {'RoomType': {'name': 'name'}} + + COLLECTION_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_old/scheduler.py b/opendc/models_old/scheduler.py new file mode 100644 index 00000000..b9939321 --- /dev/null +++ b/opendc/models_old/scheduler.py @@ -0,0 +1,14 @@ +from opendc.models_old.model import Model + + +class Scheduler(Model): + JSON_TO_PYTHON_DICT = {'Scheduler': {'name': 'name'}} + + COLLECTION_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_old/section.py b/opendc/models_old/section.py new file mode 100644 index 00000000..0df4967c --- /dev/null +++ b/opendc/models_old/section.py @@ -0,0 +1,32 @@ +from opendc.models_old.model import Model +from opendc.models_old.path import Path +from opendc.util import exceptions + + +class Section(Model): + JSON_TO_PYTHON_DICT = { + 'Section': { + 'id': 'id', + 'pathId': 'path_id', + 'datacenterId': 'datacenter_id', + 'startTick': 'start_tick' + } + } + + COLLECTION_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_old/simulation.py b/opendc/models_old/simulation.py new file mode 100644 index 00000000..9c1820a3 --- /dev/null +++ b/opendc/models_old/simulation.py @@ -0,0 +1,39 @@ +from opendc.models_old.authorization import Authorization +from opendc.models_old.model import Model +from opendc.models_old.user import User +from opendc.util import exceptions + + +class Simulation(Model): + JSON_TO_PYTHON_DICT = { + 'Simulation': { + 'id': 'id', + 'name': 'name', + 'datetimeCreated': 'datetime_created', + 'datetimeLastEdited': 'datetime_last_edited' + } + } + + COLLECTION_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_old/storage.py b/opendc/models_old/storage.py new file mode 100644 index 00000000..9f0f9215 --- /dev/null +++ b/opendc/models_old/storage.py @@ -0,0 +1,34 @@ +from opendc.models_old.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' + } + } + + COLLECTION_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_old/task.py b/opendc/models_old/task.py new file mode 100644 index 00000000..e6f99014 --- /dev/null +++ b/opendc/models_old/task.py @@ -0,0 +1,22 @@ +from opendc.models_old.model import Model + + +class Task(Model): + JSON_TO_PYTHON_DICT = { + 'Task': { + 'id': 'id', + 'startTick': 'start_tick', + 'totalFlopCount': 'total_flop_count', + 'coreCount': 'core_count', + 'jobId': 'job_id', + } + } + + COLLECTION_NAME = 'tasks' + COLUMNS = ['id', 'start_tick', 'total_flop_count', 'job_id', 'core_count'] + 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_old/task_duration.py b/opendc/models_old/task_duration.py new file mode 100644 index 00000000..5058e8de --- /dev/null +++ b/opendc/models_old/task_duration.py @@ -0,0 +1,39 @@ +from opendc.models_old.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 = %s + GROUP BY task_id + ''' + + results = database.fetch_all(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_old/task_state.py b/opendc/models_old/task_state.py new file mode 100644 index 00000000..cc3fdd89 --- /dev/null +++ b/opendc/models_old/task_state.py @@ -0,0 +1,42 @@ +from opendc.models_old.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', + 'coresUsed': 'cores_used' + } + } + + COLLECTION_NAME = 'task_states' + + COLUMNS = ['id', 'task_id', 'experiment_id', 'tick', 'flops_left', 'cores_used'] + 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 = %s AND tick = %s' + results = database.fetch_all(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 User has at least the given auth level over this TaskState.""" + + if authorization_level in ['EDIT', 'OWN']: + return False + + return True diff --git a/opendc/models_old/tile.py b/opendc/models_old/tile.py new file mode 100644 index 00000000..e46b29a6 --- /dev/null +++ b/opendc/models_old/tile.py @@ -0,0 +1,47 @@ +from opendc.models_old.model import Model +from opendc.models_old.object import Object +from opendc.models_old.room import Room +from opendc.util import 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', + 'topologyId': 'topology_id' + } + } + + PATH = '/v1/rooms/{roomId}/tiles' + + COLLECTION_NAME = 'tiles' + COLUMNS = ['id', 'position_x', 'position_y', 'room_id', 'object_id', 'topology_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_old/trace.py b/opendc/models_old/trace.py new file mode 100644 index 00000000..58abe058 --- /dev/null +++ b/opendc/models_old/trace.py @@ -0,0 +1,14 @@ +from opendc.models_old.model import Model + + +class Trace(Model): + JSON_TO_PYTHON_DICT = {'Trace': {'id': 'id', 'name': 'name'}} + + COLLECTION_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_old/user.py b/opendc/models_old/user.py new file mode 100644 index 00000000..657d5019 --- /dev/null +++ b/opendc/models_old/user.py @@ -0,0 +1,47 @@ +from opendc.models_old.model import Model + + +class User(Model): + JSON_TO_PYTHON_DICT = { + 'User': { + 'id': 'id', + 'googleId': 'google_id', + 'email': 'email', + 'givenName': 'given_name', + 'familyName': 'family_name' + } + } + + COLLECTION_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 = %s', (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 = %s', (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 -- cgit v1.2.3