Source code for festivalgrid.management.commands.check_config
import os
import json
import requests
from django.core.management import call_command
from django.contrib.auth.models import User
from django.conf import settings
from grafana_api.grafana_api import GrafanaClientError
from grafana_api.grafana_face import GrafanaFace
from django.core.management.base import BaseCommand
[docs]class Command(BaseCommand):
help = 'Check Festival Grid configuration.'
[docs] def handle(self, *args, **options):
self.stdout.write(self.style.MIGRATE_LABEL("\nMaking and applying django migrations."))
call_command('makemigrations', 'festivalgrid')
call_command('migrate')
self.stdout.write(self.style.MIGRATE_LABEL("\nChecking superuser."))
if len(User.objects.filter(is_superuser=True)) < 1:
self.stdout.write(self.style.MIGRATE_LABEL(" No superuser detected. Creating default user \"festivalgrid\" with password \"festivalgrid\"\n"))
user = User.objects.create_user(username='festivalgrid',
password='festivalgrid', is_superuser=True, is_staff=True)
else:
self.stdout.write(" found superuser")
self.stdout.write(self.style.MIGRATE_LABEL("\nGenerating sphinx documentation."))
os.system('cd /app/doc/ && make clean && make html')
self.stdout.write(self.style.MIGRATE_LABEL("\nChecking grafana configuration."))
token = settings.GRAFANA_TOKEN
if token == "":
self.stdout.write(" requesting API token...")
r = requests.post("http://grafana:3000/api/auth/keys", auth=(settings.GRAFANA_USERNAME, settings.GRAFANA_PASSWORD), verify=False, json={"name": "festivalgrid-id", "role": "Admin"})
try:
settings.GRAFANA_TOKEN = token = json.loads(r.text)["key"]
text = open(settings.ENV_PATH).read()
new_text = '\n'.join(("GRAFANA_TOKEN=%s" % token) if line.startswith("GRAFANA_TOKEN") else line for line in text.splitlines())
open(settings.ENV_PATH, 'w').write(new_text)
except KeyError:
self.stdout.write(" keyerror: " + str(r.text))
self.stdout.write(" checking grafana datasource")
grafana_api = GrafanaFace(auth=token, host="grafana:3000")
try:
datasource_id = grafana_api.datasource.get_datasource_id_by_name(settings.GRAFANA_DATASOURCE)
self.stdout.write(" datasource found.")
except GrafanaClientError:
self.stdout.write(" creating grafana datasource (influxdb)")
datasource = {
"name": settings.GRAFANA_DATASOURCE,
"type": "influxdb",
"url": "http://%s:%s" % (settings.INFLUXDB_HOST, settings.INFLUXDB_PORT),
"access": "proxy",
"database": settings.INFLUXDB_DATABASE_NAME,
"user": settings.INFLUXDB_USERNAME,
"password": settings.INFLUXDB_PASSWORD,
}
grafana_api.datasource.create_datasource(datasource)
self.stdout.write("\neverything looks good.\n ")