Skip to content

Commit

Permalink
Add database connection and migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
bkuen committed Dec 26, 2023
1 parent fe94b99 commit 4ebdf01
Show file tree
Hide file tree
Showing 12 changed files with 287 additions and 13 deletions.
9 changes: 9 additions & 0 deletions Taskfile.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
version: '3'

env:
GOOSE_DRIVER: mysql
GOOSE_DBSTRING: "root:bwizard@/bwizard"

tasks:
setup:
cmds:
- go install github.com/deepmap/oapi-codegen/v2/cmd/oapi-codegen@latest
- go install github.com/pressly/goose/v3/cmd/goose@latest
migrations-create:
cmd: goose -dir ./migrations create {{.CLI_ARGS}} sql
migrations-migrate:
cmd: goose -dir ./migrations up
gen-http:
cmds:
- oapi-codegen -package wizard -generate types,server ./api/openapi/wizard/wizard.yml > ./api/openapi/wizard/wizard.gen.go
27 changes: 25 additions & 2 deletions cmd/bwizard/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
package main

import "bwizard/internal/pkg/wizardapi"
import (
"bwizard/internal/pkg/wizard/application"
"bwizard/internal/pkg/wizard/infrastructure/mysql"
"bwizard/internal/pkg/wizardapi"
"github.com/rs/zerolog"
"os"
"time"
)

func main() {
wizardapi.StartAPIServer()
logger := zerolog.New(
zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339},
).Level(zerolog.TraceLevel).
With().
Timestamp().
Caller().
Logger()

db, err := mysql.Connect(&logger)
if err != nil {
logger.Error().Msg(err.Error())
os.Exit(1)
}

app := application.NewApplication(db)

wizardapi.StartAPIServer(app)
}
24 changes: 19 additions & 5 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version: '3.8'
version: '3.9'

volumes:
db_data:
Expand All @@ -10,19 +10,33 @@ services:
db:
image: mariadb
environment:
MYSQL_ROOT_PASSWORD: bwizard
MYSQL_DATABASE: bwizard
MYSQL_USER: bwizard
MYSQL_PASSWORD: bwizard
MARIADB_ROOT_PASSWORD: bwizard
MARIADB_DATABASE: bwizard
MARIADB_USER: bwizard
MARIADB_PASSWORD: bwizard
healthcheck:
test: [ "CMD", "mariadb-admin" ,"ping", "-u", "root", "-pbwizard", "-h", "localhost" ]
timeout: 20s
retries: 10
ports:
- 3306:3306
volumes:
- db_data:/var/lib/mysql
networks:
- bwizard
wizard:
depends_on:
db:
condition: service_healthy
build:
context: .
# Correct the path to your Dockerfile
dockerfile: Dockerfile
environment:
DB_USER: bwizard
DB_PASS: bwizard
DB_HOST: db
DB_DATABASE: bwizard
ports:
- 8080:3000
- 8099:8099
Expand Down
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ go 1.21

require (
github.com/doug-martin/goqu/v9 v9.19.0
github.com/go-sql-driver/mysql v1.6.0
github.com/google/uuid v1.4.0
github.com/labstack/echo/v4 v4.11.4
github.com/oapi-codegen/runtime v1.1.0
github.com/rs/zerolog v1.31.0
golang.org/x/crypto v0.17.0
)

require (
Expand All @@ -18,7 +21,6 @@ require (
github.com/stretchr/objx v0.5.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
golang.org/x/crypto v0.17.0 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/text v0.14.0 // indirect
Expand Down
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMz
github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ=
github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk=
github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand All @@ -12,6 +13,7 @@ github.com/doug-martin/goqu/v9 v9.19.0 h1:PD7t1X3tRcUiSdc5TEyOFKujZA5gs3VSA7wxSv
github.com/doug-martin/goqu/v9 v9.19.0/go.mod h1:nf0Wc2/hV3gYK9LiyqIrzBEVGlI8qW3GuDCEobC4wBQ=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
Expand All @@ -27,13 +29,18 @@ github.com/lib/pq v1.10.1/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.7/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/oapi-codegen/runtime v1.1.0 h1:rJpoNUawn5XTvekgfkvSZr0RqEnoYpFkyvrzfWeFKWM=
github.com/oapi-codegen/runtime v1.1.0/go.mod h1:BeSfBkWWWnAnGdyS+S/GnlbmHKzf8/hwkvelJZDeKA8=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A=
github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
Expand Down Expand Up @@ -61,8 +68,11 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
Expand Down
58 changes: 58 additions & 0 deletions internal/pkg/wizard/application/application.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package application

import (
deviceSvcImpl "bwizard/internal/pkg/wizard/application/svc/device"
"bwizard/internal/pkg/wizard/domain/entity/device"
deviceRepo "bwizard/internal/pkg/wizard/domain/repo/device"
deviceSvc "bwizard/internal/pkg/wizard/domain/svc/device"
deviceValue "bwizard/internal/pkg/wizard/domain/valueobject/device"
deviceRepoImpl "bwizard/internal/pkg/wizard/infrastructure/mysql/repo/device"
"database/sql"
)

type Application interface {
// SetupDevice setups a new device
SetupDevice(ips []deviceValue.IPAddress, kind deviceValue.Kind, name *string) (*device.Device, error)
}

type Impl struct {
deviceRepo deviceRepo.Repository
deviceInspectionSvc deviceSvc.InspectionService
}

var _ Application = &Impl{}

// NewApplication returns a new application
func NewApplication(db *sql.DB) *Impl {
deviceRepository := deviceRepoImpl.NewRepository(db)
deviceInspectionSvc := deviceSvcImpl.NewInspectionSvc()

return &Impl{
deviceRepo: deviceRepository,
deviceInspectionSvc: deviceInspectionSvc,
}
}

// SetupDevice setups a new device
func (i *Impl) SetupDevice(ips []deviceValue.IPAddress, kind deviceValue.Kind, name *string) (*device.Device, error) {
inspection, err := i.deviceInspectionSvc.Inspect(ips)
if err != nil {
return nil, err
}

if inspection == nil {
// TODO: Throw some kind of error if inspection failed
}

if name == nil {
name = &inspection.Hostname
}

deviceEntity := device.NewBuilder().
Name(*name).
Kind(kind).
IPs(ips).
Build()

return deviceEntity, nil
}
4 changes: 4 additions & 0 deletions internal/pkg/wizard/application/svc/device/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ type InspectionSvcImpl struct {

var _ deviceSvc.InspectionService = &InspectionSvcImpl{}

func NewInspectionSvc() *InspectionSvcImpl {
return &InspectionSvcImpl{}
}

// Inspect gains information from a backup device such like the operating system or the agent
func (i *InspectionSvcImpl) Inspect(ips []deviceValue.IPAddress) (*deviceValue.Inspection, error) {
credentials := ssh.Credentials{
Expand Down
94 changes: 94 additions & 0 deletions internal/pkg/wizard/domain/entity/device/builder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package device

import (
"bwizard/internal/pkg/wizard/domain/valueobject/device"
"github.com/google/uuid"
"time"
)

type Builder struct {
*Device
}

func NewBuilder() *Builder {
return &Builder{}
}

func (b *Builder) ID(v uuid.UUID) *Builder {
b.Device.ID = v

return b
}

func (b *Builder) Name(v string) *Builder {
b.Device.Name = v

return b
}

func (b *Builder) Kind(v device.Kind) *Builder {
b.Device.Kind = v

return b
}

func (b *Builder) Protection(v device.ProtectionStatus) *Builder {
b.Device.Protection = v

return b
}

func (b *Builder) LastBackup(v *time.Time) *Builder {
b.Device.LastBackup = v

return b
}

func (b *Builder) IPs(v []device.IPAddress) *Builder {
b.Device.IPs = v

return b
}

func (b *Builder) Agent(v string) *Builder {
b.Device.Agent = v

return b
}

func (b *Builder) CreatedAt(v time.Time) *Builder {
b.Device.CreatedAt = v

return b
}

func (b *Builder) UpdatedAt(v time.Time) *Builder {
b.Device.UpdatedAt = v

return b
}

func (b *Builder) Build() *Device {
CreatedAt := b.Device.CreatedAt
UpdatedAt := b.Device.UpdatedAt

if CreatedAt.IsZero() {
b.Device.CreatedAt = time.Now()
}

if UpdatedAt.IsZero() {
b.Device.UpdatedAt = time.Now()
}

return &Device{
ID: b.Device.ID,
Name: b.Device.Name,
Kind: b.Device.Kind,
Protection: b.Device.Protection,
LastBackup: b.Device.LastBackup,
IPs: b.Device.IPs,
Agent: b.Device.Agent,
CreatedAt: b.Device.CreatedAt,
UpdatedAt: b.Device.UpdatedAt,
}
}
35 changes: 35 additions & 0 deletions internal/pkg/wizard/infrastructure/mysql/database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package mysql

import (
"database/sql"
"github.com/go-sql-driver/mysql"
"github.com/rs/zerolog"
"os"
)

func Connect(logger *zerolog.Logger) (*sql.DB, error) {
logger.Info().Msg("try to connect to database...")

cfg := mysql.Config{
User: os.Getenv("DB_USER"),
Passwd: os.Getenv("DB_PASS"),
Net: "tcp",
Addr: os.Getenv("DB_HOST"),
DBName: os.Getenv("DB_DATABASE"),
AllowNativePasswords: true,
}

db, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return nil, err
}

pingErr := db.Ping()
if pingErr != nil {
return nil, pingErr
}

logger.Info().Msg("successfully connected to database")

return db, nil
}
5 changes: 3 additions & 2 deletions internal/pkg/wizardapi/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package wizardapi

import (
api "bwizard/api/openapi/wizard"
"bwizard/internal/pkg/wizard/application"
"flag"
"github.com/labstack/echo/v4"
echoMiddleware "github.com/labstack/echo/v4/middleware"
Expand All @@ -12,11 +13,11 @@ const (
DefaultPort = "8099"
)

func StartAPIServer() {
func StartAPIServer(app application.Application) {
port := flag.String("port", DefaultPort, "Default port to start the api and ui on")
flag.Parse()

handler := NewHandler()
handler := NewHandler(app)

e := echo.New()
e.Use(echoMiddleware.Logger())
Expand Down
Loading

0 comments on commit 4ebdf01

Please sign in to comment.