views.py
18.2 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
from collections import OrderedDict
from django import conf
from django.shortcuts import render
from .obsconfig_class import OBSConfig
from django.conf import settings
from src.core.pyros_django.dashboard.decorator import level_required
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from datetime import datetime
from django.views.decorators.csrf import csrf_exempt
import re
import yaml
import tempfile
import json
import os
def get_nested_dictionaries_as_list(dic, result=[]):
for key, value in dic.items():
print(value, type(value))
print(result)
if isinstance(value, dict):
print("recursive call")
get_nested_dictionaries_as_list(value, result)
elif isinstance(value, list) and key == "CAPABILITIES":
print("VALUE OF LIST ======= ", value)
for element in value:
# print(element)
if isinstance(element, dict):
get_nested_dictionaries_as_list(element, result)
else:
result.append((key, value))
return result
@login_required
@level_required("Admin", "Observer", "Management", "Operator", "Unit-PI")
def obs_global_config(request):
config = OBSConfig(
os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
units_names = list(config.get_units().keys())
pickle_file_mtime = os.path.getmtime(config.CONFIG_PATH+config.pickle_file)
pickle_datetime = datetime.utcfromtimestamp(
pickle_file_mtime).strftime("%Y/%m/%d %H:%M:%S")
CAN_EDIT_CONFIG = request.session.get("role") in (
"Admin", "Operator", "Unit-PI", "Unit-board")
CAN_VIEW_HARDWARE_CONFIG = request.session.get("role") in (
"Admin", "Operator", "Unit-PI", "Unit-board")
CAN_VIEW_ASTRONOMER_CONFIG = request.session.get("role") in (
"Admin", "Operator", "Unit-PI", "Observer", "Management board manager", "Unit-board")
CAN_VIEW_AGENTS_CONFIG = request.session.get("role") == "Admin"
return render(request, "obs_config/global_obs_configuration.html", {
"units_names": units_names,
"obs_name": config.get_obs_name(),
"last_modification_time": pickle_datetime,
"CAN_EDIT_CONFIG": CAN_EDIT_CONFIG,
"CAN_VIEW_HARDWARE_CONFIG": CAN_VIEW_HARDWARE_CONFIG,
"CAN_VIEW_ASTRONOMER_CONFIG": CAN_VIEW_ASTRONOMER_CONFIG,
"CAN_VIEW_AGENTS_CONFIG": CAN_VIEW_AGENTS_CONFIG
})
@login_required
@level_required("Admin", "Unit-PI", "Operator")
def obs_hardware_config(request):
config = OBSConfig(
os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
devices = config.get_devices()
active_devices = config.get_active_devices()
computers = config.get_computers()
active_computers = config.get_active_computers()
# give for a device name (key) the unit name where it is used (value)
device_to_unit = {}
# give for a computer name (key) the unit name where it is used (value)
computer_to_unit = {}
for device in active_devices:
device_to_unit[device] = config.get_unit_of_device(device)
for computer in active_computers:
computer_to_unit[computer] = config.get_unit_of_computer(computer)
devices_links = config.devices_links
return render(request, 'obs_config/obs_hardware_configuration.html', {'devices': devices, "active_devices": active_devices, "computers": computers, "active_computers": active_computers, "device_to_unit": device_to_unit, "computer_to_unit": computer_to_unit, "devices_links": devices_links})
@login_required
@level_required("Admin", "Unit-PI", "Operator")
def unit_hardware_configuration(request, unit_name):
config = OBSConfig(
os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
devices = config.get_devices()
return render(request, 'obs_config/unit_hardware_configuration.html', {'config': config})
@login_required
@level_required("Admin", "Unit-PI", "Operator")
def computer_details(request, computer_name):
config = OBSConfig(
os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
computer_detail = yaml.dump(config.get_computers()[computer_name])
"""
computer_detail = { re.sub("^_","",key):value for key,
value in config.get_computers()[computer_name].items() }
# We're removing "_" at the beginning of each key :
power = { re.sub("^_","",key):value for key,
value in config.get_computer_power(computer_name).items() }
computer_config = computer_detail["computer_config"]
# We're removing "_" at the beginning of each key :
computer_detail["computer_config"] = {
re.sub("^_","",key):value for key,value in computer_config.items() }
# Remove power key as we have this information in the same
if power is not None:
computer_detail["computer_config"].pop("power")
return render(request,"obs_config/computer_details.html", {"computer_detail" : computer_detail, "power" : power})
"""
return render(request, "obs_config/computer_details.html", {"computer_detail": computer_detail})
@login_required
@level_required("Admin", "Unit-PI", "Operator", "Observer")
def device_details(request, device_name):
config = OBSConfig(
os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
# We're removing "_" at the beginning of each key :
device = config.get_devices()[device_name]
# device_detail = yaml.dump(device)
# config_device = open(config.CONFIG_PATH+device["file"],"r").read()
devices_links = config.devices_links
file_name_to_device_name = {
v: k for k, v in config.get_devices_names_and_file().items()}
active_devices = config.get_active_devices()
"""
Alternative solutions:
- test_device -> we're using a recursive function to get all nested dicitonaries but we loose a level of
"precision" (no separations of capabilities for example)
- device_detail -> we use multiple function to get specific value (not global enougth, if we had another key we have to change the code)
"""
device_detail = {re.sub("^_", "", key): value for key,
value in config.get_devices()[device_name].items()}
# test_device= get_nested_dictionaries_as_list(device_detail,[])
if config.get_device_power(device_name) is not None:
# We're removing "_" at the beginning of each key :
power = {re.sub("^_", "", key): value for key,
value in config.get_device_power(device_name).items()}
else:
power = None
if config.get_device_connector(device_name) is not None:
# We're removing "_" at the beginning of each key :
connector = {re.sub("^_", "", key): value for key,
value in config.get_device_connector(device_name).items()}
else:
connector = None
capabilities = []
if config.get_device_capabilities(device_name) is not None:
copy_capabilities = config.get_device_capabilities(device_name)
for capability in copy_capabilities:
# We're removing "_" at the beginning of each key :
capabilities.append(
{re.sub("^_", "", key): value for key, value in capability.items()})
device_config = device_detail["device_config"]
# We're removing "_" at the beginning of each key :
device_detail["device_config"] = {
re.sub("^_", "", key): value for key, value in device_config.items()}
# Remove power key as we have this information in the same
if power is not None:
device_detail["device_config"].pop("power")
if connector is not None:
device_detail["device_config"].pop("connector")
if len(capabilities) != 0:
device_detail["device_config"].pop("CAPABILITIES")
return render(request, "obs_config/device_details.html", {"device_detail": device_detail, "power": power, "connector": connector, "capabilities": capabilities, "devices_links": devices_links, "file_name_to_device_name": file_name_to_device_name, "active_devices": active_devices})
# return render(request,"obs_config/device_details.html", { "device_detail" : device_detail, "config" : config_device })
@login_required
@level_required("Admin", "Observer", "Management", "Operator", "Unit-PI", "TAC")
def obs_astronomer_config(request):
config = OBSConfig(
os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
units = config.get_units()
units_topologies = {}
# for each unit
for unit_name in units:
units_topologies[unit_name] = config.get_topology(unit_name)
layouts = units_topologies[unit_name].pop("LAYOUTS")["layouts"]
albums = units_topologies[unit_name].pop("ALBUMS")["albums"]
# for each category (security, mount, channels)
for category in units_topologies[unit_name]:
if category != "CHANNELS":
# Security and Mount are directly a dictionary containing the attributes of those categories
# However, component_agents is a list so we need to iterate through this list
for index, component_agent in enumerate(units_topologies[unit_name][category]["COMPONENT_AGENTS"]):
component_name = list(component_agent.keys())[0]
agent = component_agent[component_name]
device_of_agent = config.get_device_for_agent(
unit_name, agent)
units_topologies[unit_name][category]["COMPONENT_AGENTS"][index][component_name] = device_of_agent
else:
# Channels is composed of a list of channel, we're looping through it
# We want to list every component for each channels
for channel_name in units_topologies[unit_name]["CHANNELS"]:
units_topologies[unit_name]["CHANNELS"][channel_name]["DEVICES"] = []
for index, agent in enumerate(units_topologies[unit_name]["CHANNELS"][channel_name]["AGENTS"]):
device = config.get_device_for_agent(
unit_name, agent)
if device is None:
# Agent is not an AgentDevice
continue
else:
units_topologies[unit_name]["CHANNELS"][channel_name]["DEVICES"].append(device)
for index, device in enumerate(units_topologies[unit_name]["CHANNELS"][channel_name]["COMPONENTS"]):
device = config.get_device_information(device)
units_topologies[unit_name]["CHANNELS"][channel_name]["DEVICES"].append(device)
# Re add layouts and albums
units_topologies[unit_name]["LAYOUTS"] = layouts
units_topologies[unit_name]["ALBUMS"] = albums
order_of_keys = ["SECURITY", "MOUNT", "LAYOUTS", "ALBUMS", "CHANNELS"]
list_of_tuples = [(key, units_topologies[unit_name][key])
for key in order_of_keys]
units_topologies[unit_name] = OrderedDict(list_of_tuples)
return render(request, "obs_config/obs_astronomer_config.html", {
"units_topologies": units_topologies,
})
@ login_required
@ level_required("Admin")
def obs_agents_config(request):
config = OBSConfig(
os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
units = config.get_units()
units_topologies = {}
active_agents_by_unit = {}
# for each unit
for unit_name in units:
agents = config.get_agents(unit_name)
# list of active agents of the current unit
active_agents_by_unit[unit_name] = config.get_active_agents(unit_name)
# topology of the current unit
units_topologies[unit_name] = config.get_topology(unit_name)
# removing albums and layouts, not useful in this view
units_topologies[unit_name].pop("LAYOUTS")
units_topologies[unit_name].pop("ALBUMS")
for category in units_topologies[unit_name]:
if category != "CHANNELS":
# Security and Mount are directly a dictionary containing the attributes of those categories
# However, component_agents is a list so we need to iterate through this list
for component_agent in units_topologies[unit_name][category]["COMPONENT_AGENTS"]:
component_name = list(component_agent.keys())[0]
agent = agents[component_agent[component_name]]
# get the index of the current component, agent couple
index = units_topologies[unit_name][category]["COMPONENT_AGENTS"].index(
component_agent)
units_topologies[unit_name][category]["COMPONENT_AGENTS"][index][component_name] = agent
else:
for channel_name in units_topologies[unit_name]["CHANNELS"]:
units_topologies[unit_name]["CHANNELS"][channel_name]["CAPABILITIES"] = {}
for index, agent in enumerate(units_topologies[unit_name]["CHANNELS"][channel_name]["AGENTS"]):
# get agent informations
if type(agent) == str:
agent = config.get_agent_information(unit_name, agent)
if agent is None:
# agent missing link, not defined in agents list in obs config
pass
device = agent.get("device")
if device:
capabilities = config.get_device_capabilities(device)
units_topologies[unit_name]["CHANNELS"][channel_name]["CAPABILITIES"][device] = capabilities
units_topologies[unit_name]["CHANNELS"][channel_name]["AGENTS"][index] = agent
agents = config.get_agents_per_computer(config.unit_name)
computers = {}
for computer in config.get_computers():
computers[config.get_computers().get(computer).get("computer_config").get("hostname")] = computer
units_topologies[unit_name]["COMPUTERS"] = agents
return render(request, "obs_config/obs_agents_config.html", {"units_topologies": units_topologies, "active_agents_by_unit": active_agents_by_unit,"computers":computers})
@ login_required
@ level_required("Admin", "Operator", "Unit-PI", "Unit-board")
def edit_config(request):
config = OBSConfig(
os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
return render(request, "obs_config/edit_config.html", {"config_file": config.raw_config})
@ login_required
@ level_required("Admin", "Operator", "Unit-PI", "Unit-board")
def verify_config(request):
if request.POST.get("config"):
temp_config_file = tempfile.NamedTemporaryFile(
mode='w+', suffix=".yml")
temp_config_file.write(request.POST.get("config"))
temp_config_file.seek(0)
response_data = {}
try:
config_file = yaml.safe_load(temp_config_file.read())
except yaml.YAMLError as exc:
if hasattr(exc, 'problem_mark'):
yaml_error_message = ""
if exc.context != None:
yaml_error_message += str(exc.problem_mark) + \
'\n ' + str(exc.problem) + ' ' + str(exc.context)
else:
yaml_error_message = str(
exc.problem_mark.name) + '\n ' + str(exc.problem)
response_data["is_valid"] = False
response_data["yaml_error_message"] = yaml_error_message
return HttpResponse(json.dumps(response_data), content_type="application/json")
temp_config_file.seek(0)
schema = config_file["schema"]
errors = []
if schema == None:
response_data["is_valid"] = False
response_data["message"] = "Missing schema"
schema_path = os.path.join(
os.environ["DJANGO_PATH"], "../../../config/observatory/general/schemas/")
config = OBSConfig.check_config(
temp_config_file.name, schema_path+schema)
if type(config) == bool and config:
response_data["is_valid"] = True
else:
response_data["is_valid"] = False
for error in config:
errors.append(
(f"Error : {str(error).split('. Path')[0]}", f"Path to error : '{error.path}'"))
response_data["message"] = errors
temp_config_file.close()
return HttpResponse(json.dumps(response_data), content_type="application/json")
@ login_required
@ level_required("Admin", "Operator", "Unit-PI", "Unit-board")
def save_config(request):
if request.POST:
if request.POST["config"]:
with open(os.environ["PATH_TO_OBSCONF_FILE"], "w") as obs_config_file:
obs_config_file.write(request.POST.get("config"))
return HttpResponse("Ok !")
@ login_required
@ level_required("Admin", "Unit-PI", "Operator", "Observer")
@ csrf_exempt
def view_raw_component_config_file(request):
COMPONENT_PATH = os.path.join(
os.environ["DJANGO_PATH"], "../../../config/components/")
if request.POST:
try:
yaml_file = open(COMPONENT_PATH+request.POST["yaml_file"])
content = yaml_file.readlines()
except:
content = "Component defined within the device configuration file"
return HttpResponse(content)
@ login_required
@ level_required("Admin", "Unit-PI", "Operator", "Observer")
@ csrf_exempt
def view_raw_generic_device_config_file(request):
GENERIC_DEVICES_PATH = os.path.join(
os.environ["DJANGO_PATH"], "../../../config/observatory/general/devices/")
if request.POST:
yaml_file = open(GENERIC_DEVICES_PATH+request.POST["yaml_file"])
content = yaml_file.readlines()
return HttpResponse(content)
@ login_required
@ level_required("Admin", "Unit-PI", "Operator", "Observer")
@ csrf_exempt
def view_raw_device_config_file(request):
obs_folder = os.environ["PATH_TO_OBSCONF_FOLDER"]
if request.POST:
yaml_file = open(obs_folder+request.POST["yaml_file"])
content = yaml_file.readlines()
return HttpResponse(content)
@ login_required
@ level_required("Admin", "Unit-PI", "Operator", "Observer")
def obs_config_help(request):
return render(request, "obs_config/obs_config_help.html")