Files
gmbase/app/operator/dump.go
T
2026-06-07 18:19:15 +02:00

108 lines
2.2 KiB
Go

package operator
import (
"context"
"fmt"
"time"
"mbase/pkg/descr"
"mbase/pkg/mbctl"
"go.yaml.in/yaml/v4"
)
func (oper *Operator) GetDump(ctx context.Context, accountID string, params *mbctl.GetDumpParams) (*mbctl.GetDumpResult, error) {
var err error
res := &mbctl.GetDumpResult{}
grantExists, _, err := oper.db.GetGrant(ctx, accountID, descr.GrantModifyDatabase)
if err != nil {
return res, err
}
if !grantExists {
err := fmt.Errorf("Operation not allowed for the user")
return res, err
}
oper.WaitRestoring()
oper.WaitDumping()
oper.DumpingSemUp()
defer oper.DumpingSemDown()
listAccounts, err := oper.db.CompletedListAccounts(ctx)
if err != nil {
return res, err
}
listGrants, err := oper.db.ListGrants(ctx)
if err != nil {
return res, err
}
oper.DumpingSemDown()
dump := descr.Dump{
Timestamp: time.Now().Format(time.RFC3339),
Accounts: listAccounts,
Grants: listGrants,
}
dumpBytes, err := yaml.Marshal(dump)
if err != nil {
return res, err
}
res.Dump = string(dumpBytes)
return res, err
}
func (oper *Operator) RestoreDump(ctx context.Context, accountID string, params *mbctl.RestoreDumpParams) (*mbctl.RestoreDumpResult, error) {
var err error
res := &mbctl.RestoreDumpResult{}
grantExists, _, err := oper.db.GetGrant(ctx, accountID, descr.GrantModifyDatabase)
if err != nil {
return res, err
}
if !grantExists {
err := fmt.Errorf("Operation not allowed for the user")
return res, err
}
oper.WaitDumping()
oper.WaitRestoring()
var dump descr.Dump
err = yaml.Unmarshal([]byte(params.Dump), &dump)
if err != nil {
return res, err
}
oper.RestoringSemUp()
defer oper.RestoringSemDown()
if params.DeleteAllRecords {
err = oper.db.CleanDatabase(ctx)
if err != nil {
return res, err
}
}
for _, account := range dump.Accounts {
oper.log.Infof("Insert account %s", account.Username)
err = oper.db.InsertAccount(ctx, &account)
if err != nil {
oper.log.Errorf("Insert account error: %v", err)
}
}
for _, grant := range dump.Grants {
oper.log.Infof("Insert grant %s for account %d", grant.Operation, grant.AccountID)
err = oper.db.InsertGrant(ctx, &grant)
if err != nil {
oper.log.Errorf("Insert account error: %v", err)
}
}
return res, err
}