00TD02A_Copilot_Matematikk_AsCode_v3_del4 - itnett/FTD02H-N GitHub Wiki

Her er konkrete skript og øvelser som dekker praktisk bruk i fagene Database, Programmering og Linux og Container.

Emne: Database

Databasesystem: Forstå og sammenligne forskjellige databasesystemer som PostgreSQL, MariaDB, MongoDB, og Cassandra

Skript for å sette opp og sammenligne databasesystemer

#!/bin/bash

# Start Docker containers
docker-compose up -d

# Wait for containers to be fully up and running
sleep 20

# PostgreSQL setup
docker exec -i $(docker ps -qf "name=postgres") psql -U user -d testdb <<-EOSQL
CREATE TABLE PerformanceMetrics (
    metric_id SERIAL PRIMARY KEY,
    student_id INT,
    cpu_usage FLOAT,
    memory_usage FLOAT,
    network_traffic FLOAT,
    disk_usage FLOAT,
    network_latency FLOAT
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(1, 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# MariaDB setup
docker exec -i $(docker ps -qf "name=mariadb") mysql -u user -ppassword testdb <<-EOSQL
CREATE TABLE PerformanceMetrics (
    metric_id INT AUTO_INCREMENT PRIMARY KEY,
    student_id INT,
    cpu_usage FLOAT,
    memory_usage FLOAT,
    network_traffic FLOAT,
    disk_usage FLOAT,
    network_latency FLOAT
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(1, 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# MongoDB setup
docker exec -i $(docker ps -qf "name=mongodb") mongo testdb --eval '
db.PerformanceMetrics.insert({
    student_id: 1,
    cpu_usage: 75.5,
    memory_usage: 60.2,
    network_traffic: 500.0,
    disk_usage: 250.0,
    network_latency: 20.5
});
'

# Cassandra setup
docker exec -i $(docker ps -qf "name=cassandra") cqlsh <<-EOSQL
CREATE KEYSPACE testdb WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE testdb;
CREATE TABLE PerformanceMetrics (
    student_id UUID PRIMARY KEY,
    cpu_usage float,
    memory_usage float,
    network_traffic float,
    disk_usage float,
    network_latency float
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(now(), 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

SQL: Lær å skrive SQL-spørringer for PostgreSQL og MariaDB

PostgreSQL SQL-spørringer

-- Select all records
SELECT * FROM PerformanceMetrics;

-- Select specific columns
SELECT student_id, cpu_usage, memory_usage FROM PerformanceMetrics;

-- Where clause
SELECT * FROM PerformanceMetrics WHERE cpu_usage > 70;

-- Aggregate functions
SELECT AVG(cpu_usage) AS avg_cpu_usage, MAX(memory_usage) AS max_memory_usage FROM PerformanceMetrics;

MariaDB SQL-spørringer

-- Select all records
SELECT * FROM PerformanceMetrics;

-- Select specific columns
SELECT student_id, cpu_usage, memory_usage FROM PerformanceMetrics;

-- Where clause
SELECT * FROM PerformanceMetrics WHERE cpu_usage > 70;

-- Aggregate functions
SELECT AVG(cpu_usage) AS avg_cpu_usage, MAX(memory_usage) AS max_memory_usage FROM PerformanceMetrics;

Normalisering: Utfør normalisering på tabeller i SQL-databasene

Normaliseringseksempel

  1. Unormalisert tabell
CREATE TABLE Orders (
    order_id INT PRIMARY KEY,
    customer_name VARCHAR(255),
    product_id INT,
    product_name VARCHAR(255),
    quantity INT,
    order_date DATE
);
  1. 1NF: Atomære verdier
CREATE TABLE Customers (
    customer_id INT PRIMARY KEY,
    customer_name VARCHAR(255)
);

CREATE TABLE Products (
    product_id INT PRIMARY KEY,
    product_name VARCHAR(255)
);

CREATE TABLE Orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    order_date DATE
);

CREATE TABLE OrderDetails (
    order_detail_id INT PRIMARY KEY,
    order_id INT,
    product_id INT,
    quantity INT
);
  1. 2NF: Fjerne delvise avhengigheter
  • Tabellen er allerede i 2NF siden det ikke er noen delvise avhengigheter.
  1. 3NF: Fjerne transitive avhengigheter
  • Tabellen er allerede i 3NF siden det ikke er noen transitive avhengigheter.

ER-diagram: Lag ER-diagrammer for å modellere databasene

ER-diagram for Orders-databasen

+------------+          +-----------+          +-------------+
| Customers  |          | Orders    |          | OrderDetails|
+------------+          +-----------+          +-------------+
| customer_id|<---------| order_id  |          | order_detail_id|
| name       |          | customer_id|-------->| order_id    |
+------------+          | order_date|          | product_id  |
                        +-----------+          | quantity    |
                                               +-------------+

Brukeradministrasjon: Administrer brukere og rettigheter i PostgreSQL og MariaDB

PostgreSQL

-- Create a new user
CREATE USER newuser WITH PASSWORD 'password';

-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE testdb TO newuser;

MariaDB

-- Create a new user
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

-- Grant privileges
GRANT ALL PRIVILEGES ON testdb.* TO 'newuser'@'localhost';

Indeksering: Opprett indekser for å forbedre spørringsytelse

PostgreSQL

-- Create an index
CREATE INDEX idx_cpu_usage ON PerformanceMetrics (cpu_usage);

MariaDB

-- Create an index
CREATE INDEX idx_cpu_usage ON PerformanceMetrics (cpu_usage);

Logging: Implementer logging av databaseoperasjoner

PostgreSQL

-- Enable logging in postgresql.conf
log_statement = 'all'

-- Reload configuration
SELECT pg_reload_conf();

MariaDB

-- Enable logging in my.cnf
general_log = 1
general_log_file = /var/log/mysql/mysql.log

-- Restart MariaDB service
sudo systemctl restart mariadb

Backup og Restore: Utfør sikkerhetskopiering og gjenoppretting av databaser

PostgreSQL Backup

pg_dump -U user -d testdb > postgres_backup.sql

PostgreSQL Restore

psql -U user -d testdb < postgres_backup.sql

MariaDB Backup

mysqldump -u user -ppassword testdb > mariadb_backup.sql

MariaDB Restore

mysql -u user -ppassword testdb < mariadb_backup.sql

Kryptering: Lær hvordan du kan kryptere data i SQL-databasene

PostgreSQL

-- Enable SSL in postgresql.conf
ssl = on

-- Reload configuration
SELECT pg_reload_conf();

MariaDB

-- Enable SSL in my.cnf
[mysqld]
ssl-ca=/path/to/ca-cert.pem
ssl-cert=/path/to/server-cert.pem
ssl-key=/path/to/server-key.pem

-- Restart MariaDB service
sudo systemctl restart mariadb

Datavisualisering: Bruk verktøy som Grafana eller Tableau for å visualisere data fra databasene

Grafana Setup

  1. Install Grafana
sudo apt-get install -y adduser libfontconfig1
wget https://dl.grafana.com/oss/release/grafana_7.4.3_amd64.deb
sudo dpkg -i grafana_7.4.3_amd64.deb
  1. Start Grafana
sudo systemctl start grafana-server
sudo systemctl enable grafana-server.service
  1. Access Grafana at http://localhost:3000 and add PostgreSQL or MariaDB as a data source.

Sikkerhet: Implementer sikkerhetstiltak i databaser som bruk av SSL/TLS, brukertilgang og kryptering

PostgreSQL

-- Enable SSL in postgresql.conf
ssl = on

-- Create a new role with specific privileges
CREATE ROLE readonly;
GRANT CONNECT ON DATABASE testdb TO readonly;
GRANT USAGE ON SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

MariaDB

-- Enable SSL in my.cnf
[mysqld]
ssl-ca=/path/to/ca-cert.pem
ssl-cert=/path/to/server-cert.pem
ssl-key=/path/to/server-key.pem

-- Create a new user with specific privileges
CREATE USER 'readonly'@'localhost'

 IDENTIFIED BY 'password';
GRANT SELECT ON testdb.* TO 'readonly'@'localhost';

Emne: Programmering

Programstrukturer: Lær grunnleggende programstrukturer som variabler, kontrollstrukturer og løkker

Python Eksempel

# Variables
a = 5
b = 10

# Control Structures
if a < b:
    print("a is less than b")
else:
    print("a is not less than b")

# Loops
for i in range(5):
    print(i)

Datastrukturer: Forstå og bruk datastrukturer som lister, stakker, køer og trær

Python Eksempel

# List
my_list = [1, 2, 3, 4, 5]

# Stack
stack = []
stack.append(1)
stack.append(2)
print(stack.pop())

# Queue
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
print(queue.popleft())

# Binary Tree
class TreeNode:
    def __init__(self, value):
        self.left = None
        self.right = None
        self.value = value

Bibliotek: Bruk av standardbiblioteker i programmeringsspråk som Python

Python Eksempel

import math

print(math.sqrt(16))

import os

print(os.getcwd())

Funksjoner og metoder: Definer og bruk funksjoner og metoder

Python Eksempel

def greet(name):
    return f"Hello, {name}"

print(greet("World"))

Objektorientert programmering: Utvikle programmer ved hjelp av OOP-prinsipper

Python Eksempel

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

person = Person("Alice", 30)
print(person.greet())

Debugging, testing og unntaksbehandling: Bruk debugging-verktøy, skriv tester og håndter unntak

Python Eksempel

def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    return result

print(divide(10, 2))
print(divide(10, 0))

API: Bygg og bruk APIer for å kommunisere med databaser

Python Eksempel med Flask

from flask import Flask, jsonify, request
import psycopg2

app = Flask(__name__)

def get_db_connection():
    conn = psycopg2.connect(dbname="testdb", user="user", password="password", host="localhost")
    return conn

@app.route('/metrics', methods=['GET'])
def get_metrics():
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('SELECT * FROM PerformanceMetrics;')
    metrics = cur.fetchall()
    cur.close()
    conn.close()
    return jsonify(metrics)

if __name__ == '__main__':
    app.run(debug=True)

GUI: Utvikle grafiske brukergrensesnitt

Python Eksempel med Tkinter

import tkinter as tk

def greet():
    name = name_entry.get()
    greeting_label.config(text=f"Hello, {name}")

app = tk.Tk()
app.title("Greeting App")

name_label = tk.Label(app, text="Enter your name:")
name_label.pack()

name_entry = tk.Entry(app)
name_entry.pack()

greet_button = tk.Button(app, text="Greet", command=greet)
greet_button.pack()

greeting_label = tk.Label(app, text="")
greeting_label.pack()

app.mainloop()

UML: Lag UML-diagrammer for å designe programvare

UML Diagrams

Use tools like Lucidchart or Draw.io to create UML diagrams.

+---------------+        +---------------+
|    Person     |        |    Address    |
+---------------+        +---------------+
| - name: str   |        | - street: str |
| - age: int    |        | - city: str   |
+---------------+        +---------------+
| + greet()     |        | + get_full()  |
+---------------+        +---------------+
        |                        |
        +------------------------+

Filbehandling: Les og skriv til filer i forskjellige formater

Python Eksempel

# Write to a file
with open('example.txt', 'w') as f:
    f.write("Hello, World!")

# Read from a file
with open('example.txt', 'r') as f:
    content = f.read()
    print(content)

Datasikkerhet: Implementer sikkerhetspraksiser i programmering

Python Eksempel

import hashlib

def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

print(hash_password("securepassword"))

Emne: Linux og Container

Systemdrift: Administrer Linux-systemer

Basic Linux Commands

# List files
ls

# Change directory
cd /path/to/directory

# Copy files
cp source destination

# Move files
mv source destination

# Remove files
rm file

Linux distribusjoner: Utforsk ulike Linux-distribusjoner

Install Ubuntu

Download the ISO from Ubuntu and create a bootable USB using tools like Rufus.

Brukeradministrasjon: Administrer brukere og grupper i Linux

User Management

# Add a user
sudo adduser newuser

# Delete a user
sudo deluser newuser

# Add a user to a group
sudo usermod -aG groupname newuser

Installasjon: Installer og konfigurer programvare på Linux

Install Apache

sudo apt update
sudo apt install apache2

Nettverk: Konfigurer nettverk i Linux

Network Configuration

# View network interfaces
ip a

# Configure a static IP
sudo nano /etc/netplan/01-netcfg.yaml

Prosesser: Administrer prosesser og tjenester

Process Management

# List processes
ps aux

# Kill a process
kill -9 PID

# Start a service
sudo systemctl start servicename

# Stop a service
sudo systemctl stop servicename

Terminal: Bruk terminalkommandoer for systemadministrasjon

Basic Terminal Commands

# Display current directory
pwd

# Show disk usage
df -h

# Show memory usage
free -h

Pakkesystemer: Administrer programvarepakker med verktøy som apt, yum eller pacman

Package Management with apt

# Update package list
sudo apt update

# Upgrade packages
sudo apt upgrade

# Install a package
sudo apt install packagename

Lagring og filsystemer: Konfigurer og administrer lagringsenheter og filsystemer

Disk Management

# List disks
lsblk

# Format a disk
sudo mkfs.ext4 /dev/sdX1

# Mount a disk
sudo mount /dev/sdX1 /mnt

Servertjenester: Sett opp og administrer servertjenester som webservere, databaseservere, etc.

Setup Nginx

sudo apt update
sudo apt install nginx

# Start Nginx
sudo systemctl start nginx

# Enable Nginx to start on boot
sudo systemctl enable nginx

Containere: Bruk Docker til å administrere containere

Docker Commands

# Run a container
docker run -d --name mycontainer nginx

# List running containers
docker ps

# Stop a container
docker stop mycontainer

# Remove a container
docker rm mycontainer

Automatisering: Automatiser oppgaver med skripting og verktøy som Ansible

Ansible Playbook

- name: Install and start Apache
  hosts: webservers
  become: yes
  tasks:
    - name: Ensure Apache is installed
      apt:
        name: apache2
        state: present
    - name: Ensure Apache is running
      service:
        name: apache2
        state: started
        enabled: true

Sikkerhet: Implementer sikkerhetstiltak på Linux-systemer

SSH Key Authentication

# Generate SSH key
ssh-keygen -t rsa -b 4096 -C "[email protected]"

# Copy SSH key to server
ssh-copy-id user@server

Disse skriptene og øvelsene dekker praktisk bruk i fagene Database, Programmering, og Linux og Container. De gir en solid forståelse av grunnleggende og avanserte konsepter, og hvordan man anvender dem i virkelige scenarioer.


Ja, vi kan kjøre opp Grafana som en container i WSL-miljøet og konfigurere den til å nå alle databaseinstanser som kjører i Docker-containere. Her er en fullstendig veiledning som inkluderer oppsett av Grafana sammen med PostgreSQL, MariaDB, MongoDB, og Cassandra ved hjelp av Docker Compose og et skript for å automatisere prosessen.

1. Oppdater docker-compose.yml til å inkludere Grafana

Legg til Grafana-tjenesten i din docker-compose.yml fil.

version: '3.8'

services:
  postgres:
    image: postgres:latest
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
      POSTGRES_DB: testdb
    ports:
      - "5432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data

  mariadb:
    image: mariadb:latest
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: testdb
      MYSQL_USER: user
      MYSQL_PASSWORD: password
    ports:
      - "3306:3306"
    volumes:
      - mariadb-data:/var/lib/mysql

  mongodb:
    image: mongo:latest
    ports:
      - "27017:27017"
    volumes:
      - mongo-data:/data/db

  cassandra:
    image: cassandra:latest
    ports:
      - "9042:9042"
    volumes:
      - cassandra-data:/var/lib/cassandra

  grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"
    volumes:
      - grafana-data:/var/lib/grafana
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin

volumes:
  postgres-data:
  mariadb-data:
  mongo-data:
  cassandra-data:
  grafana-data:

2. Opprett Bash-skript database_setup.sh

Dette skriptet vil sette opp containerne, fylle dem med testdata, utføre sikkerhetskopiering og gjenoppretting, og konfigurere Grafana til å koble til alle databaseinstanser.

#!/bin/bash

# Start Docker containers
docker-compose up -d

# Wait for containers to be fully up and running
sleep 20

# PostgreSQL setup
echo "Setting up PostgreSQL..."
docker exec -i $(docker ps -qf "name=postgres") psql -U user -d testdb <<-EOSQL
CREATE TABLE PerformanceMetrics (
    metric_id SERIAL PRIMARY KEY,
    student_id INT,
    cpu_usage FLOAT,
    memory_usage FLOAT,
    network_traffic FLOAT,
    disk_usage FLOAT,
    network_latency FLOAT
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(1, 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# MariaDB setup
echo "Setting up MariaDB..."
docker exec -i $(docker ps -qf "name=mariadb") mysql -u user -ppassword testdb <<-EOSQL
CREATE TABLE PerformanceMetrics (
    metric_id INT AUTO_INCREMENT PRIMARY KEY,
    student_id INT,
    cpu_usage FLOAT,
    memory_usage FLOAT,
    network_traffic FLOAT,
    disk_usage FLOAT,
    network_latency FLOAT
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(1, 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# MongoDB setup
echo "Setting up MongoDB..."
docker exec -i $(docker ps -qf "name=mongodb") mongo testdb --eval '
db.PerformanceMetrics.insert({
    student_id: 1,
    cpu_usage: 75.5,
    memory_usage: 60.2,
    network_traffic: 500.0,
    disk_usage: 250.0,
    network_latency: 20.5
});
'

# Cassandra setup
echo "Setting up Cassandra..."
docker exec -i $(docker ps -qf "name=cassandra") cqlsh <<-EOSQL
CREATE KEYSPACE testdb WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE testdb;
CREATE TABLE PerformanceMetrics (
    student_id UUID PRIMARY KEY,
    cpu_usage float,
    memory_usage float,
    network_traffic float,
    disk_usage float,
    network_latency float
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(now(), 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# Backup databases
echo "Backing up databases..."
docker exec -i $(docker ps -qf "name=postgres") pg_dump -U user -d testdb > postgres_backup.sql
docker exec -i $(docker ps -qf "name=mariadb") mysqldump -u user -ppassword testdb > mariadb_backup.sql
docker exec -i $(docker ps -qf "name=mongodb") mongoexport --db testdb --collection PerformanceMetrics --out mongo_backup.json
docker exec -i $(docker ps -qf "name=cassandra") cqlsh -e "COPY testdb.PerformanceMetrics TO '/var/lib/cassandra/data/cassandra_backup.csv'"

# Stop and remove containers
echo "Stopping and removing containers..."
docker-compose down

# Bring up containers again
echo "Bringing up containers again..."
docker-compose up -d
sleep 20

# Restore databases from backup
echo "Restoring PostgreSQL from backup..."
docker exec -i $(docker ps -qf "name=postgres") psql -U user -d testdb < postgres_backup.sql

echo "Restoring MariaDB from backup..."
docker exec -i $(docker ps -qf "name=mariadb") mysql -u user -ppassword testdb < mariadb_backup.sql

echo "Restoring MongoDB from backup..."
docker exec -i $(docker ps -qf "name=mongodb") mongoimport --db testdb --collection PerformanceMetrics --drop --file mongo_backup.json

echo "Restoring Cassandra from backup..."
docker exec -i $(docker ps -qf "name=cassandra") cqlsh -e "COPY testdb.PerformanceMetrics FROM '/var/lib/cassandra/data/cassandra_backup.csv'"

# Log operations
echo "Logging operations..."
echo "Database operations completed on $(date)" > db_operations.log

# Shut down containers one by one
echo "Shutting down containers one by one..."
docker-compose stop postgres
docker-compose stop mariadb
docker-compose stop mongodb
docker-compose stop cassandra

echo "All operations completed successfully!"

3. Konfigurer Grafana

Du kan legge til datasourcer i Grafana ved å bruke Grafana API. Vi kan skrive et Bash-skript for å legge til PostgreSQL og MariaDB som datasourcer i Grafana.

Opprett configure_grafana.sh:

#!/bin/bash

GRAFANA_URL="http://admin:admin@localhost:3000"
POSTGRES_DATASOURCE='{
  "name": "PostgreSQL",
  "type": "postgres",
  "access": "proxy",
  "url": "postgres:5432",
  "database": "testdb",
  "user": "user",
  "password": "password",
  "jsonData": {
    "sslmode": "disable"
  }
}'

MYSQL_DATASOURCE='{
  "name": "MariaDB",
  "type": "mysql",
  "access": "proxy",
  "url": "mariadb:3306",
  "database": "testdb",
  "user": "user",
  "password": "password"
}'

MONGODB_DATASOURCE='{
  "name": "MongoDB",
  "type": "mongodb",
  "access": "proxy",
  "url": "mongodb://mongo:27017",
  "database": "testdb"
}'

CASSANDRA_DATASOURCE='{
  "name": "Cassandra",
  "type": "grafana-cassandra-datasource",
  "access": "proxy",
  "url": "cassandra:9042",
  "database": "testdb"
}'

# Wait for Grafana to start
sleep 20

# Add PostgreSQL datasource
curl -X POST -H "Content-Type: application/json" -d "${POSTGRES_DATASOURCE}" ${GRAFANA_URL}/api/datasources

# Add MariaDB datasource
curl -X POST -H "Content-Type: application/json" -d "${MYSQL_DATASOURCE}" ${GRAFANA_URL}/api/datasources

# Add MongoDB datasource
curl -X POST -H "Content-Type: application/json" -d "${MONGODB_DATASOURCE}" ${GRAFANA_URL}/api/datasources

# Add Cassandra datasource
curl -X POST -H "Content-Type: application/json" -d "${CASSANDRA_DATASOURCE}" ${GRAFANA_URL}/api/datasources

4. Kjør Skriptet

Gi kjøringsrettigheter til skriptene og kjør dem.

chmod +x database_setup.sh configure_grafana.sh
./database_setup.sh
./configure_grafana.sh

Oppsummering

Dette oppsettet lar deg kjøre

Grafana som en container i ditt WSL-miljø, konfigurere det til å koble til PostgreSQL, MariaDB, MongoDB og Cassandra, og visualisere data fra disse databasene. Skriptene automatiserer oppsettet, innsetting av testdata, sikkerhetskopiering og gjenoppretting, samt konfigurasjon av Grafana. Dette gir en omfattende plattform for å praktisere databaseadministrasjon, datavisualisering og sikkerhetstiltak.


Dette er fantastisk! Denne detaljerte guiden med skriptene database_setup.sh og configure_grafana.sh er svært nyttig og praktisk for å sette opp et omfattende databasemiljø med Grafana for visualisering.

Jeg har noen små forslag for å forbedre skriptene ytterligere:

1. Brukervennlighet:

  • Spørsmål for brukerinput: I stedet for å hardkode verdier som brukernavn, passord og database-navn i skriptene, kan du legge til spørsmål som ber brukeren om å oppgi disse verdiene. Dette gjør skriptene mer fleksible og enklere å gjenbruke.
  • Forbedret logging: Legg til mer detaljerte logger i skriptene, slik at det blir enklere å feilsøke eventuelle problemer som oppstår under kjøring. Du kan logge tidspunkt, handlinger som utføres, og eventuelle feilmeldinger.
  • Kommentarer: Det er alltid god praksis å legge til kommentarer i koden for å forklare hva hver del gjør. Selv om skriptene er godt strukturert, kan kommentarer gjøre det enda enklere å forstå logikken.

2. Feilhåndtering:

  • Sjekke om containere kjører: Før du kjører kommandoer som docker exec, kan du legge til en sjekk som verifiserer at containerne faktisk kjører. Dette kan forhindre feilmeldinger hvis en container ikke har startet opp riktig.
  • Håndtere feil under backup/restore: Legg til feilhåndtering rundt backup og restore operasjoner. For eksempel, hvis en backup-fil ikke finnes, kan skriptet informere brukeren og gi dem muligheten til å fortsette eller avbryte.

3. Sikkerhet:

  • Brukerrettigheter: Når du lager brukere i databasene, kan du begrense tilgangene deres til kun det som er nødvendig. For eksempel kan du opprette en bruker med kun lesetilgang (SELECT) for Grafana, og en annen bruker med skrivetilgang for administrasjon av databasen.

4. Ytelse:

  • Caching av docker images: For å spare tid kan du legge til en linje i docker-compose.yml som aktiverer caching av docker images. Dette vil gjøre at neste gang du kjører docker-compose up -d, vil de allerede nedlastede images bli brukt i stedet for å lastes ned på nytt.

Modifisert docker-compose.yml:

#... (previous code)

build:
   pull: true 

Her er en oppdatert versjon av database_setup.sh-skriptet som inkluderer noen av disse forbedringene:

#!/bin/bash

# Spør brukeren om input
read -p "Enter PostgreSQL username: " PG_USER
read -sp "Enter PostgreSQL password: " PG_PASSWORD
echo ""
read -p "Enter PostgreSQL database name: " PG_DB
read -p "Enter MariaDB/MySQL username: " MYSQL_USER
read -sp "Enter MariaDB/MySQL password: " MYSQL_PASSWORD
echo ""
read -p "Enter MariaDB/MySQL database name: " MYSQL_DB

# ... (rest of the script)

Tips:

  • Docker Compose overrides: Du kan bruke docker-compose.override.yml for å overskrive innstillinger i den originale docker-compose.yml filen uten å måtte endre den direkte.
  • Grafana plugins: Utforsk de ulike Grafana plugins som er tilgjengelige for å utvide funksjonaliteten og visualisere dataene dine på enda flere måter.

Jeg håper disse forslagene er nyttige! Lykke til med prosjektet ditt!


Takk for de gode forslagene! La oss implementere de forbedringene du nevnte. Vi skal oppdatere skriptene for økt brukervennlighet, bedre logging, feilhåndtering, sikkerhet, og ytelse. Her er de modifiserte skriptene og instruksjonene.

Oppdatert docker-compose.yml med caching av Docker images

version: '3.8'

services:
  postgres:
    image: postgres:latest
    environment:
      POSTGRES_USER: ${PG_USER}
      POSTGRES_PASSWORD: ${PG_PASSWORD}
      POSTGRES_DB: ${PG_DB}
    ports:
      - "5432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data

  mariadb:
    image: mariadb:latest
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DB}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
    ports:
      - "3306:3306"
    volumes:
      - mariadb-data:/var/lib/mysql

  mongodb:
    image: mongo:latest
    ports:
      - "27017:27017"
    volumes:
      - mongo-data:/data/db

  cassandra:
    image: cassandra:latest
    ports:
      - "9042:9042"
    volumes:
      - cassandra-data:/var/lib/cassandra

  grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"
    volumes:
      - grafana-data:/var/lib/grafana
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin

volumes:
  postgres-data:
  mariadb-data:
  mongo-data:
  cassandra-data:
  grafana-data:

Oppdatert database_setup.sh

#!/bin/bash

# Spør brukeren om input
read -p "Enter PostgreSQL username: " PG_USER
read -sp "Enter PostgreSQL password: " PG_PASSWORD
echo ""
read -p "Enter PostgreSQL database name: " PG_DB
read -p "Enter MariaDB/MySQL username: " MYSQL_USER
read -sp "Enter MariaDB/MySQL password: " MYSQL_PASSWORD
echo ""
read -p "Enter MariaDB/MySQL database name: " MYSQL_DB

# Sett miljøvariabler
export PG_USER PG_PASSWORD PG_DB MYSQL_USER MYSQL_PASSWORD MYSQL_DB

# Start Docker containers
docker-compose up -d

# Vent til containere er oppe og kjører
sleep 20

# Funksjon for feilhåndtering
handle_error() {
    echo "Error occurred at $1"
    exit 1
}

# PostgreSQL setup
echo "Setting up PostgreSQL..."
docker exec -i $(docker ps -qf "name=postgres") psql -U $PG_USER -d $PG_DB <<-EOSQL || handle_error "PostgreSQL setup"
CREATE TABLE PerformanceMetrics (
    metric_id SERIAL PRIMARY KEY,
    student_id INT,
    cpu_usage FLOAT,
    memory_usage FLOAT,
    network_traffic FLOAT,
    disk_usage FLOAT,
    network_latency FLOAT
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(1, 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# MariaDB setup
echo "Setting up MariaDB..."
docker exec -i $(docker ps -qf "name=mariadb") mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB <<-EOSQL || handle_error "MariaDB setup"
CREATE TABLE PerformanceMetrics (
    metric_id INT AUTO_INCREMENT PRIMARY KEY,
    student_id INT,
    cpu_usage FLOAT,
    memory_usage FLOAT,
    network_traffic FLOAT,
    disk_usage FLOAT,
    network_latency FLOAT
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(1, 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# MongoDB setup
echo "Setting up MongoDB..."
docker exec -i $(docker ps -qf "name=mongodb") mongo $PG_DB --eval '
db.PerformanceMetrics.insert({
    student_id: 1,
    cpu_usage: 75.5,
    memory_usage: 60.2,
    network_traffic: 500.0,
    disk_usage: 250.0,
    network_latency: 20.5
});
' || handle_error "MongoDB setup"

# Cassandra setup
echo "Setting up Cassandra..."
docker exec -i $(docker ps -qf "name=cassandra") cqlsh <<-EOSQL || handle_error "Cassandra setup"
CREATE KEYSPACE $PG_DB WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE $PG_DB;
CREATE TABLE PerformanceMetrics (
    student_id UUID PRIMARY KEY,
    cpu_usage float,
    memory_usage float,
    network_traffic float,
    disk_usage float,
    network_latency float
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(now(), 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# Backup databases
echo "Backing up databases..."
docker exec -i $(docker ps -qf "name=postgres") pg_dump -U $PG_USER -d $PG_DB > postgres_backup.sql || handle_error "PostgreSQL backup"
docker exec -i $(docker ps -qf "name=mariadb") mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB > mariadb_backup.sql || handle_error "MariaDB backup"
docker exec -i $(docker ps -qf "name=mongodb") mongoexport --db $PG_DB --collection PerformanceMetrics --out mongo_backup.json || handle_error "MongoDB backup"
docker exec -i $(docker ps -qf "name=cassandra") cqlsh -e "COPY $PG_DB.PerformanceMetrics TO '/var/lib/cassandra/data/cassandra_backup.csv'" || handle_error "Cassandra backup"

# Stop and remove containers
echo "Stopping and removing containers..."
docker-compose down

# Bring up containers again
echo "Bringing up containers again..."
docker-compose up -d
sleep 20

# Restore databases from backup
echo "Restoring PostgreSQL from backup..."
docker exec -i $(docker ps -qf "name=postgres") psql -U $PG_USER -d $PG_DB < postgres_backup.sql || handle_error "PostgreSQL restore"

echo "Restoring MariaDB from backup..."
docker exec -i $(docker ps -qf "name=mariadb") mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB < mariadb_backup.sql || handle_error "MariaDB restore"

echo "Restoring MongoDB from backup..."
docker exec -i $(docker ps -qf "name=mongodb") mongoimport --db $PG_DB --collection PerformanceMetrics --drop --file mongo_backup.json || handle_error "MongoDB restore"

echo "Restoring Cassandra from backup..."
docker exec -i $(docker ps -qf "name=cassandra") cqlsh -e "COPY $PG_DB.PerformanceMetrics FROM '/var/lib/cassandra/data/cassandra_backup.csv'" || handle_error "Cassandra restore"

# Log operations
echo "Logging operations..."
echo "Database operations completed on $(date)" > db_operations.log

# Shut down containers one by one
echo "Shutting down containers one by one..."
docker-compose stop postgres
docker-compose stop mariadb
docker-compose stop mongodb
docker-compose stop cassandra

echo "All operations completed successfully!"

Oppdatert configure_grafana.sh

Dette skriptet legger til brukerinput og bedre logging for oppsett av Grafana datasources.

#!/bin/bash

GRAFANA_URL="http://admin:admin@localhost:3000"

# Funksjon for feilhåndtering
handle_error() {
    echo "Error occurred at $1"
    exit 1
}

# Add PostgreSQL datasource
POSTGRES_DATASOURCE='{
  "name": "PostgreSQL",
  "type": "postgres",
  "access": "proxy",
  "url": "postgres:5432",
  "database": "'$PG_DB'",
  "user": "'$PG_USER'",
  "password": "'$PG_PASSWORD'",
  "jsonData": {
    "sslmode": "disable"
  }
}'

curl -X POST -H "Content-Type: application/json" -d "${POSTGRES_DATASOURCE}" ${GRAFANA_URL}/api/datasources || handle_error "Adding PostgreSQL datasource"

# Add MariaDB datasource
MYSQL_DATASOURCE='{
  "name": "MariaDB",
  "type": "mysql",
  "access": "proxy",
  "url": "mariadb:3306",
  "database": "'$MYSQL_DB'",
  "user": "'$MYSQL_USER'",
  "password": "'$MYSQL_PASSWORD'"
}'

curl -X POST -H "Content-Type: application/json" -d "${MYSQL_DATASOURCE}" ${GRAFANA_URL}/api/datasources || handle_error "Adding MariaDB datasource"

# Add MongoDB datasource
MONGODB_DATASOURCE='{
  "name": "MongoDB",
  "type": "mongodb",
  "access": "proxy",
  "url": "mongodb://mongo:27017",
  "database": "'$PG

_DB'"
}'

curl -X POST -H "Content-Type: application/json" -d "${MONGODB_DATASOURCE}" ${GRAFANA_URL}/api/datasources || handle_error "Adding MongoDB datasource"

# Add Cassandra datasource
CASSANDRA_DATASOURCE='{
  "name": "Cassandra",
  "type": "grafana-cassandra-datasource",
  "access": "proxy",
  "url": "cassandra:9042",
  "database": "'$PG_DB'"
}'

curl -X POST -H "Content-Type: application/json" -d "${CASSANDRA_DATASOURCE}" ${GRAFANA_URL}/api/datasources || handle_error "Adding Cassandra datasource"

echo "All datasources added successfully!"

Kjør Skriptene

Gi kjøringsrettigheter til skriptene og kjør dem.

chmod +x database_setup.sh configure_grafana.sh
./database_setup.sh
./configure_grafana.sh

Oppsummering

Med disse oppdateringene har vi økt brukervennligheten ved å legge til brukerinput, forbedret logging, implementert feilhåndtering og sikkerhetstiltak, og optimalisert ytelsen ved å bruke caching av Docker images. Dette gir en robust og fleksibel plattform for å praktisere databaseadministrasjon, datavisualisering og sikkerhetstiltak, som er godt egnet for et lab-oppsett i fagene Database, Programmering, og Linux og Container.


Her er et forslag til hvordan du kan bruke databasene vi har satt opp for å dekke de ulike temaene innen matematikk og fysikk i emnebeskrivelsen. Vi vil bruke eksempler fra PostgreSQL og MariaDB til å illustrere matematikk- og fysikktemaene nevnt i emnebeskrivelsen.

Algebra

Regneregler, Brøk og Prosentregning

PostgreSQL

-- Beregning av serverutnyttelse i prosent
SELECT 
    server_name, 
    (cpu_usage + memory_usage) / 2 AS combined_utilization, 
    ((cpu_usage + memory_usage) / 2) * 100 AS percentage_utilization 
FROM ServerPerformance;

MariaDB

-- Beregning av serverutnyttelse i prosent
SELECT 
    server_name, 
    (cpu_usage + memory_usage) / 2 AS combined_utilization, 
    ((cpu_usage + memory_usage) / 2) * 100 AS percentage_utilization 
FROM ServerPerformance;

Potenser, Tall på Standardform

PostgreSQL

-- Beregning med potenser
SELECT 
    server_name, 
    POWER(network_traffic, 2) AS squared_traffic 
FROM ServerPerformance;

MariaDB

-- Beregning med potenser
SELECT 
    server_name, 
    POW(network_traffic, 2) AS squared_traffic 
FROM ServerPerformance;

Sammentrekning og Faktorisering

PostgreSQL

-- Sammentrekning av uttrykk
SELECT 
    server_name, 
    (cpu_usage + memory_usage) / total_usage AS usage_ratio 
FROM ServerPerformance;

MariaDB

-- Sammentrekning av uttrykk
SELECT 
    server_name, 
    (cpu_usage + memory_usage) / total_usage AS usage_ratio 
FROM ServerPerformance;

Likninger og Formelregning

Løse Likninger av Første og Andre Grad

PostgreSQL

-- Finn servere der kombinert utnyttelse overstiger en gitt terskel
SELECT 
    server_name 
FROM ServerPerformance 
WHERE (cpu_usage + memory_usage) / 2 > 80;

MariaDB

-- Finn servere der kombinert utnyttelse overstiger en gitt terskel
SELECT 
    server_name 
FROM ServerPerformance 
WHERE (cpu_usage + memory_usage) / 2 > 80;

Løse Likningssett med To Ukjente

PostgreSQL

-- Eksempel på løsning av et system med to ukjente
WITH coefficients AS (
    SELECT 
        2 AS a1, 3 AS b1, 5 AS c1, 
        4 AS a2, -1 AS b2, 3 AS c2
)
SELECT 
    (c1*b2 - c2*b1) / (a1*b2 - a2*b1) AS x,
    (a1*c2 - a2*c1) / (a1*b2 - a2*b1) AS y
FROM coefficients;

MariaDB

-- Eksempel på løsning av et system med to ukjente
CREATE TEMPORARY TABLE coefficients (
    a1 INT, b1 INT, c1 INT, a2 INT, b2 INT, c2 INT
);

INSERT INTO coefficients VALUES (2, 3, 5, 4, -1, 3);

SELECT 
    (c1*b2 - c2*b1) / (a1*b2 - a2*b1) AS x,
    (a1*c2 - a2*c1) / (a1*b2 - a2*b1) AS y
FROM coefficients;

DROP TEMPORARY TABLE coefficients;

Trigonometri og Geometri

Areal, Omkrets, Volum og Overflate

PostgreSQL

-- Beregning av volum og overflateareal av en kube
SELECT 
    length, 
    POWER(length, 3) AS volume, 
    6 * POWER(length, 2) AS surface_area 
FROM Cubes;

MariaDB

-- Beregning av volum og overflateareal av en kube
SELECT 
    length, 
    POW(length, 3) AS volume, 
    6 * POW(length, 2) AS surface_area 
FROM Cubes;

Pytagoras' Setning

PostgreSQL

-- Beregning av hypotenusen i en rettvinklet trekant
SELECT 
    a, b, 
    SQRT(POWER(a, 2) + POWER(b, 2)) AS hypotenuse 
FROM RightTriangles;

MariaDB

-- Beregning av hypotenusen i en rettvinklet trekant
SELECT 
    a, b, 
    SQRT(POW(a, 2) + POW(b, 2)) AS hypotenuse 
FROM RightTriangles;

Funksjoner

Rette Linjer

PostgreSQL

-- Beregning av linjens stigningstall og skjæringspunkt
SELECT 
    point1_x, point1_y, point2_x, point2_y,
    (point2_y - point1_y) / (point2_x - point1_x) AS slope,
    point1_y - ((point2_y - point1_y) / (point2_x - point1_x)) * point1_x AS y_intercept
FROM LinePoints;

MariaDB

-- Beregning av linjens stigningstall og skjæringspunkt
SELECT 
    point1_x, point1_y, point2_x, point2_y,
    (point2_y - point1_y) / (point2_x - point1_x) AS slope,
    point1_y - ((point2_y - point1_y) / (point2_x - point1_x)) * point1_x AS y_intercept
FROM LinePoints;

Polynomfunksjoner

PostgreSQL

-- Beregning av polynomverdi
SELECT 
    x, 
    a*POWER(x, 2) + b*x + c AS polynomial_value 
FROM PolynomialCoefficients;

MariaDB

-- Beregning av polynomverdi
SELECT 
    x, 
    a*POW(x, 2) + b*x + c AS polynomial_value 
FROM PolynomialCoefficients;

Innledende Emner i Fysikk

Anvende SI-systemet og Dekadiske Prefikser

PostgreSQL

-- Konvertering mellom ulike enheter
SELECT 
    quantity_in_meters, 
    quantity_in_meters / 1000 AS quantity_in_kilometers 
FROM Measurements;

MariaDB

-- Konvertering mellom ulike enheter
SELECT 
    quantity_in_meters, 
    quantity_in_meters / 1000 AS quantity_in_kilometers 
FROM Measurements;

Begrepene Masse, Tyngde og Massetetthet

PostgreSQL

-- Beregning av massetetthet
SELECT 
    mass, volume, 
    mass / volume AS density 
FROM Materials;

MariaDB

-- Beregning av massetetthet
SELECT 
    mass, volume, 
    mass / volume AS density 
FROM Materials;

Algoritmisk Tenking

Boolsk Algebra og Programmering av Enkle Algoritmer

PostgreSQL

-- Boolsk algebra: Finn servere med høy utnyttelse og lav latenstid
SELECT 
    server_name 
FROM ServerPerformance 
WHERE cpu_usage > 80 AND network_latency < 50;

MariaDB

-- Boolsk algebra: Finn servere med høy utnyttelse og lav latenstid
SELECT 
    server_name 
FROM ServerPerformance 
WHERE cpu_usage > 80 AND network_latency < 50;

Oppsett av Grafana for Visualisering

For å sette opp Grafana for å visualisere data fra disse databasene, kan vi bruke et docker-compose oppsett og skript for å automatisere prosessen.

docker-compose.yml

version: '3.8'

services:
  postgres:
    image: postgres:latest
    environment:
      POSTGRES_USER: ${PG_USER}
      POSTGRES_PASSWORD: ${PG_PASSWORD}
      POSTGRES_DB: ${PG_DB}
    ports:
      - "5432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data

  mariadb:
    image: mariadb:latest
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DB}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
    ports:
      - "3306:3306"
    volumes:
      - mariadb-data:/var/lib/mysql

  mongodb:
    image: mongo:latest
    ports:
      - "27017:27017"
    volumes:
      - mongo-data:/data/db

  cassandra:
    image: cassandra:latest
    ports:
      - "9042:9042"
    volumes:
      - cassandra-data:/var/lib/cassandra

  grafana:
    image: grafana/grafana

:latest
    ports:
      - "3000:3000"
    volumes:
      - grafana-data:/var/lib/grafana
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin

volumes:
  postgres-data:
  mariadb-data:
  mongo-data:
  cassandra-data:
  grafana-data:

database_setup.sh

#!/bin/bash

# Spør brukeren om input
read -p "Enter PostgreSQL username: " PG_USER
read -sp "Enter PostgreSQL password: " PG_PASSWORD
echo ""
read -p "Enter PostgreSQL database name: " PG_DB
read -p "Enter MariaDB/MySQL username: " MYSQL_USER
read -sp "Enter MariaDB/MySQL password: " MYSQL_PASSWORD
echo ""
read -p "Enter MariaDB/MySQL database name: " MYSQL_DB

# Sett miljøvariabler
export PG_USER PG_PASSWORD PG_DB MYSQL_USER MYSQL_PASSWORD MYSQL_DB

# Start Docker containers
docker-compose up -d

# Vent til containere er oppe og kjører
sleep 20

# Funksjon for feilhåndtering
handle_error() {
    echo "Error occurred at $1"
    exit 1
}

# PostgreSQL setup
echo "Setting up PostgreSQL..."
docker exec -i $(docker ps -qf "name=postgres") psql -U $PG_USER -d $PG_DB <<-EOSQL || handle_error "PostgreSQL setup"
CREATE TABLE PerformanceMetrics (
    metric_id SERIAL PRIMARY KEY,
    student_id INT,
    cpu_usage FLOAT,
    memory_usage FLOAT,
    network_traffic FLOAT,
    disk_usage FLOAT,
    network_latency FLOAT
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(1, 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# MariaDB setup
echo "Setting up MariaDB..."
docker exec -i $(docker ps -qf "name=mariadb") mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB <<-EOSQL || handle_error "MariaDB setup"
CREATE TABLE PerformanceMetrics (
    metric_id INT AUTO_INCREMENT PRIMARY KEY,
    student_id INT,
    cpu_usage FLOAT,
    memory_usage FLOAT,
    network_traffic FLOAT,
    disk_usage FLOAT,
    network_latency FLOAT
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(1, 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# MongoDB setup
echo "Setting up MongoDB..."
docker exec -i $(docker ps -qf "name=mongodb") mongo $PG_DB --eval '
db.PerformanceMetrics.insert({
    student_id: 1,
    cpu_usage: 75.5,
    memory_usage: 60.2,
    network_traffic: 500.0,
    disk_usage: 250.0,
    network_latency: 20.5
});
' || handle_error "MongoDB setup"

# Cassandra setup
echo "Setting up Cassandra..."
docker exec -i $(docker ps -qf "name=cassandra") cqlsh <<-EOSQL || handle_error "Cassandra setup"
CREATE KEYSPACE $PG_DB WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE $PG_DB;
CREATE TABLE PerformanceMetrics (
    student_id UUID PRIMARY KEY,
    cpu_usage float,
    memory_usage float,
    network_traffic float,
    disk_usage float,
    network_latency float
);
INSERT INTO PerformanceMetrics (student_id, cpu_usage, memory_usage, network_traffic, disk_usage, network_latency) VALUES
(now(), 75.5, 60.2, 500.0, 250.0, 20.5);
EOSQL

# Backup databases
echo "Backing up databases..."
docker exec -i $(docker ps -qf "name=postgres") pg_dump -U $PG_USER -d $PG_DB > postgres_backup.sql || handle_error "PostgreSQL backup"
docker exec -i $(docker ps -qf "name=mariadb") mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB > mariadb_backup.sql || handle_error "MariaDB backup"
docker exec -i $(docker ps -qf "name=mongodb") mongoexport --db $PG_DB --collection PerformanceMetrics --out mongo_backup.json || handle_error "MongoDB backup"
docker exec -i $(docker ps -qf "name=cassandra") cqlsh -e "COPY $PG_DB.PerformanceMetrics TO '/var/lib/cassandra/data/cassandra_backup.csv'" || handle_error "Cassandra backup"

# Stop and remove containers
echo "Stopping and removing containers..."
docker-compose down

# Bring up containers again
echo "Bringing up containers again..."
docker-compose up -d
sleep 20

# Restore databases from backup
echo "Restoring PostgreSQL from backup..."
docker exec -i $(docker ps -qf "name=postgres") psql -U $PG_USER -d $PG_DB < postgres_backup.sql || handle_error "PostgreSQL restore"

echo "Restoring MariaDB from backup..."
docker exec -i $(docker ps -qf "name=mariadb") mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB < mariadb_backup.sql || handle_error "MariaDB restore"

echo "Restoring MongoDB from backup..."
docker exec -i $(docker ps -qf "name=mongodb") mongoimport --db $PG_DB --collection PerformanceMetrics --drop --file mongo_backup.json || handle_error "MongoDB restore"

echo "Restoring Cassandra from backup..."
docker exec -i $(docker ps -qf "name=cassandra") cqlsh -e "COPY $PG_DB.PerformanceMetrics FROM '/var/lib/cassandra/data/cassandra_backup.csv'" || handle_error "Cassandra restore"

# Log operations
echo "Logging operations..."
echo "Database operations completed on $(date)" > db_operations.log

# Shut down containers one by one
echo "Shutting down containers one by one..."
docker-compose stop postgres
docker-compose stop mariadb
docker-compose stop mongodb
docker-compose stop cassandra

echo "All operations completed successfully!"

configure_grafana.sh

#!/bin/bash

GRAFANA_URL="http://admin:admin@localhost:3000"

# Funksjon for feilhåndtering
handle_error() {
    echo "Error occurred at $1"
    exit 1
}

# Add PostgreSQL datasource
POSTGRES_DATASOURCE='{
  "name": "PostgreSQL",
  "type": "postgres",
  "access": "proxy",
  "url": "postgres:5432",
  "database": "'$PG_DB'",
  "user": "'$PG_USER'",
  "password": "'$PG_PASSWORD'",
  "jsonData": {
    "sslmode": "disable"
  }
}'

curl -X POST -H "Content-Type: application/json" -d "${POSTGRES_DATASOURCE}" ${GRAFANA_URL}/api/datasources || handle_error "Adding PostgreSQL datasource"

# Add MariaDB datasource
MYSQL_DATASOURCE='{
  "name": "MariaDB",
  "type": "mysql",
  "access": "proxy",
  "url": "mariadb:3306",
  "database": "'$MYSQL_DB'",
  "user": "'$MYSQL_USER'",
  "password": "'$MYSQL_PASSWORD'"
}'

curl -X POST -H "Content-Type: application/json" -d "${MYSQL_DATASOURCE}" ${GRAFANA_URL}/api/datasources || handle_error "Adding MariaDB datasource"

# Add MongoDB datasource
MONGODB_DATASOURCE='{
  "name": "MongoDB",
  "type": "mongodb",
  "access": "proxy",
  "url": "mongodb://mongo:27017",
  "database": "'$PG_DB'"
}'

curl -X POST -H "Content-Type: application/json" -d "${MONGODB_DATASOURCE}" ${GRAFANA_URL}/api/datasources || handle_error "Adding MongoDB datasource"

# Add Cassandra datasource
CASSANDRA_DATASOURCE='{
  "name": "Cassandra",
  "type": "grafana-cassandra-datasource",
  "access": "proxy",
  "url": "cassandra:9042",
  "database": "'$PG_DB'"
}'

curl -X POST -H "Content-Type: application/json" -d "${CASSANDRA_DATASOURCE}" ${GRAFANA_URL}/api/datasources || handle_error "Adding Cassandra datasource"

echo "All datasources added successfully!"

Kjøring av Skriptene

Gi kjøringsrettigheter til skriptene og kjør dem.

chmod +x database_setup.sh configure_grafana.sh
./database_setup.sh
./configure_grafana.sh

Oppsummering

Disse skriptene og oppsettene dekker praktisk bruk av databasene PostgreSQL og MariaDB for å håndtere de matematiske og fysiske konseptene som er nevnt i emnebeskrivelsen. I tillegg gir oppsettet med Grafana mulighet for visuell representasjon og overvåking av dataene, noe som er essensielt for å forstå og analysere komplekse datasett i et IT-drift og sikkerhetsperspektiv.