RacksDB 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. RacksDB-0.2.0.dist-info/LICENSE +674 -0
  2. RacksDB-0.2.0.dist-info/METADATA +126 -0
  3. RacksDB-0.2.0.dist-info/RECORD +42 -0
  4. RacksDB-0.2.0.dist-info/WHEEL +5 -0
  5. RacksDB-0.2.0.dist-info/entry_points.txt +3 -0
  6. RacksDB-0.2.0.dist-info/top_level.txt +1 -0
  7. racksdb/__init__.py +74 -0
  8. racksdb/bases.py +117 -0
  9. racksdb/drawers/__init__.py +10 -0
  10. racksdb/drawers/base.py +42 -0
  11. racksdb/drawers/infrastructure.py +253 -0
  12. racksdb/drawers/room.py +160 -0
  13. racksdb/dtypes/__init__.py +0 -0
  14. racksdb/dtypes/angle.py +21 -0
  15. racksdb/dtypes/bytes.py +31 -0
  16. racksdb/dtypes/dimension.py +23 -0
  17. racksdb/dtypes/netif_type.py +17 -0
  18. racksdb/dtypes/rack_height.py +17 -0
  19. racksdb/dtypes/rack_width.py +26 -0
  20. racksdb/dtypes/storage_type.py +17 -0
  21. racksdb/errors.py +9 -0
  22. racksdb/exec.py +218 -0
  23. racksdb/generic/__init__.py +0 -0
  24. racksdb/generic/db.py +609 -0
  25. racksdb/generic/definedtype.py +24 -0
  26. racksdb/generic/dumpers/__init__.py +30 -0
  27. racksdb/generic/dumpers/_common.py +30 -0
  28. racksdb/generic/dumpers/console.py +31 -0
  29. racksdb/generic/dumpers/json.py +108 -0
  30. racksdb/generic/dumpers/yaml.py +138 -0
  31. racksdb/generic/errors.py +21 -0
  32. racksdb/generic/openapi.py +199 -0
  33. racksdb/generic/schema.py +367 -0
  34. racksdb/generic/views.py +139 -0
  35. racksdb/tests/__init__.py +0 -0
  36. racksdb/tests/test_schema.py +211 -0
  37. racksdb/tests/test_schema_defined_type_loader.py +23 -0
  38. racksdb/tests/tests_db_load.py +83 -0
  39. racksdb/version.py +11 -0
  40. racksdb/views.py +136 -0
  41. racksdb/web/__init__.py +0 -0
  42. racksdb/web/app.py +195 -0
@@ -0,0 +1,211 @@
1
+ # Copyright (c) 2022-2023 Rackslab
2
+ #
3
+ # This file is part of RacksDB.
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ import unittest
8
+ import copy
9
+
10
+ from racksdb.generic.schema import Schema
11
+ from racksdb.generic.definedtype import SchemaDefinedType
12
+ from racksdb.generic.errors import DBSchemaError
13
+
14
+
15
+ class FakeSchemaLoader:
16
+ def __init__(self, content):
17
+ self.content = content
18
+
19
+
20
+ class FakeTypesLoader:
21
+ def __init__(self, content):
22
+ self.content = content
23
+
24
+
25
+ VALID_SCHEMA = {
26
+ "_version": "1",
27
+ "_content": {
28
+ "properties": {
29
+ "apples": {"type": "list[:Apple]"},
30
+ "pear": {"type": ":Pear"},
31
+ "bananas": {"type": "list[:Banana]", "optional": True},
32
+ "stock": {
33
+ "type": "list[:AppleCrate]",
34
+ },
35
+ }
36
+ },
37
+ "_objects": {
38
+ "Apple": {
39
+ "properties": {
40
+ "color": {
41
+ "type": "str",
42
+ },
43
+ "weight": {"type": "~weight"},
44
+ "variety": {
45
+ "type": "str",
46
+ },
47
+ }
48
+ },
49
+ "Pear": {
50
+ "properties": {
51
+ "color": {
52
+ "type": "str",
53
+ },
54
+ "weight": {
55
+ "type": "~weight",
56
+ },
57
+ "variety": {
58
+ "type": "str",
59
+ },
60
+ }
61
+ },
62
+ "Banana": {
63
+ "properties": {
64
+ "origin": {
65
+ "type": "str",
66
+ }
67
+ }
68
+ },
69
+ "AppleCrate": {
70
+ "properties": {
71
+ "name": {
72
+ "type": "expandable",
73
+ },
74
+ "id": {
75
+ "type": "rangeid",
76
+ },
77
+ "variety": {
78
+ "type": "$Apple.variety",
79
+ },
80
+ "quantity": {
81
+ "type": "int",
82
+ },
83
+ }
84
+ },
85
+ },
86
+ }
87
+
88
+ VALID_DEFINED_TYPES = {"weight": SchemaDefinedType()}
89
+
90
+
91
+ class TestSchema(unittest.TestCase):
92
+ def test_empty_schema(self):
93
+ schema_loader = FakeSchemaLoader({})
94
+ types_loader = FakeTypesLoader({})
95
+ with self.assertRaisesRegex(DBSchemaError, "Version must be defined in schema"):
96
+ Schema(schema_loader, types_loader)
97
+
98
+ def test_empty_content(self):
99
+ schema_loader = FakeSchemaLoader({"_version": "0"})
100
+ types_loader = FakeTypesLoader({})
101
+ with self.assertRaisesRegex(DBSchemaError, "Content must be defined in schema"):
102
+ Schema(schema_loader, types_loader)
103
+
104
+ def test_minimal_schema(self):
105
+ schema_loader = FakeSchemaLoader(
106
+ {"_version": "0", "_content": {"properties": {}}}
107
+ )
108
+ types_loader = FakeTypesLoader({})
109
+ schema = Schema(schema_loader, types_loader)
110
+ self.assertEqual(schema.version, "0")
111
+ self.assertEqual(len(schema.types), 0)
112
+ self.assertEqual(len(schema.content.properties), 0)
113
+
114
+ def test_valid_schema(self):
115
+ schema_loader = FakeSchemaLoader(VALID_SCHEMA)
116
+ types_loader = FakeTypesLoader(VALID_DEFINED_TYPES)
117
+ schema = Schema(schema_loader, types_loader)
118
+ self.assertEqual(schema.version, "1")
119
+ self.assertEqual(len(schema.types), 1)
120
+ self.assertEqual(len(schema.content.properties), 4)
121
+
122
+ def test_missing_objects(self):
123
+ schema_content = copy.deepcopy(VALID_SCHEMA)
124
+ del schema_content["_objects"]
125
+ schema_loader = FakeSchemaLoader(schema_content)
126
+ types_loader = FakeTypesLoader(VALID_DEFINED_TYPES)
127
+ with self.assertRaisesRegex(
128
+ DBSchemaError, "Definition of object \w+ not found in schema"
129
+ ):
130
+ Schema(schema_loader, types_loader)
131
+
132
+ def test_missing_object(self):
133
+ for obj in VALID_SCHEMA["_objects"].keys():
134
+ schema_content = copy.deepcopy(VALID_SCHEMA)
135
+ del schema_content["_objects"][obj]
136
+ schema_loader = FakeSchemaLoader(schema_content)
137
+ types_loader = FakeTypesLoader(VALID_DEFINED_TYPES)
138
+ with self.assertRaisesRegex(
139
+ DBSchemaError, f"Definition of object {obj} not found in schema"
140
+ ):
141
+ Schema(schema_loader, types_loader)
142
+
143
+ def test_missing_defined_type(self):
144
+ schema_loader = FakeSchemaLoader(VALID_SCHEMA)
145
+ defined_types = copy.deepcopy(VALID_DEFINED_TYPES)
146
+ del defined_types["weight"]
147
+ types_loader = FakeTypesLoader(defined_types)
148
+ with self.assertRaisesRegex(
149
+ DBSchemaError, "Definition of defined type weight not found"
150
+ ):
151
+ Schema(schema_loader, types_loader)
152
+
153
+ def test_invalid_type(self):
154
+ schema_content = copy.deepcopy(VALID_SCHEMA)
155
+ schema_content["_objects"]["Apple"]["properties"]["color"]["type"] = "fail"
156
+ schema_loader = FakeSchemaLoader(schema_content)
157
+ types_loader = FakeTypesLoader(VALID_DEFINED_TYPES)
158
+ with self.assertRaisesRegex(DBSchemaError, "Unable to parse value type 'fail'"):
159
+ Schema(schema_loader, types_loader)
160
+
161
+ def test_expandable_not_in_list(self):
162
+ schema_content = copy.deepcopy(VALID_SCHEMA)
163
+ schema_content["_content"]["properties"]["stock"]["type"] = ":AppleCrate"
164
+ schema_loader = FakeSchemaLoader(schema_content)
165
+ types_loader = FakeTypesLoader(VALID_DEFINED_TYPES)
166
+ with self.assertRaisesRegex(
167
+ DBSchemaError,
168
+ "Expandable object SchemaAppleCrate\+ must be in a list, it cannot "
169
+ "be member of object such as _content",
170
+ ):
171
+ Schema(schema_loader, types_loader)
172
+
173
+ def test_expandable_double(self):
174
+ schema_content = copy.deepcopy(VALID_SCHEMA)
175
+ schema_content["_objects"]["AppleCrate"]["properties"]["quantity"][
176
+ "type"
177
+ ] = "expandable"
178
+ schema_loader = FakeSchemaLoader(schema_content)
179
+ types_loader = FakeTypesLoader(VALID_DEFINED_TYPES)
180
+ with self.assertRaisesRegex(
181
+ DBSchemaError,
182
+ "Expandable object AppleCrate cannot contain more than one "
183
+ "expandable property",
184
+ ):
185
+ Schema(schema_loader, types_loader)
186
+
187
+ def test_reference_undefined_object(self):
188
+ schema_content = copy.deepcopy(VALID_SCHEMA)
189
+ schema_content["_objects"]["AppleCrate"]["properties"]["variety"][
190
+ "type"
191
+ ] = "$Unknown.object"
192
+ schema_loader = FakeSchemaLoader(schema_content)
193
+ types_loader = FakeTypesLoader(VALID_DEFINED_TYPES)
194
+ with self.assertRaisesRegex(
195
+ DBSchemaError,
196
+ "Definition of object Unknown not found in schema",
197
+ ):
198
+ Schema(schema_loader, types_loader)
199
+
200
+ def test_reference_undefined_property(self):
201
+ schema_content = copy.deepcopy(VALID_SCHEMA)
202
+ schema_content["_objects"]["AppleCrate"]["properties"]["variety"][
203
+ "type"
204
+ ] = "$Apple.unknown"
205
+ schema_loader = FakeSchemaLoader(schema_content)
206
+ types_loader = FakeTypesLoader(VALID_DEFINED_TYPES)
207
+ with self.assertRaisesRegex(
208
+ DBSchemaError,
209
+ "Reference \$Apple.unknown to undefined SchemaApple object " "property",
210
+ ):
211
+ Schema(schema_loader, types_loader)
@@ -0,0 +1,23 @@
1
+ # Copyright (c) 2022-2023 Rackslab
2
+ #
3
+ # This file is part of RacksDB.
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ import unittest
8
+
9
+ from racksdb.generic.schema import SchemaDefinedTypeLoader
10
+ from racksdb.generic.definedtype import SchemaDefinedType
11
+
12
+
13
+ class TestSchemaDefinedTypeLoader(unittest.TestCase):
14
+ def test_schema_defined_type_loader(self):
15
+ # Load defined types provided in RacksDB
16
+ loader = SchemaDefinedTypeLoader("racksdb.dtypes")
17
+ # Verify at least one defined type has been loaded
18
+ self.assertGreater(len(loader.content), 0)
19
+ # Verify loader content is a dict
20
+ self.assertIs(type(loader.content), dict)
21
+ # Verify content values are valid SchemaDefinedType
22
+ for defined_type in loader.content.values():
23
+ self.assertIsInstance(defined_type, SchemaDefinedType)
@@ -0,0 +1,83 @@
1
+ # Copyright (c) 2023 Rackslab
2
+ #
3
+ # This file is part of RacksDB.
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ import os
8
+ from pathlib import Path
9
+ import unittest
10
+
11
+ from racksdb import RacksDB
12
+
13
+
14
+ class TestDBLoad(unittest.TestCase):
15
+ def setUp(self):
16
+ # Try relative path and system paths sequentially for both the schema
17
+ # and example database. If none of these paths exist, gently skip the
18
+ # test with meaningful message.
19
+ current_dir = os.path.dirname(os.path.realpath(__file__))
20
+ schema_paths = [
21
+ Path(current_dir).joinpath("../../schema/racksdb.yml"),
22
+ Path("/usr/share/racksdb/schema.yml"),
23
+ ]
24
+ self.schema_path = None
25
+ for schema_path in schema_paths:
26
+ if schema_path.exists():
27
+ self.schema_path = schema_path
28
+ break
29
+ if self.schema_path is None:
30
+ self.skipTest("Unable to find schema file to run test")
31
+ db_paths = [
32
+ Path(current_dir).joinpath("../../examples/db"),
33
+ Path("/usr/share/doc/racksdb/examples/db"),
34
+ ]
35
+ self.db_path = None
36
+ for db_path in db_paths:
37
+ if db_path.exists():
38
+ self.db_path = db_path
39
+ break
40
+ if self.db_path is None:
41
+ self.skipTest("Unable to find db file to run test")
42
+
43
+ def test_load(self):
44
+ RacksDB.load(schema=self.schema_path, db=self.db_path)
45
+
46
+ def test_content(self):
47
+ db = RacksDB.load(schema=self.schema_path, db=self.db_path)
48
+ self.assertEqual(type(db), RacksDB)
49
+ self.assertEqual(len(db.infrastructures), 1)
50
+ # Thanks to lazy loading, just a few expandable object are loaded, much
51
+ # fewer than the number of nodes. The number of potentially expanded
52
+ # objects is reported correctly by len(). However, it must be much lower
53
+ # than the actual number of keys/values in the dictionnary.
54
+ self.assertEqual(len(db.nodes.keys()), 5)
55
+ self.assertEqual(len(db.nodes), 121)
56
+ self.assertEqual(
57
+ type(db.infrastructures.first()).__name__, "RacksDBInfrastructure"
58
+ )
59
+ self.assertEqual(db.infrastructures.first().name, "mercury")
60
+ self.assertEqual(db.infrastructures["mercury"].name, "mercury")
61
+ self.assertEqual(len(db.infrastructures["mercury"].nodes.keys()), 5)
62
+ self.assertEqual(len(db.infrastructures["mercury"].nodes), 121)
63
+ self.assertEqual(len(db.infrastructures["mercury"].layout[0].nodes), 61)
64
+ self.assertEqual(
65
+ type(db.infrastructures["mercury"].nodes["mecn0001"]).__name__,
66
+ "RacksDBNode",
67
+ )
68
+ self.assertEqual(
69
+ db.infrastructures["mercury"].nodes["mecn0001"].name, "mecn0001"
70
+ )
71
+ self.assertEqual(
72
+ db.infrastructures["mercury"].nodes["mecn0001"].type.model,
73
+ "SuperMicro A+ Server 2124BT-HTR",
74
+ )
75
+ self.assertEqual(
76
+ db.infrastructures["mercury"].nodes["mecn0010"]._first.name, "mecn0001"
77
+ )
78
+ self.assertEqual(
79
+ db.infrastructures["mercury"].nodes["mecn0010"].tags, ["compute"]
80
+ )
81
+ node = db.infrastructures["mercury"].nodes["mecn0001"]
82
+ self.assertEqual(node, node._first)
83
+ # print(db.infrastructures["mercury"].nodes)
racksdb/version.py ADDED
@@ -0,0 +1,11 @@
1
+ # Copyright (c) 2022-2023 Rackslab
2
+ #
3
+ # This file is part of RacksDB.
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ import pkg_resources
8
+
9
+
10
+ def get_version():
11
+ return pkg_resources.get_distribution("racksdb").version
racksdb/views.py ADDED
@@ -0,0 +1,136 @@
1
+ # Copyright (c) 2023 Rackslab
2
+ #
3
+ # This file is part of RacksDB.
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ from .generic.views import (
8
+ DBViewSet,
9
+ DBView,
10
+ DBViewFilter,
11
+ DBViewParameter,
12
+ DBAction,
13
+ DBActionParameter,
14
+ DBActionResponse,
15
+ )
16
+
17
+
18
+ class RacksDBViews(DBViewSet):
19
+ VIEWS = [
20
+ DBView(
21
+ content="datacenters",
22
+ objects_name="Datacenter",
23
+ description="Get information about datacenters",
24
+ filters=[
25
+ DBViewFilter(name="name", description="Filter datacenters by name"),
26
+ DBViewFilter(
27
+ name="tags", description="Filter datacenters by tag", nargs="*"
28
+ ),
29
+ ],
30
+ objects_map={
31
+ "RacksDBDatacenter": None,
32
+ "RacksDBDatacenterRoom": "name",
33
+ "RacksDBRacksRow": "name",
34
+ "RacksDBRack": "name",
35
+ "RacksDBRack.nodes": None,
36
+ },
37
+ ),
38
+ DBView(
39
+ content="infrastructures",
40
+ objects_name="Infrastructure",
41
+ description="Get information about infrastructures",
42
+ filters=[
43
+ DBViewFilter(name="name", description="Filter infrastructures by name"),
44
+ DBViewFilter(
45
+ name="tags",
46
+ description="Filter infrastructures by tag",
47
+ nargs="*",
48
+ ),
49
+ ],
50
+ objects_map={
51
+ "RacksDBDatacenter": "name",
52
+ "RacksDBDatacenterRoom": "name",
53
+ "RacksDBRack": "name",
54
+ "RacksDBInfrastructure": None,
55
+ },
56
+ ),
57
+ DBView(
58
+ content="nodes",
59
+ objects_name="Node",
60
+ description="Get information about nodes",
61
+ filters=[
62
+ DBViewFilter(name="name", description="Filter nodes by name"),
63
+ DBViewFilter(
64
+ name="infrastructure",
65
+ description="Filter nodes by infrastructure",
66
+ ),
67
+ DBViewFilter(name="tags", description="Filter nodes by tag", nargs="*"),
68
+ ],
69
+ objects_map={
70
+ "RacksDBGroupRack": "name",
71
+ "RacksDBDatacenter": "name",
72
+ "RacksDBDatacenterRoom": "name",
73
+ "RacksDBRacksRow": "name",
74
+ "RacksDBInfrastructure": "name",
75
+ "RacksDBRack.nodes": None,
76
+ },
77
+ ),
78
+ DBView(
79
+ content="racks",
80
+ objects_name="Rack",
81
+ description="Get information about racks",
82
+ filters=[DBViewFilter(name="name", description="Filter racks by name")],
83
+ objects_map={
84
+ "RacksDBDatacenter": "name",
85
+ "RacksDBDatacenterRoom": "name",
86
+ "RacksDBRacksRow": "name",
87
+ "RacksDBRack": None,
88
+ "RacksDBNodeType": "id",
89
+ "RacksDBInfrastructure": "name",
90
+ },
91
+ ),
92
+ ]
93
+ PARAMETERS = [
94
+ DBViewParameter(
95
+ "list",
96
+ "Get list of object names instead of full objects",
97
+ short="l",
98
+ nargs=0,
99
+ ),
100
+ DBViewParameter("fold", "Fold expandable objects", short="f", nargs=0),
101
+ DBViewParameter(
102
+ "with_objects_types", "Report object types in YAML dumps", nargs=0
103
+ ),
104
+ DBViewParameter(
105
+ "format",
106
+ "Select output format",
107
+ choices=["yaml", "json"],
108
+ ),
109
+ ]
110
+ ACTIONS = [
111
+ DBAction(
112
+ name="draw",
113
+ path="/draw/<entity>/<name>.<format>",
114
+ description="Draw an entity",
115
+ parameters=[
116
+ DBActionParameter(
117
+ "entity",
118
+ description="Type of entity to draw",
119
+ choices=["infrastructure", "room"],
120
+ positional=True,
121
+ ),
122
+ DBActionParameter("name", description="Name of entity", required=True),
123
+ DBActionParameter(
124
+ "format",
125
+ description="Format of the generated image",
126
+ choices=["png", "svg", "pdf"],
127
+ default="png",
128
+ ),
129
+ ],
130
+ responses=[
131
+ DBActionResponse("image/png", binary=True),
132
+ DBActionResponse("image/svg+xml"),
133
+ DBActionResponse("application/pdf", binary=True),
134
+ ],
135
+ )
136
+ ]
File without changes
racksdb/web/app.py ADDED
@@ -0,0 +1,195 @@
1
+ # Copyright (c) 2023 Rackslab
2
+ #
3
+ # This file is part of RacksDB.
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ import argparse
8
+ from pathlib import Path
9
+ import io
10
+ import logging
11
+
12
+ from flask import Flask, Blueprint, Response, request, send_file
13
+
14
+ from .. import RacksDB
15
+ from ..version import get_version
16
+ from ..views import RacksDBViews
17
+ from ..generic.openapi import OpenAPIGenerator
18
+ from ..generic.dumpers import DBDumperFactory, SchemaDumperFactory
19
+ from ..drawers import InfrastructureDrawer, RoomDrawer
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ class RacksDBWebBlueprint(Blueprint):
25
+ MIMETYPES = {
26
+ "json": "application/json",
27
+ "yaml": "application/x-yaml",
28
+ "png": "image/png",
29
+ "svg": "image/svg+xml",
30
+ "pdf": "application/pdf",
31
+ }
32
+
33
+ def __init__(
34
+ self,
35
+ schema=RacksDB.DEFAULT_SCHEMA,
36
+ ext=RacksDB.DEFAULT_EXT,
37
+ db=RacksDB.DEFAULT_DB,
38
+ openapi=False,
39
+ ):
40
+ super().__init__("RacksDB web blueprint", __name__)
41
+ self.db = RacksDB.load(schema=schema, ext=ext, db=db)
42
+ self.views = RacksDBViews()
43
+ self.add_url_rule("/schema", view_func=self._schema, methods=["GET"])
44
+ self.add_url_rule("/dump", view_func=self._dump, methods=["GET"])
45
+ if openapi:
46
+ self.add_url_rule("/openapi.yaml", view_func=self._openapi, methods=["GET"])
47
+ self.add_url_rule("/<content>", view_func=self._dump_view, methods=["GET"])
48
+
49
+ for action in self.views.actions():
50
+ # add path with generic action
51
+ self.add_url_rule(
52
+ action.path,
53
+ view_func=getattr(self, f"_{action.name}"),
54
+ methods=["GET"],
55
+ )
56
+
57
+ def _schema(self):
58
+ return Response(
59
+ response=SchemaDumperFactory.get("yaml")().dump(self.db._schema),
60
+ mimetype=self.MIMETYPES["yaml"],
61
+ )
62
+
63
+ def _dump(self):
64
+ return Response(
65
+ response=DBDumperFactory.get("yaml")().dump(self.db._loader.content),
66
+ mimetype=self.MIMETYPES["yaml"],
67
+ )
68
+
69
+ def _dump_view(self, content):
70
+ data = getattr(self.db, content)
71
+ view = self.views[content]
72
+ filters = {}
73
+ for _filter in view.filters:
74
+ value = request.args.get(_filter.name)
75
+ if value is not None and _filter.nargs is not None:
76
+ value = value.split(",")
77
+ filters[_filter.name] = value
78
+ data = data.filter(**filters)
79
+
80
+ if "list" in request.args:
81
+ data = [item.name for item in data]
82
+
83
+ dump_format = request.args.get("format", "json")
84
+ dumper = DBDumperFactory.get(dump_format)(
85
+ show_types="with_objects_types" in request.args,
86
+ objects_map=view.objects_map,
87
+ fold="fold" in request.args,
88
+ )
89
+ return Response(
90
+ response=dumper.dump(data), mimetype=self.MIMETYPES[dump_format]
91
+ )
92
+
93
+ def _draw(self, entity, name, format):
94
+ file = io.BytesIO()
95
+ if entity == "infrastructure":
96
+ drawer = InfrastructureDrawer(self.db, name, file, format)
97
+ elif entity == "room":
98
+ drawer = RoomDrawer(self.db, name, file, format)
99
+ drawer.draw()
100
+ file.seek(0)
101
+ return send_file(
102
+ file,
103
+ mimetype=self.MIMETYPES[format],
104
+ )
105
+
106
+ def _openapi(self):
107
+ dumper = DBDumperFactory.get("yaml")()
108
+ data = OpenAPIGenerator(self.db, self.views).generate()
109
+ return Response(response=dumper.dump(data), mimetype=self.MIMETYPES["yaml"])
110
+
111
+
112
+ class RacksDBWebApp(Flask):
113
+ def __init__(self):
114
+ super().__init__("RacksDB web application")
115
+ parser = argparse.ArgumentParser(description="RacksDB web application")
116
+ parser.add_argument(
117
+ "-v",
118
+ "--version",
119
+ dest="version",
120
+ action="version",
121
+ version="RacksDB " + get_version(),
122
+ )
123
+ parser.add_argument(
124
+ "--debug",
125
+ dest="debug",
126
+ action="store_true",
127
+ help="Enable debug mode",
128
+ )
129
+ parser.add_argument(
130
+ "-s",
131
+ "--schema",
132
+ help="Schema to load (default: %(default)s)",
133
+ default=RacksDB.DEFAULT_SCHEMA,
134
+ type=Path,
135
+ )
136
+ parser.add_argument(
137
+ "-e",
138
+ "--ext",
139
+ help="Path to extensions of schema (default: %(default)s)",
140
+ default=RacksDB.DEFAULT_EXT,
141
+ type=Path,
142
+ )
143
+ parser.add_argument(
144
+ "-b",
145
+ "--db",
146
+ help="Database to load (default: %(default)s)",
147
+ default=RacksDB.DEFAULT_DB,
148
+ type=Path,
149
+ )
150
+ parser.add_argument(
151
+ "--host",
152
+ help="Binding interface for listening socket (default: %(default)s)",
153
+ default="localhost",
154
+ )
155
+ parser.add_argument(
156
+ "-p",
157
+ "--port",
158
+ help="TCP port for listening socket (default: %(default)s)",
159
+ default=5000,
160
+ type=int,
161
+ )
162
+ parser.add_argument(
163
+ "--cors",
164
+ action="store_true",
165
+ help="Enable CORS headers",
166
+ )
167
+ parser.add_argument(
168
+ "--openapi",
169
+ action="store_true",
170
+ help="Enable OpenAPI route",
171
+ )
172
+
173
+ self.args = parser.parse_args()
174
+ self.register_blueprint(
175
+ RacksDBWebBlueprint(
176
+ self.args.schema, self.args.ext, self.args.db, self.args.openapi
177
+ )
178
+ )
179
+
180
+ def serve(self):
181
+ logger.info("Running RacksDB web application")
182
+ if self.args.cors:
183
+ from flask_cors import CORS
184
+
185
+ CORS(self)
186
+ super().run(
187
+ host=self.args.host,
188
+ port=self.args.port,
189
+ debug=self.args.debug,
190
+ )
191
+
192
+ @classmethod
193
+ def run(cls):
194
+ app = cls()
195
+ app.serve()