Skip to content

Commit

Permalink
Merge pull request #60 from HilkopterBob/logging
Browse files Browse the repository at this point in the history
Logging, close #60
  • Loading branch information
HilkopterBob authored Oct 8, 2024
2 parents e756cce + c1b15af commit ea25449
Show file tree
Hide file tree
Showing 15 changed files with 243 additions and 276 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ config.yaml
config.yml
packagelock.pid
packagelock/**
logs/**
38 changes: 23 additions & 15 deletions certs/generate-certs.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"os"
"packagelock/logger"
"time"
)

Expand All @@ -17,7 +17,8 @@ func CreateSelfSignedCert(certFile, keyFile string) error {
// Generate a private key using RSA (2048-bit key size)
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return fmt.Errorf("failed to generate private key: %v", err)
logger.Logger.Warnf("failed to generate private key: %v", err)
return err
}

// Create a certificate template
Expand All @@ -26,7 +27,8 @@ func CreateSelfSignedCert(certFile, keyFile string) error {

serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return fmt.Errorf("failed to generate serial number: %v", err)
logger.Logger.Warnf("failed to generate serial number: %v", err)
return err
}

template := x509.Certificate{
Expand All @@ -44,49 +46,55 @@ func CreateSelfSignedCert(certFile, keyFile string) error {
// Generate a self-signed certificate using the RSA private key
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return fmt.Errorf("failed to create certificate: %v", err)
logger.Logger.Warnf("failed to create certificate: %v", err)
return err
}

// Save the certificate to certFile
certOut, err := os.Create(certFile)
if err != nil {
return fmt.Errorf("failed to open cert.pem for writing: %v", err)
logger.Logger.Warnf("failed to open cert.pem for writing: %v", err)
}

// INFO: If the parrent throws an err and this defer is called
// and fileOut.Close() throws an error to, the original error will be overwritten.
defer func() {
err := certOut.Close()
if err != nil {
panic(err)
deferredErr := certOut.Close()
if deferredErr != nil {
logger.Logger.Warnf("Cannot close Cert File, got: %s", deferredErr)
return
}
}()

if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certDER}); err != nil {
return fmt.Errorf("failed to write certificate to cert.pem: %v", err)
logger.Logger.Warnf("failed to write certificate to cert.pem: %v", err)
return err
}

// Save the RSA private key to keyFile
keyOut, err := os.Create(keyFile)
if err != nil {
return fmt.Errorf("failed to open key.pem for writing: %v", err)
logger.Logger.Warnf("failed to open key.pem for writing: %v", err)
return err
}

// INFO: If the parrent throws an err and this defer is called
// and fileOut.Close() throws an error to, the original error will be overwritten.
defer func() {
err := keyOut.Close()
if err != nil {
panic(err)
deferredErr := keyOut.Close()
if deferredErr != nil {
logger.Logger.Warnf("Cannot close Cert File, got: %s", deferredErr)
return
}
}()

// Marshal the RSA private key
privBytes := x509.MarshalPKCS1PrivateKey(priv)
if err := pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: privBytes}); err != nil {
return fmt.Errorf("failed to write private key to key.pem: %v", err)
logger.Logger.Warnf("failed to write private key to key.pem: %v", err)
return err
}

fmt.Println("Successfully created self-signed RSA certificate and private key.")
logger.Logger.Infof("Successfully created self-signed RSA certificate and private key.\n%s \n%s", certFile, keyFile)
return nil
}
11 changes: 6 additions & 5 deletions config/conf-init.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package config

import (
"bytes"
"fmt"
"io"
"packagelock/logger"

"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
Expand Down Expand Up @@ -43,17 +43,18 @@ func StartViper(config ConfigProvider) ConfigProvider {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
CreateDefaultConfig(config)
new_config := StartViper(config)
logger.Logger.Info("No Config found, created default Config.")
return new_config
} else {
panic(fmt.Errorf("fatal error config file: %w", err))
logger.Logger.Panicf("Cannot create default config, got: %s", err)
}
}

logger.Logger.Info("Successfully Created Config Manager.")
return config
}

func CreateDefaultConfig(config ConfigProvider) {
// TODO: Add default config
yamlExample := []byte(`
general:
debug: true
Expand All @@ -75,11 +76,11 @@ network:

err := config.ReadConfig(bytes.NewBuffer(yamlExample))
if err != nil {
panic(fmt.Errorf("fatal error while reading config file: %w", err))
logger.Logger.Panicf("Incompatible Default Config! Got: %s", err)
}

err_write := config.WriteConfigAs("./config.yaml")
if err_write != nil {
panic(fmt.Errorf("fatal error while writing config file: %w", err))
logger.Logger.Panicf("Cannot write config file, got: %s", err)
}
}
16 changes: 0 additions & 16 deletions config/conf-init_test.go.ignore

This file was deleted.

143 changes: 0 additions & 143 deletions config/mockgen.go.ignore

This file was deleted.

15 changes: 6 additions & 9 deletions db/db.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package db

import (
"fmt"
"packagelock/config"
"packagelock/logger"

"github.com/surrealdb/surrealdb.go"
)
Expand All @@ -17,41 +17,38 @@ func InitDB() error {

db, err := surrealdb.New("ws://" + dbAddress + ":" + dbPort + "/rpc")
if err != nil {
errorMessage := fmt.Sprintf(` Couldn't connect to DB! Got: '%s'.
logger.Logger.Errorf(` Couldn't connect to DB! Got: '%s'.
1. Check the config for a wrong Address/Port (Currently: %s:%s)
2. Check if the DB is reachable (eg. a Ping). Check the Firewalls if there.
3. Consult the PackageLock Doc's! 🚀
Golang Trace Logs:
`, err.Error(), dbAddress, dbPort)
fmt.Println(errorMessage)
panic(err)
}

if _, err = db.Signin(map[string]interface{}{
// TODO: get user&password from Conf
"user": dbUsername,
"pass": dbPasswd,
}); err != nil {
errorMessage := fmt.Sprintf(` Couldn't connect to DB! Got: '%s'.
logger.Logger.Errorf(` Couldn't connect to DB! Got: '%s'.
1. Check the config for a wrong DB-Username/Password (Currently: %s/<read the config!>)
3. Consult the PackageLock Doc's! 🚀
Golang Trace Logs:
`, err.Error(), dbUsername)
fmt.Println(errorMessage)
panic(err)
}

if _, err = db.Use("PackageLock", "db1.0"); err != nil {
// No error handling possible, as we need to use this db
panic(err)
logger.Logger.Panicf("Couldn't Use 'PackageLock' Namespace and 'db1.0' Database. Got: %s", err)
}

DB = db

logger.Logger.Infof("Successfully Connected to DB, at: %s:%s", dbAddress, dbPort)
return nil
}

// INFO: If you use this, fix it!
// INFO: And add logging/error handling
func Select(tablename string, SliceOfType interface{}) error {
transaction, err := DB.Select(tablename)
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ require (
github.com/valyala/fasthttp v1.55.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/text v0.17.0 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
Loading

0 comments on commit ea25449

Please sign in to comment.