working commit
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"mbase/pkg/mbctl"
|
||||
)
|
||||
|
||||
func (util *Util) CreateAccount(ctx context.Context, operID int64) (*mbctl.CreateAccountResult, error) {
|
||||
var err error
|
||||
res := &mbctl.CreateAccountResult{}
|
||||
|
||||
params := &mbctl.CreateAccountParams{
|
||||
Username: util.username,
|
||||
Password: util.password,
|
||||
}
|
||||
res, err = util.lg.CreateAccount(ctx, operID, params)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (util *Util) DeleteAccount(ctx context.Context, operID int64) (*mbctl.DeleteAccountResult, error) {
|
||||
var err error
|
||||
res := &mbctl.DeleteAccountResult{}
|
||||
params := &mbctl.DeleteAccountParams{
|
||||
Username: util.username,
|
||||
AccountID: util.accountID,
|
||||
}
|
||||
res, err = util.lg.DeleteAccount(ctx, operID, params)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (util *Util) ListAccounts(ctx context.Context, operID int64) (*mbctl.ListAccountsResult, error) {
|
||||
var err error
|
||||
res := &mbctl.ListAccountsResult{}
|
||||
params := &mbctl.ListAccountsParams{}
|
||||
res, err = util.lg.ListAccounts(ctx, operID, params)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (util *Util) UpdateAccount(ctx context.Context, operID int64) (*mbctl.UpdateAccountResult, error) {
|
||||
var err error
|
||||
res := &mbctl.UpdateAccountResult{}
|
||||
params := &mbctl.UpdateAccountParams{
|
||||
Username: util.username,
|
||||
AccountID: util.accountID,
|
||||
NewUsername: util.newUsername,
|
||||
NewPassword: util.newPassword,
|
||||
}
|
||||
res, err = util.lg.UpdateAccount(ctx, operID, params)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"mbase/pkg/mbctl"
|
||||
)
|
||||
|
||||
func (util *Util) SetGrant(ctx context.Context, operID int64) (*mbctl.SetGrantResult, error) {
|
||||
var err error
|
||||
res := &mbctl.SetGrantResult{}
|
||||
params := &mbctl.SetGrantParams{
|
||||
Username: util.username,
|
||||
AccountID: util.accountID,
|
||||
Operation: util.operation,
|
||||
}
|
||||
res, err = util.lg.SetGrant(ctx, operID, params)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (util *Util) DeleteGrant(ctx context.Context, operID int64) (*mbctl.DeleteGrantResult, error) {
|
||||
var err error
|
||||
res := &mbctl.DeleteGrantResult{}
|
||||
params := &mbctl.DeleteGrantParams{
|
||||
Username: util.username,
|
||||
AccountID: util.accountID,
|
||||
Operation: util.operation,
|
||||
}
|
||||
res, err = util.lg.DeleteGrant(ctx, operID, params)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
/*
|
||||
* Copyright 2024 Oleg Borodin <borodin@unix7.org>
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"mbase/app/config"
|
||||
"mbase/app/database"
|
||||
"mbase/app/descriptor"
|
||||
"mbase/app/logic"
|
||||
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
const (
|
||||
rcFilename = ".certmanager.yaml"
|
||||
|
||||
helpCmd = "help"
|
||||
|
||||
createAccountCmd = "createAccount"
|
||||
updateAccountCmd = "updateAccount"
|
||||
deleteAccountCmd = "deleteAccount"
|
||||
listAccountsCmd = "listAccounts"
|
||||
|
||||
setGrantCmd = "setGrant"
|
||||
deleteGrantCmd = "deleteGrant"
|
||||
|
||||
initDatabaseCmd = "initDatabase"
|
||||
seedAccountCmd = "seedAccount"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var err error
|
||||
util := NewUtil()
|
||||
err = util.Build()
|
||||
if err != nil {
|
||||
fmt.Printf("Build error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
err = util.Exec()
|
||||
if err != nil {
|
||||
fmt.Printf("Exec error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
type Util struct {
|
||||
subCmd string
|
||||
cmdTimeout int64
|
||||
|
||||
conf *config.Config
|
||||
lg *logic.Logic
|
||||
db *database.Database
|
||||
state descriptor.Server
|
||||
sfile string
|
||||
|
||||
accessUsername string
|
||||
accessPassword string
|
||||
accountID int64
|
||||
username string
|
||||
password string
|
||||
disable bool
|
||||
newUsername string
|
||||
newPassword string
|
||||
operation string
|
||||
quiet bool
|
||||
}
|
||||
|
||||
func NewUtil() *Util {
|
||||
var util Util
|
||||
util.cmdTimeout = 120
|
||||
return &util
|
||||
}
|
||||
|
||||
func (util *Util) GetOpt() error {
|
||||
var err error
|
||||
|
||||
exeName := filepath.Base(os.Args[0])
|
||||
|
||||
flag.Int64Var(&util.cmdTimeout, "timeout", util.cmdTimeout, "command execution timeout")
|
||||
flag.StringVar(&util.accessUsername, "user", util.accessUsername, "access login")
|
||||
flag.StringVar(&util.accessPassword, "pass", util.accessPassword, "access password")
|
||||
flag.BoolVar(&util.quiet, "quiet", util.quiet, "don't print result")
|
||||
|
||||
help := func() {
|
||||
fmt.Println("")
|
||||
fmt.Printf("Usage: %s [option] command [command option]\n", exeName)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf(" %s, %s, %s, %s,\n",
|
||||
createAccountCmd,
|
||||
deleteAccountCmd,
|
||||
listAccountsCmd,
|
||||
updateAccountCmd)
|
||||
fmt.Printf(" %s, %s\n",
|
||||
setGrantCmd,
|
||||
deleteGrantCmd)
|
||||
fmt.Printf(" %s, %s\n",
|
||||
initDatabaseCmd,
|
||||
seedAccountCmd)
|
||||
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Global options:\n")
|
||||
flag.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flag.Usage = help
|
||||
flag.Parse()
|
||||
|
||||
args := flag.Args()
|
||||
|
||||
var subCmd string
|
||||
var subArgs []string
|
||||
if len(args) > 0 {
|
||||
subCmd = args[0]
|
||||
subArgs = args[1:]
|
||||
}
|
||||
|
||||
util.subCmd = subCmd
|
||||
|
||||
switch subCmd {
|
||||
case helpCmd:
|
||||
help()
|
||||
return errors.New("Unknown command")
|
||||
|
||||
case createAccountCmd:
|
||||
flagSet := flag.NewFlagSet(createAccountCmd, flag.ExitOnError)
|
||||
|
||||
flagSet.StringVar(&util.username, "username", util.username, "user name")
|
||||
flagSet.StringVar(&util.password, "password", util.password, "user password")
|
||||
|
||||
flagSet.Usage = func() {
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Usage: %s [global options] %s [command options]\n", exeName, subCmd)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("The command options: none\n")
|
||||
flagSet.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flagSet.Parse(subArgs)
|
||||
util.subCmd = subCmd
|
||||
|
||||
case deleteAccountCmd:
|
||||
flagSet := flag.NewFlagSet(deleteAccountCmd, flag.ExitOnError)
|
||||
|
||||
flagSet.StringVar(&util.username, "username", util.username, "user name")
|
||||
flagSet.Int64Var(&util.accountID, "accountId", util.accountID, "account ID")
|
||||
|
||||
flagSet.Usage = func() {
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Usage: %s [global options] %s [command options]\n", exeName, subCmd)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("The command options: none\n")
|
||||
flagSet.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flagSet.Parse(subArgs)
|
||||
util.subCmd = subCmd
|
||||
|
||||
case listAccountsCmd:
|
||||
flagSet := flag.NewFlagSet(listAccountsCmd, flag.ExitOnError)
|
||||
|
||||
flagSet.Usage = func() {
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Usage: %s [global options] %s [command options]\n", exeName, subCmd)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("The command options: none\n")
|
||||
flagSet.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flagSet.Parse(subArgs)
|
||||
util.subCmd = subCmd
|
||||
|
||||
case updateAccountCmd:
|
||||
flagSet := flag.NewFlagSet(updateAccountCmd, flag.ExitOnError)
|
||||
|
||||
flagSet.StringVar(&util.username, "username", util.username, "user name")
|
||||
flagSet.Int64Var(&util.accountID, "accountId", util.accountID, "account ID")
|
||||
|
||||
flagSet.StringVar(&util.newUsername, "newUsername", util.newUsername, "new user name")
|
||||
flagSet.StringVar(&util.newPassword, "newPassword", util.newPassword, "new user password")
|
||||
flagSet.BoolVar(&util.disable, "disable", util.disable, "disable account")
|
||||
|
||||
flagSet.Usage = func() {
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Usage: %s [global options] %s [command options]\n", exeName, subCmd)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("The command options: none\n")
|
||||
flagSet.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flagSet.Parse(subArgs)
|
||||
util.subCmd = subCmd
|
||||
|
||||
case setGrantCmd:
|
||||
flagSet := flag.NewFlagSet(setGrantCmd, flag.ExitOnError)
|
||||
|
||||
flagSet.StringVar(&util.username, "username", util.username, "user name")
|
||||
flagSet.Int64Var(&util.accountID, "accountId", util.accountID, "account ID")
|
||||
flagSet.StringVar(&util.operation, "operation", util.operation, "grant type")
|
||||
|
||||
flagSet.Usage = func() {
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Usage: %s [global options] %s [command options]\n", exeName, subCmd)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("The command options: none\n")
|
||||
flagSet.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flagSet.Parse(subArgs)
|
||||
util.subCmd = subCmd
|
||||
|
||||
case deleteGrantCmd:
|
||||
flagSet := flag.NewFlagSet(deleteGrantCmd, flag.ExitOnError)
|
||||
|
||||
flagSet.StringVar(&util.username, "username", util.username, "user name")
|
||||
flagSet.Int64Var(&util.accountID, "accountId", util.accountID, "account ID")
|
||||
flagSet.StringVar(&util.operation, "operation", util.operation, "grant type")
|
||||
|
||||
flagSet.Usage = func() {
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Usage: %s [global options] %s [command options]\n", exeName, subCmd)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("The command options: none\n")
|
||||
flagSet.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flagSet.Parse(subArgs)
|
||||
util.subCmd = subCmd
|
||||
|
||||
case initDatabaseCmd:
|
||||
flagSet := flag.NewFlagSet(initDatabaseCmd, flag.ExitOnError)
|
||||
|
||||
flagSet.Usage = func() {
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Usage: %s [global options] %s [command options]\n", exeName, subCmd)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("The command options: none\n")
|
||||
flagSet.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flagSet.Parse(subArgs)
|
||||
util.subCmd = subCmd
|
||||
case seedAccountCmd:
|
||||
flagSet := flag.NewFlagSet(seedAccountCmd, flag.ExitOnError)
|
||||
|
||||
flagSet.Usage = func() {
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Usage: %s [global options] %s [command options]\n", exeName, subCmd)
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("The command options: none\n")
|
||||
flagSet.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
flagSet.Parse(subArgs)
|
||||
util.subCmd = subCmd
|
||||
|
||||
default:
|
||||
help()
|
||||
return errors.New("Unknown command")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (util *Util) Build() error {
|
||||
var err error
|
||||
|
||||
util.conf = config.NewConfig()
|
||||
err = util.conf.ReadFile()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = util.conf.ReadEnv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
util.sfile = filepath.Join(util.conf.DataDir, "certmanager.yaml")
|
||||
|
||||
db, err := database.NewDatabase(util.conf.DataDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.OpenDatabase()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
util.db = db
|
||||
logicConfig := &logic.LogicConfig{
|
||||
Database: util.db,
|
||||
}
|
||||
util.lg, err = logic.NewLogic(logicConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
Command string `json:"command" yaml:"command"`
|
||||
Args []string `json:"args" yaml:"args"`
|
||||
Error bool `json:"error" yaml:"error"`
|
||||
Message string `json:"message,omitempty" yaml:"message,omitempty"`
|
||||
Result any `json:"result,omitempty" yaml:"result,omitempty"`
|
||||
}
|
||||
|
||||
func (util *Util) Exec() error {
|
||||
var err error
|
||||
err = util.GetOpt()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var timeout = time.Duration(util.cmdTimeout) * time.Second
|
||||
ctx, close := context.WithTimeout(context.Background(), timeout)
|
||||
defer close()
|
||||
|
||||
var res any
|
||||
|
||||
switch util.subCmd {
|
||||
case initDatabaseCmd:
|
||||
res, err = util.InitDatabase(ctx)
|
||||
case seedAccountCmd:
|
||||
res, err = util.SeedAccount(ctx)
|
||||
default:
|
||||
authOk, operID, localErr := util.lg.ValidateAcount(ctx, util.accessUsername, util.accessPassword)
|
||||
if err != nil {
|
||||
err = localErr
|
||||
goto exit
|
||||
}
|
||||
if !authOk {
|
||||
err = fmt.Errorf("Incorrect username or password")
|
||||
goto exit
|
||||
}
|
||||
switch util.subCmd {
|
||||
case createAccountCmd:
|
||||
res, err = util.CreateAccount(ctx, operID)
|
||||
case updateAccountCmd:
|
||||
res, err = util.UpdateAccount(ctx, operID)
|
||||
case listAccountsCmd:
|
||||
res, err = util.ListAccounts(ctx, operID)
|
||||
case deleteAccountCmd:
|
||||
res, err = util.DeleteAccount(ctx, operID)
|
||||
case setGrantCmd:
|
||||
res, err = util.SetGrant(ctx, operID)
|
||||
case deleteGrantCmd:
|
||||
res, err = util.DeleteGrant(ctx, operID)
|
||||
default:
|
||||
err = errors.New("Unknown cli command")
|
||||
}
|
||||
}
|
||||
|
||||
exit:
|
||||
var resp Response
|
||||
resp.Command = util.subCmd
|
||||
resp.Args = os.Args
|
||||
if err != nil {
|
||||
resp.Error = true
|
||||
resp.Message = fmt.Sprintf("%v", err)
|
||||
} else {
|
||||
resp.Result = res
|
||||
}
|
||||
|
||||
if !resp.Error && !util.quiet {
|
||||
respBytes, _ := yaml.Marshal(resp)
|
||||
fmt.Println(string(respBytes))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type InitDatabaseRes struct{}
|
||||
|
||||
func (util *Util) InitDatabase(ctx context.Context) (InitDatabaseRes, error) {
|
||||
res := InitDatabaseRes{}
|
||||
// Initialize database
|
||||
|
||||
// Load state
|
||||
err := util.LoadState()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if !util.state.DatabaseInitialized {
|
||||
if util.db == nil {
|
||||
err = fmt.Errorf("Nil db object")
|
||||
return res, err
|
||||
}
|
||||
err := util.db.InitDatabase()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
util.state.DatabaseInitialized = true
|
||||
err = util.SaveState()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
type SeedAccountRes struct{}
|
||||
|
||||
func (util *Util) SeedAccount(ctx context.Context) (SeedAccountRes, error) {
|
||||
// Seed accounts
|
||||
res := SeedAccountRes{}
|
||||
_, err := util.lg.SeedAccount(ctx)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (util *Util) LoadState() error {
|
||||
var err error
|
||||
_, err = os.Stat(util.sfile)
|
||||
if os.IsNotExist(err) {
|
||||
err = nil
|
||||
return err
|
||||
}
|
||||
file, err := os.Open(util.sfile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
stateBytes, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = yaml.Unmarshal(stateBytes, &util.state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (util *Util) SaveState() error {
|
||||
var err error
|
||||
|
||||
file, err := os.OpenFile(util.sfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
util.state.UpdatedAt = time.Now().Format(time.RFC3339)
|
||||
if util.state.CreatedAt == "" {
|
||||
util.state.CreatedAt = util.state.UpdatedAt
|
||||
}
|
||||
stateBytes, err := yaml.Marshal(util.state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = file.Write(stateBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
|
||||
*/
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var err error
|
||||
util := NewUtil()
|
||||
err = util.Build()
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
err = util.Exec(os.Args[1:])
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
|
||||
*/
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
func printResponse(res any, err error) {
|
||||
type Response struct {
|
||||
Error bool `json:"error" yaml:"error"`
|
||||
Message string `json:"message,omitempty" yaml:"message,omitempty"`
|
||||
Result any `json:"result,omitempty" yaml:"result,omitempty"`
|
||||
}
|
||||
resp := Response{}
|
||||
if err != nil {
|
||||
resp.Error = true
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
resp.Result = res
|
||||
}
|
||||
respBytes, _ := yaml.Marshal(resp)
|
||||
fmt.Printf("---\n%s\n", string(respBytes))
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
|
||||
*/
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"context"
|
||||
"io"
|
||||
"bytes"
|
||||
|
||||
"mbase/app/config"
|
||||
"mbase/app/database"
|
||||
"mbase/app/descriptor"
|
||||
"mbase/pkg/auxtool"
|
||||
"mbase/pkg/logger"
|
||||
|
||||
"go.yaml.in/yaml/v4"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
type Util struct {
|
||||
rootCmd *cobra.Command
|
||||
dumpDatabaseParams dumpDatabaseParams
|
||||
restoreDatabaseParams restoreDatabaseParams
|
||||
}
|
||||
|
||||
func NewUtil() *Util {
|
||||
return &Util{}
|
||||
}
|
||||
|
||||
func (util *Util) GetRooCmd() *cobra.Command {
|
||||
return util.rootCmd
|
||||
}
|
||||
|
||||
func (util *Util) Build() error {
|
||||
var err error
|
||||
execName := filepath.Base(os.Args[0])
|
||||
rootCmd := &cobra.Command{
|
||||
Use: execName,
|
||||
Short: "\nDump application database",
|
||||
SilenceUsage: true,
|
||||
}
|
||||
rootCmd.CompletionOptions.DisableDefaultCmd = true
|
||||
|
||||
var dumpDatabaseCmd = &cobra.Command{
|
||||
Use: "dump [filename|-]",
|
||||
Short: "Dump application database",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: util.DumpDatabase,
|
||||
}
|
||||
rootCmd.AddCommand(dumpDatabaseCmd)
|
||||
|
||||
var restoreDatabaseCmd = &cobra.Command{
|
||||
Use: "restore [] [filename|-]",
|
||||
Short: "Restore application database",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: util.RestoreDatabase,
|
||||
}
|
||||
restoreDatabaseCmd.Flags().BoolVarP(&util.restoreDatabaseParams.DeleteAllRecords, "clean", "C", false, "Clean all record")
|
||||
rootCmd.AddCommand(restoreDatabaseCmd)
|
||||
|
||||
util.rootCmd = rootCmd
|
||||
return err
|
||||
}
|
||||
|
||||
func (util *Util) Exec(args []string) error {
|
||||
var err error
|
||||
util.rootCmd.SetArgs(args)
|
||||
err = util.rootCmd.Execute()
|
||||
return err
|
||||
}
|
||||
|
||||
func (util *Util) DumpDatabase(cmd *cobra.Command, args []string) {
|
||||
util.dumpDatabaseParams.Filename = args[0]
|
||||
res, err := util.dumpDatabase(util.dumpDatabaseParams)
|
||||
printResponse(res, err)
|
||||
}
|
||||
|
||||
type dumpDatabaseParams struct {
|
||||
Filename string
|
||||
}
|
||||
type dumpDatabaseResult struct {}
|
||||
|
||||
func (util *Util) dumpDatabase(params dumpDatabaseParams) (dumpDatabaseResult, error) {
|
||||
var err error
|
||||
res := dumpDatabaseResult{}
|
||||
ctx := context.Background()
|
||||
|
||||
conf := config.NewConfig()
|
||||
err = conf.ReadFile()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
err = conf.ReadEnv()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
db, err := database.NewDatabase(conf.DataDir)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
err = db.OpenDatabase()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
file := os.Stdout
|
||||
if params.Filename != "-" {
|
||||
file, err = os.OpenFile(params.Filename, os.O_CREATE|os.O_WRONLY, 0640)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
defer file.Close()
|
||||
}
|
||||
listAccounts, err := db.CompletedListAccounts(ctx)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
listGrants, err := db.ListGrants(ctx)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
dump := descriptor.Dump{
|
||||
Timestamp: auxtool.TimeNow(),
|
||||
Accounts: listAccounts,
|
||||
Grants: listGrants,
|
||||
}
|
||||
dumpBytes, err := yaml.Marshal(dump)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
_, err = file.Write(dumpBytes)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
|
||||
func (util *Util) RestoreDatabase(cmd *cobra.Command, args []string) {
|
||||
util.restoreDatabaseParams.Filename = args[0]
|
||||
res, err := util.restoreDatabase(util.restoreDatabaseParams)
|
||||
printResponse(res, err)
|
||||
}
|
||||
|
||||
type restoreDatabaseParams struct {
|
||||
Filename string
|
||||
DeleteAllRecords bool
|
||||
}
|
||||
type restoreDatabaseResult struct {}
|
||||
|
||||
func (util *Util) restoreDatabase(params restoreDatabaseParams) (restoreDatabaseResult, error) {
|
||||
var err error
|
||||
res := restoreDatabaseResult{}
|
||||
ctx := context.Background()
|
||||
log := logger.NewLogger("restore")
|
||||
|
||||
conf := config.NewConfig()
|
||||
err = conf.ReadFile()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
err = conf.ReadEnv()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
db, err := database.NewDatabase(conf.DataDir)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
err = db.OpenDatabase()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
file := os.Stdin
|
||||
if params.Filename != "-" {
|
||||
file, err = os.Open(params.Filename)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
defer file.Close()
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
_, err = io.Copy(buffer, file)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
dump := descriptor.Dump{}
|
||||
err = yaml.Unmarshal(buffer.Bytes(), &dump)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if params.DeleteAllRecords {
|
||||
err = db.CleanDatabase(ctx)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
for _, account := range dump.Accounts {
|
||||
log.Infof("Insert account %s", account.Username)
|
||||
err = db.InsertAccount(ctx, &account)
|
||||
if err != nil {
|
||||
log.Errorf("Insert account error: %v", err)
|
||||
}
|
||||
}
|
||||
for _, grant := range dump.Grants {
|
||||
log.Infof("Insert grant %s for account %d", grant.Operation, grant.AccountID)
|
||||
err = db.InsertGrant(ctx, &grant)
|
||||
if err != nil {
|
||||
log.Errorf("Insert account error: %v", err)
|
||||
}
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Copyright 2022 Oleg Borodin <borodin@unix7.org>
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"mbase/app/config"
|
||||
"mbase/app/database"
|
||||
"mbase/app/descriptor"
|
||||
"mbase/pkg/logger"
|
||||
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var err error
|
||||
util := NewUtil()
|
||||
err = util.Exec()
|
||||
if err != nil {
|
||||
fmt.Printf("Exec error: %s\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
type Util struct {
|
||||
conf *config.Config
|
||||
db *database.Database
|
||||
log *logger.Logger
|
||||
|
||||
filename string
|
||||
deleteAllRecords bool
|
||||
}
|
||||
|
||||
func NewUtil() *Util {
|
||||
var util Util
|
||||
util.log = logger.NewLogger("logic")
|
||||
return &util
|
||||
}
|
||||
|
||||
func (util *Util) GetOpt() error {
|
||||
var err error
|
||||
|
||||
exeName := filepath.Base(os.Args[0])
|
||||
|
||||
help := func() {
|
||||
fmt.Println("")
|
||||
fmt.Printf("Usage: %s [option]\n", exeName)
|
||||
fmt.Printf("\n")
|
||||
flag.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
}
|
||||
|
||||
flag.Usage = help
|
||||
|
||||
flag.StringVar(&util.filename, "file", util.filename, "dump file name")
|
||||
flag.BoolVar(&util.deleteAllRecords, "deleteAllRecords", util.deleteAllRecords, "delete all existing records before restoring")
|
||||
|
||||
flag.Parse()
|
||||
return err
|
||||
}
|
||||
|
||||
func (util *Util) Exec() error {
|
||||
var err error
|
||||
err = util.GetOpt()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
const timeout = 30 * time.Second
|
||||
ctx, _ := context.WithTimeout(context.Background(), timeout)
|
||||
|
||||
err = util.RestoreRecords(ctx)
|
||||
|
||||
type ErrorDescr struct {
|
||||
Error bool `json:"error,omitempty"`
|
||||
Message string `json:"errorMessage,omitempty" yaml:"errorMessage,omitempty"`
|
||||
}
|
||||
|
||||
errDescr := ErrorDescr{}
|
||||
if err != nil {
|
||||
errDescr.Error = true
|
||||
errDescr.Message = fmt.Sprintf("%v", err)
|
||||
}
|
||||
|
||||
errBytes, _ := yaml.Marshal(errDescr)
|
||||
fmt.Printf("%s\n", string(errBytes))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (util *Util) RestoreRecords(ctx context.Context) error {
|
||||
var err error
|
||||
|
||||
util.conf = config.NewConfig()
|
||||
err = util.conf.ReadFile()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = util.conf.ReadEnv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
db, err := database.NewDatabase(util.conf.DataDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
util.db = db
|
||||
|
||||
err = util.db.OpenDatabase()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
file := os.Stdin
|
||||
if util.filename != "" {
|
||||
file, err = os.Open(util.filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
}
|
||||
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
_, err = io.Copy(buffer, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dump := descriptor.Dump{}
|
||||
|
||||
err = yaml.Unmarshal(buffer.Bytes(), &dump)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if util.deleteAllRecords {
|
||||
err = util.db.CleanDatabase(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, account := range dump.Accounts {
|
||||
util.log.Infof("Insert account %s", account.Username)
|
||||
err = util.db.InsertAccount(ctx, &account)
|
||||
if err != nil {
|
||||
util.log.Errorf("Insert account error: %v", err)
|
||||
}
|
||||
}
|
||||
for _, grant := range dump.Grants {
|
||||
util.log.Infof("Insert grant %s for account %d", grant.Operation, grant.AccountID)
|
||||
err = util.db.InsertGrant(ctx, &grant)
|
||||
if err != nil {
|
||||
util.log.Errorf("Insert account error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user