summaryrefslogtreecommitdiff
path: root/opendc/api/v2/simulations/simulationId/datacenters/endpoint.py
blob: e28402e41704b5ad616de173fb466878bbe83fdd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from opendc.models.datacenter import Datacenter
from opendc.models.simulation import Simulation
from opendc.util import exceptions
from opendc.util.rest import Response


def POST(request):
    """Add a new Datacenter to this Simulation."""

    # Make sure required parameters are there

    try:
        request.check_required_parameters(
            path={
                'simulationId': 'int'
            },
            body={
                'datacenter': {
                    'starred': 'int',
                    'simulationId': 'int'
                }
            }
        )

    except exceptions.ParameterError as e:
        return Response(400, e.message)

    # Make sure the passed object's simulation id matches the path simulation id

    if request.params_path['simulationId'] != request.params_body['datacenter']['simulationId']:
        return Response(400, 'ID mismatch.')

    # Instantiate a Simulation from the database

    simulation = Simulation.from_primary_key((request.params_path['simulationId'],))

    # Make sure this Simulation exists

    if not simulation.exists():
        return Response(404, '{} not found.'.format(simulation))

    # Make sure this user is authorized to edit this Simulation's Databases

    if not simulation.google_id_has_at_least(request.google_id, 'EDIT'):
        return Response(403, 'Forbidden from adding a datacenter to {}.'.format(simulation))

    # Instantiate a Datacenter

    datacenter = Datacenter.from_JSON(request.params_body['datacenter'])

    datacenter.insert()

    # return this Datacenter

    datacenter.read()

    return Response(
        200,
        'Successfully added {}.'.format(datacenter),
        datacenter.to_JSON()
    )