dockerfile

main
alex 2023-08-08 17:27:07 +02:00
parent d89df2b70d
commit 63bc576bc5
10 changed files with 222 additions and 29 deletions

41
Dockerfile Normal file
View File

@ -0,0 +1,41 @@
# Stage 1: Build the Go application
FROM golang:latest AS go_builder
WORKDIR /app
COPY ./backend/main /app/main
COPY ./backend/grouptasks_lang_log_messages.json /app/
COPY ./backend/system_lang_log_messages.json /app/
COPY ./backend/public/swagger/ /app/swagger
# Assuming you build your Go binary using "go build -o main"
#RUN go build -o main
# Stage 2: Create the final image with Python 3 and the Go binary
FROM python:3
WORKDIR /app
# Copy the Go binary from the previous stage
COPY --from=go_builder /app/main /app/main
# Copy any other files you need
COPY ./backend/grouptasks_lang_log_messages.json /app/
COPY ./backend/system_lang_log_messages.json /app/
COPY ./backend/public/swagger/ /app/swagger
# Set up any Python dependencies you might need
# RUN pip install ...
CMD ["./main"]
#FROM golang:latest
#WORKDIR /app
#COPY ./backend/main /app/main
#COPY ./backend/grouptasks_lang_log_messages.json /app/
#COPY ./backend/system_lang_log_messages.json /app/
#COPY ./backend/public/swagger/ /app/swagger
#CMD ["./main"]

View File

@ -0,0 +1,5 @@
matplotlib==3.7.2
numpy==1.24.3
numpy_stl==3.0.1
Pillow==9.5.0
Pillow==10.0.0

View File

@ -1,5 +1,47 @@
import sys import sys
import random
import matplotlib.pyplot as plt
def create_avatar(size):
# Erstelle ein neues Plot-Fenster
fig, ax = plt.subplots()
fig.set_size_inches(size/100, size/100) # Größe des Fensters festlegen
# Generiere zufällige Farben für Hintergrund und Formen
bg_color = (random.random(), random.random(), random.random())
shape_color = (random.random(), random.random(), random.random())
# Setze den Hintergrund
ax.set_facecolor(bg_color)
# Zeichne zufällige Formen
num_shapes = random.randint(3, 6)
for _ in range(num_shapes):
shape_type = random.choice(['circle', 'rectangle'])
if shape_type == 'circle':
x = random.randint(0, size)
y = random.randint(0, size)
radius = random.randint(0, size // 2)
circle = plt.Circle((x, y), radius, fc=shape_color)
ax.add_patch(circle)
elif shape_type == 'rectangle':
x = random.randint(0, size)
y = random.randint(0, size)
width = random.randint(0, size // 2)
height = random.randint(0, size // 2)
rectangle = plt.Rectangle((x, y), width, height, fc=shape_color)
ax.add_patch(rectangle)
# Verstecke Achsenbeschriftungen
ax.axis("off")
# Speichere das Bild
plt.savefig("random_avatar.png", dpi=100)
plt.close()
# Beispielaufruf
create_avatar(400)
print("hello") print("hello")
sys.exit(0)

View File

@ -0,0 +1,37 @@
Brlapi==0.8.2
certifi==2020.6.20
chardet==4.0.0
chrome-gnome-shell==0.0.0
cupshelpers==1.0
dbus-python==1.2.16
distlib==0.3.6
distro==1.5.0
distro-info==1.0
filelock==3.10.7
httplib2==0.18.1
idna==2.10
louis==3.16.0
numpy==1.24.3
numpy-stl==3.0.1
Pillow==9.5.0
platformdirs==3.2.0
pycairo==1.16.2
pycups==2.0.1
pycurl==7.43.0.6
PyGObject==3.38.0
PySimpleSOAP==1.16.2
pysmbc==1.0.23
python-apt==2.2.1
python-debian==0.1.39
python-debianbts==3.1.0
python-utils==3.6.0
pyxdg==0.27
reportbug==7.10.3+deb11u1
requests==2.25.1
six==1.16.0
typing_extensions==4.6.3
unattended-upgrades==0.1
urllib3==1.26.5
vboxapi==1.0
virtualenv==20.21.0
xdg==5

BIN
main

Binary file not shown.

80
main.go
View File

@ -17,7 +17,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"janex/admin-dashboard-backend/modules/config" "janex/admin-dashboard-backend/modules/config"
"janex/admin-dashboard-backend/modules/database" "janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/grouptasks" "janex/admin-dashboard-backend/modules/grouptasks"
@ -28,6 +28,8 @@ import (
"janex/admin-dashboard-backend/routers/router" "janex/admin-dashboard-backend/routers/router"
"janex/admin-dashboard-backend/socketserver" "janex/admin-dashboard-backend/socketserver"
"os" "os"
"path/filepath"
"time"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/cors"
@ -37,12 +39,22 @@ import (
) )
func init() { func init() {
createEnvConfigFileIfotExists() fmt.Println("Server is starting...")
createEnvConfigFileIfNotExists()
config.LoadConfig() config.LoadConfig()
logger.InitLogger() logger.InitLogger()
createServerDirectoriesIfotExists() if os.Getenv("DOCKER") != "" {
fmt.Println("Waiting for mariadb docker")
// waiting for the start of mariadb docker
time.Sleep(10 * time.Second)
copySwaggerFolder()
}
createServerDirectoriesIfNotExists()
createLogLanguageFilesIfNotExist() createLogLanguageFilesIfNotExist()
utils.ValidatorInit() utils.ValidatorInit()
@ -52,6 +64,20 @@ func init() {
systempermissions.CreateMasterRoleIfNotExist() systempermissions.CreateMasterRoleIfNotExist()
} }
func copySwaggerFolder() {
// copied by docker build to /app/swagger
srcDir := "./swagger"
destDir := config.Cfg.FolderPaths.PublicStatic + "swagger/"
err := copyDir(srcDir, destDir)
if err != nil {
panic("Failed to copy swagger folder: " + err.Error())
}
log.Debug().Msgf("Copied swagger folder to %s", destDir)
}
func main() { func main() {
app := fiber.New() app := fiber.New()
@ -105,7 +131,11 @@ func main() {
app.Listen(config.Cfg.Host + ":" + config.Cfg.Port) app.Listen(config.Cfg.Host + ":" + config.Cfg.Port)
} }
func createEnvConfigFileIfotExists() { func createEnvConfigFileIfNotExists() {
if os.Getenv("DOCKER") != "" {
return
}
content := `DEBUG=false content := `DEBUG=false
COLORIZED_OUTPUT=true COLORIZED_OUTPUT=true
HOST=127.0.0.1 HOST=127.0.0.1
@ -132,7 +162,7 @@ MARIADB_PASSWORD=db_password
MARIADB_DATABASE_NAME=db_database_name` MARIADB_DATABASE_NAME=db_database_name`
if _, err := os.Stat(".env"); os.IsNotExist(err) { if _, err := os.Stat(".env"); os.IsNotExist(err) {
err := ioutil.WriteFile(".env", []byte(content), 0644) err := os.WriteFile(".env", []byte(content), 0644)
if err != nil { if err != nil {
panic("Failed to create .env file, err: " + err.Error()) panic("Failed to create .env file, err: " + err.Error())
@ -143,7 +173,7 @@ MARIADB_DATABASE_NAME=db_database_name`
} }
} }
func createServerDirectoriesIfotExists() { func createServerDirectoriesIfNotExists() {
cfg := config.Cfg.FolderPaths cfg := config.Cfg.FolderPaths
paths := []string{ paths := []string{
@ -205,3 +235,41 @@ func createLogLanguageFilesIfNotExist() {
} }
} }
} }
func copyDir(srcDir, destDir string) error {
err := os.MkdirAll(destDir, 0755)
if err != nil {
return err
}
files, err := filepath.Glob(filepath.Join(srcDir, "*"))
if err != nil {
return err
}
for _, file := range files {
destFile := filepath.Join(destDir, filepath.Base(file))
if err := copyFile(file, destFile); err != nil {
return err
}
}
return nil
}
func copyFile(srcFile, destFile string) error {
source, err := os.Open(srcFile)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(destFile)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
return err
}

View File

@ -1,6 +1,7 @@
package config package config
import ( import (
"fmt"
"os" "os"
"github.com/joho/godotenv" "github.com/joho/godotenv"
@ -36,7 +37,13 @@ type MariaDB struct {
} }
func LoadConfig() { func LoadConfig() {
// used to determine server was startet in docker or not
if os.Getenv("DOCKER") == "" {
fmt.Println("Load env from file")
godotenv.Load(".env") godotenv.Load(".env")
} else {
fmt.Println("Load env from system")
}
Cfg = Config{ Cfg = Config{
Debug: os.Getenv("DEBUG") == "true", Debug: os.Getenv("DEBUG") == "true",

View File

@ -529,7 +529,7 @@ func RunGroupTask(args RunGroupTaskArgs) {
} }
if !info.IsDir() && filepath.Ext(path) == ".py" { if !info.IsDir() && filepath.Ext(path) == ".py" {
bytesRead, err := ioutil.ReadFile(path) bytesRead, err := os.ReadFile(path)
if err != nil { if err != nil {
log.Error().Msgf("Error reading file %s", err.Error()) log.Error().Msgf("Error reading file %s", err.Error())

View File

@ -21,14 +21,6 @@ import (
var systemLanguageLogMessages []structs.LanguageLogMessages var systemLanguageLogMessages []structs.LanguageLogMessages
var grouptasksLanguageLogMessages []structs.LanguageLogMessages var grouptasksLanguageLogMessages []structs.LanguageLogMessages
const (
systemLogsRootPath = "./logs/system/"
groupTasksLogsRootPath = "./logs/grouptasks/"
systemLanguageLogPath = "./system_lang_log_messages.json"
grouptasksLanguageLogPath = "./grouptasks_lang_log_messages.json"
)
func InitLogger() { func InitLogger() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
@ -54,10 +46,10 @@ func AddGroupTasksLog(logMessage structs.LogMessage) {
func addLog(logMessage structs.LogMessage, systemLog bool) { func addLog(logMessage structs.LogMessage, systemLog bool) {
year, month, day := time.Now().Date() year, month, day := time.Now().Date()
path := systemLogsRootPath path := config.Cfg.FolderPaths.LogsSystem
if !systemLog { if !systemLog {
path = groupTasksLogsRootPath path = config.Cfg.FolderPaths.LogsGroupTasks
} }
f, err := os.OpenFile(path+strconv.Itoa(day)+"-"+strconv.Itoa(int(month))+"-"+strconv.Itoa(year)+".json", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) f, err := os.OpenFile(path+strconv.Itoa(day)+"-"+strconv.Itoa(int(month))+"-"+strconv.Itoa(year)+".json", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
@ -79,10 +71,10 @@ func addLog(logMessage structs.LogMessage, systemLog bool) {
} }
func ReadLogs(date string, systemLogs bool, language string) []structs.LogMessageResponse { func ReadLogs(date string, systemLogs bool, language string) []structs.LogMessageResponse {
path := systemLogsRootPath path := config.Cfg.FolderPaths.LogsSystem
if !systemLogs { if !systemLogs {
path = groupTasksLogsRootPath path = config.Cfg.FolderPaths.LogsGroupTasks
} }
file, err := os.Open(path + date + ".json") file, err := os.Open(path + date + ".json")
@ -159,10 +151,10 @@ func getLogLanguageMessage(languages []structs.LanguageLogMessagesLanguage, lang
} }
func GetAllLogMessagesDates(systemLogs bool) []string { func GetAllLogMessagesDates(systemLogs bool) []string {
path := systemLogsRootPath path := config.Cfg.FolderPaths.LogsSystem
if !systemLogs { if !systemLogs {
path = groupTasksLogsRootPath path = config.Cfg.FolderPaths.LogsGroupTasks
} }
files, err := ioutil.ReadDir(path) files, err := ioutil.ReadDir(path)
@ -220,13 +212,13 @@ func InitLanguageLogMessages() {
} }
func readLanguageLogMessages(systemLogs bool) { func readLanguageLogMessages(systemLogs bool) {
path := systemLanguageLogPath path := config.Cfg.LogLanguageSystem
if !systemLogs { if !systemLogs {
path = grouptasksLanguageLogPath path = config.Cfg.LogLanguageGroupTasks
} }
content, err := ioutil.ReadFile(path) content, err := os.ReadFile(path)
if err != nil { if err != nil {
panic("Could not read language log messages: " + err.Error()) panic("Could not read language log messages: " + err.Error())

View File

@ -2,6 +2,7 @@ package user
import ( import (
"fmt" "fmt"
"janex/admin-dashboard-backend/modules/config"
"janex/admin-dashboard-backend/modules/database" "janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/logger" "janex/admin-dashboard-backend/modules/logger"
"janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/structs"
@ -36,7 +37,7 @@ func UpdateAvatar(c *fiber.Ctx) error {
database.DB.First(&user) database.DB.First(&user)
if user.Avatar != "" { if user.Avatar != "" {
os.Remove("./public/avatars/" + user.Avatar) os.Remove(config.Cfg.FolderPaths.PublicStatic + "avatars/" + user.Avatar)
} }
fileName := uuid.V4() + "." + strings.Split(fileHeader.Header["Content-Type"][0], "/")[1] fileName := uuid.V4() + "." + strings.Split(fileHeader.Header["Content-Type"][0], "/")[1]
@ -62,7 +63,7 @@ func UpdateAvatar(c *fiber.Ctx) error {
}, },
}) })
return c.SaveFile(fileHeader, fmt.Sprintf("./public/avatars/%s", fileName)) return c.SaveFile(fileHeader, fmt.Sprintf("%savatars/%s", config.Cfg.FolderPaths.PublicStatic, fileName))
} }
func isAvatarFileTypeInList(contentType string) bool { func isAvatarFileTypeInList(contentType string) bool {