Skip to content

Commit dff5853

Browse files
committed
depend on log/slog instead of gokit/logex, update CLI usage idioms
1 parent 667484a commit dff5853

17 files changed

Lines changed: 146 additions & 202 deletions

cmd/ubackup/backup.go

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,18 @@ package main
33
import (
44
"context"
55
"errors"
6-
"log"
6+
"log/slog"
77
"os"
88

9-
"github.com/function61/gokit/log/logex"
109
// "github.com/function61/lambda-alertmanager/pkg/alertmanagerclient"
1110

1211
"github.com/function61/ubackup/pkg/ubbackup"
1312
"github.com/function61/ubackup/pkg/ubconfig"
1413
"github.com/function61/ubackup/pkg/ubtypes"
1514
)
1615

17-
func runBackup(ctx context.Context, logger *log.Logger) error {
18-
logl := logex.Levels(logger)
16+
func runBackup(ctx context.Context) error {
17+
logger := slog.Default()
1918

2019
// alertSubjects, err := newAlertSubjects()
2120
// if err != nil {
@@ -37,15 +36,15 @@ func runBackup(ctx context.Context, logger *log.Logger) error {
3736
// }
3837

3938
if SupportsSettingPriorities {
40-
if err := SetLowCpuPriority(); err != nil {
39+
if err := SetLowCPUPriority(); err != nil {
4140
return err
4241
}
4342
}
4443

4544
targets := []ubtypes.BackupTarget{}
4645

4746
if conf.DockerEndpoint != nil {
48-
logl.Debug.Println("starting Docker discovery")
47+
logger.Debug("starting Docker discovery")
4948

5049
containerTargets, err := dockerDiscoverBackupTargets(ctx, *conf.DockerEndpoint)
5150
if err != nil {
@@ -75,7 +74,7 @@ func runBackup(ctx context.Context, logger *log.Logger) error {
7574
); err != nil {
7675
failedBackups++
7776

78-
logl.Error.Printf("%s: %v", target.ServiceName, err)
77+
logger.Error("BackupAndStore", "serviceName", target.ServiceName, "err", err)
7978

8079
// raise an alert
8180
// if alertManagerClient != nil {
@@ -112,7 +111,7 @@ func runBackup(ctx context.Context, logger *log.Logger) error {
112111
return errors.New("some (or all) backups failed")
113112
}
114113

115-
logl.Info.Println("completed succesfully")
114+
logger.Info("completed succesfully")
116115

117116
return nil
118117
}

cmd/ubackup/commandoutputsnapshotter.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ func (c *commandOutputSnapshotter) Describe() string {
2323
}
2424

2525
func (c *commandOutputSnapshotter) CreateSnapshot(backupSink io.Writer) error {
26+
//nolint:gosec // ok
2627
command := exec.Command(c.command[0], c.command[1:]...)
2728
command.Dir = c.dir // if empty, current workdir will be used
2829
command.Stderr = os.Stderr

cmd/ubackup/dockerdiscovery.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func dockerDiscoverBackupTargets(ctx context.Context, dockerEndpoint string) ([]
3131
ezhttp.Client(dockerClient),
3232
ezhttp.RespondsJSONAllowUnknownFields(&containerMetaList))
3333
if err != nil {
34-
return nil, fmt.Errorf("Get containers: %v", err)
34+
return nil, fmt.Errorf("get containers: %v", err)
3535
}
3636

3737
// we've to inspect all containers separately for their ENV vars
@@ -70,7 +70,7 @@ func dockerDiscoverBackupTargets(ctx context.Context, dockerEndpoint string) ([]
7070

7171
targets = append(targets, ubtypes.BackupTarget{
7272
ServiceName: serviceName,
73-
TaskId: dockerShortenContainerId(container), // for shorter backup filenames
73+
TaskID: dockerShortenContainerID(container), // for shorter backup filenames
7474
Snapshotter: snapshotter,
7575
FileExtension: container.Config.Labels["ubackup.file_extension"], // ok if not set
7676
})
@@ -113,7 +113,7 @@ func createSnapshotter(
113113
dockerExecCmd := append([]string{
114114
"docker",
115115
"exec",
116-
dockerShortenContainerId(container), // for less verbose log messages
116+
dockerShortenContainerID(container), // for less verbose log messages
117117
}, backupCommandParts...)
118118

119119
return newCommandOutputSnapshotter(dockerExecCmd, "")
@@ -146,7 +146,7 @@ func inspectAllContainers(
146146
return containers, nil
147147
}
148148

149-
func dockerShortenContainerId(container udocker.Container) string {
149+
func dockerShortenContainerID(container udocker.Container) string {
150150
// Docker CLI truncates ids to this long
151151
return container.Id[0:12]
152152
}

cmd/ubackup/encryption.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"io"
55
"os"
66

7-
"github.com/function61/gokit/os/osutil"
87
"github.com/function61/ubackup/pkg/backupfile"
98
"github.com/spf13/cobra"
109
)
@@ -31,8 +30,8 @@ func decryptEntry() *cobra.Command {
3130
Use: "decrypt-and-decompress [pathToPrivateKey]",
3231
Short: "Decrypts an encrypted backup file (from stdin) with your private key",
3332
Args: cobra.ExactArgs(1),
34-
Run: func(cmd *cobra.Command, args []string) {
35-
osutil.ExitIfError(decryptAndDecompress(args[0], os.Stdin, os.Stdout))
33+
RunE: func(cmd *cobra.Command, args []string) error {
34+
return decryptAndDecompress(args[0], os.Stdin, os.Stdout)
3635
},
3736
}
3837
}
@@ -42,8 +41,8 @@ func decryptionKeyGenerateEntry() *cobra.Command {
4241
Use: "decryption-key-generate",
4342
Short: "Generate private key for backup decryption",
4443
Args: cobra.NoArgs,
45-
Run: func(cmd *cobra.Command, args []string) {
46-
osutil.ExitIfError(backupfile.DecryptionKeyGenerate(os.Stdout))
44+
RunE: func(_ *cobra.Command, _ []string) error {
45+
return backupfile.DecryptionKeyGenerate(os.Stdout)
4746
},
4847
}
4948
}
@@ -53,8 +52,8 @@ func decryptionKeyToEncryptionKeyEntry() *cobra.Command {
5352
Use: "decryption-key-to-encryption-key",
5453
Short: "Prints encryption key (= public key) of decryption key (= private key)",
5554
Args: cobra.NoArgs,
56-
Run: func(cmd *cobra.Command, args []string) {
57-
osutil.ExitIfError(backupfile.DecryptionKeyToEncryptionKey(os.Stdin, os.Stdout))
55+
RunE: func(_ *cobra.Command, _ []string) error {
56+
return backupfile.DecryptionKeyToEncryptionKey(os.Stdin, os.Stdout)
5857
},
5958
}
6059
}

cmd/ubackup/main.go

Lines changed: 18 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@ package main
33
import (
44
"context"
55
"io"
6-
"log"
6+
"log/slog"
77
"os"
88

9-
"github.com/function61/gokit/app/dynversion"
9+
"github.com/function61/gokit/app/cli"
1010
"github.com/function61/gokit/encoding/jsonfile"
11-
"github.com/function61/gokit/log/logex"
12-
"github.com/function61/gokit/os/osutil"
1311
"github.com/function61/ubackup/pkg/ubbackup"
1412
"github.com/function61/ubackup/pkg/ubconfig"
1513
"github.com/function61/ubackup/pkg/ubtypes"
@@ -18,22 +16,15 @@ import (
1816

1917
func main() {
2018
app := &cobra.Command{
21-
Use: os.Args[0],
22-
Short: "Backs up your stateful containers",
23-
Version: dynversion.Version,
19+
Short: "Backs up your stateful containers",
2420
}
2521

2622
app.AddCommand(&cobra.Command{
2723
Use: "now",
2824
Short: "Takes a backup now",
2925
Args: cobra.NoArgs,
30-
Run: func(cmd *cobra.Command, args []string) {
31-
rootLogger := logex.StandardLogger()
32-
33-
osutil.ExitIfError(runBackup(
34-
osutil.CancelOnInterruptOrTerminate(logex.Prefix("main", rootLogger)),
35-
rootLogger,
36-
))
26+
RunE: func(cmd *cobra.Command, args []string) error {
27+
return runBackup(cmd.Context())
3728
},
3829
})
3930

@@ -45,60 +36,48 @@ func main() {
4536
app.AddCommand(decryptionKeyGenerateEntry())
4637
app.AddCommand(decryptionKeyToEncryptionKeyEntry())
4738

48-
osutil.ExitIfError(app.Execute())
39+
cli.Execute(app)
4940
}
5041

5142
func manualEntry() *cobra.Command {
52-
manual := func(ctx context.Context, serviceName string, taskId string, backupStream io.Reader, logger *log.Logger) error {
43+
manual := func(ctx context.Context, serviceName string, taskId string, backupStream io.Reader, logger *slog.Logger) error {
5344
conf, err := ubconfig.ReadFromEnvOrFile()
5445
if err != nil {
5546
return err
5647
}
5748

5849
if SupportsSettingPriorities {
59-
if err := SetLowCpuPriority(); err != nil {
50+
if err := SetLowCPUPriority(); err != nil {
6051
return err
6152
}
6253
}
6354

6455
backup := ubtypes.BackupTarget{
6556
ServiceName: serviceName,
66-
TaskId: taskId,
57+
TaskID: taskId,
6758
Snapshotter: ubtypes.CustomStream(func(backupSink io.Writer) error {
6859
_, err := io.Copy(backupSink, backupStream)
6960
return err
7061
}),
7162
}
7263

73-
return ubbackup.BackupAndStore(
74-
ctx,
75-
ubtypes.BackupForTarget(backup),
76-
*conf,
77-
logger)
64+
return ubbackup.BackupAndStore(ctx, ubtypes.BackupForTarget(backup), *conf, logger)
7865
}
7966

8067
return &cobra.Command{
8168
Use: "manual-backup [serviceName] [taskId]",
8269
Short: "Compress+encrypt+upload one manual backup (from stdin)",
8370
Args: cobra.ExactArgs(2),
84-
Run: func(cmd *cobra.Command, args []string) {
85-
rootLogger := logex.StandardLogger()
86-
87-
osutil.ExitIfError(manual(
88-
osutil.CancelOnInterruptOrTerminate(rootLogger),
89-
args[0],
90-
args[1],
91-
os.Stdin,
92-
rootLogger))
71+
RunE: func(cmd *cobra.Command, args []string) error {
72+
return manual(cmd.Context(), args[0], args[1], os.Stdin, slog.Default())
9373
},
9474
}
9575
}
9676

9777
func configEntry() *cobra.Command {
9878
cmd := &cobra.Command{
99-
Use: "config",
100-
Short: "Commands related to the configuration file",
101-
Version: dynversion.Version,
79+
Use: "config",
80+
Short: "Commands related to the configuration file",
10281
}
10382

10483
cmd.AddCommand(configExampleEntry())
@@ -112,8 +91,8 @@ func configValidateEntry() *cobra.Command {
11291
Use: "validate",
11392
Short: "Validates your config file (from stdin)",
11493
Args: cobra.NoArgs,
115-
Run: func(cmd *cobra.Command, args []string) {
116-
osutil.ExitIfError(jsonfile.UnmarshalDisallowUnknownFields(os.Stdin, &ubconfig.Config{}))
94+
RunE: func(_ *cobra.Command, _ []string) error {
95+
return jsonfile.UnmarshalDisallowUnknownFields(os.Stdin, &ubconfig.Config{})
11796
},
11897
}
11998
}
@@ -126,8 +105,8 @@ func configExampleEntry() *cobra.Command {
126105
Use: "example",
127106
Short: "Shows you an example config file",
128107
Args: cobra.NoArgs,
129-
Run: func(cmd *cobra.Command, args []string) {
130-
osutil.ExitIfError(jsonfile.Marshal(os.Stdout, ubconfig.DefaultConfig(pubkeyFilePath, kitchenSink)))
108+
RunE: func(_ *cobra.Command, _ []string) error {
109+
return jsonfile.Marshal(os.Stdout, ubconfig.DefaultConfig(pubkeyFilePath, kitchenSink))
131110
},
132111
}
133112

cmd/ubackup/priority_linux.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
//go:build linux
2-
// +build linux
32

43
package main
54

@@ -9,7 +8,7 @@ import (
98

109
const SupportsSettingPriorities = true
1110

12-
func SetLowCpuPriority() error {
11+
func SetLowCPUPriority() error {
1312
// pid 0 means self
1413
return syscall.Setpriority(syscall.PRIO_PROCESS, 0, 19)
1514
}

cmd/ubackup/priority_nonlinux.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
//go:build !linux
2-
// +build !linux
32

43
package main
54

@@ -9,6 +8,6 @@ import (
98

109
const SupportsSettingPriorities = false
1110

12-
func SetLowCpuPriority() error {
11+
func SetLowCPUPriority() error {
1312
return errors.New("not implemented")
1413
}

0 commit comments

Comments
 (0)