migrate storage-users from urfave/cli to spf13/cobra

Signed-off-by: Christian Richter <c.richter@opencloud.eu>
This commit is contained in:
Christian Richter
2025-12-15 16:40:26 +01:00
committed by Florian Schade
parent e398ce304e
commit 5869f8c19c
6 changed files with 200 additions and 227 deletions
+8 -8
View File
@@ -8,19 +8,19 @@ import (
"github.com/opencloud-eu/opencloud/services/storage-users/pkg/config" "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config"
"github.com/opencloud-eu/opencloud/services/storage-users/pkg/config/parser" "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config/parser"
"github.com/opencloud-eu/opencloud/services/storage-users/pkg/logging" "github.com/opencloud-eu/opencloud/services/storage-users/pkg/logging"
"github.com/urfave/cli/v2"
"github.com/spf13/cobra"
) )
// Health is the entrypoint for the health command. // Health is the entrypoint for the health command.
func Health(cfg *config.Config) *cli.Command { func Health(cfg *config.Config) *cobra.Command {
return &cli.Command{ return &cobra.Command{
Name: "health", Use: "health",
Usage: "check health status", Short: "check health status",
Category: "info", PreRunE: func(cmd *cobra.Command, args []string) error {
Before: func(c *cli.Context) error {
return configlog.ReturnError(parser.ParseConfig(cfg)) return configlog.ReturnError(parser.ParseConfig(cfg))
}, },
Action: func(c *cli.Context) error { RunE: func(cmd *cobra.Command, args []string) error {
logger := logging.Configure(cfg.Service.Name, cfg.Log) logger := logging.Configure(cfg.Service.Name, cfg.Log)
resp, err := http.Get( resp, err := http.Get(
+10 -8
View File
@@ -5,12 +5,13 @@ import (
"github.com/opencloud-eu/opencloud/pkg/clihelper" "github.com/opencloud-eu/opencloud/pkg/clihelper"
"github.com/opencloud-eu/opencloud/services/storage-users/pkg/config" "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config"
"github.com/urfave/cli/v2"
"github.com/spf13/cobra"
) )
// GetCommands provides all commands for this service // GetCommands provides all commands for this service
func GetCommands(cfg *config.Config) cli.Commands { func GetCommands(cfg *config.Config) []*cobra.Command {
return []*cli.Command{ return []*cobra.Command{
// start this service // start this service
Server(cfg), Server(cfg),
@@ -26,11 +27,12 @@ func GetCommands(cfg *config.Config) cli.Commands {
// Execute is the entry point for the opencloud-storage-users command. // Execute is the entry point for the opencloud-storage-users command.
func Execute(cfg *config.Config) error { func Execute(cfg *config.Config) error {
app := clihelper.DefaultApp(&cli.App{ app := clihelper.DefaultAppCobra(&cobra.Command{
Name: "storage-users", Use: "storage-users",
Usage: "Provide storage for users and projects in OpenCloud", Short: "Provide storage for users and projects in OpenCloud",
Commands: GetCommands(cfg),
}) })
app.AddCommand(GetCommands(cfg)...)
app.SetArgs(os.Args[1:])
return app.RunContext(cfg.Context, os.Args) return app.ExecuteContext(cfg.Context)
} }
+9 -9
View File
@@ -18,21 +18,21 @@ import (
"github.com/opencloud-eu/opencloud/services/storage-users/pkg/server/debug" "github.com/opencloud-eu/opencloud/services/storage-users/pkg/server/debug"
"github.com/opencloud-eu/reva/v2/cmd/revad/runtime" "github.com/opencloud-eu/reva/v2/cmd/revad/runtime"
"github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool"
"github.com/urfave/cli/v2"
"github.com/spf13/cobra"
) )
// Server is the entry point for the server command. // Server is the entry point for the server command.
func Server(cfg *config.Config) *cli.Command { func Server(cfg *config.Config) *cobra.Command {
return &cli.Command{ return &cobra.Command{
Name: "server", Use: "server",
Usage: fmt.Sprintf("start the %s service without runtime (unsupervised mode)", cfg.Service.Name), Short: fmt.Sprintf("start the %s service without runtime (unsupervised mode)", cfg.Service.Name),
Category: "server", PreRunE: func(cmd *cobra.Command, args []string) error {
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg)) return configlog.ReturnFatal(parser.ParseConfig(cfg))
}, },
Action: func(c *cli.Context) error { RunE: func(cmd *cobra.Command, args []string) error {
logger := logging.Configure(cfg.Service.Name, cfg.Log) logger := logging.Configure(cfg.Service.Name, cfg.Log)
traceProvider, err := tracing.GetTraceProvider(c.Context, cfg.Commons.TracesExporter, cfg.Service.Name) traceProvider, err := tracing.GetTraceProvider(cmd.Context(), cfg.Commons.TracesExporter, cfg.Service.Name)
if err != nil { if err != nil {
return err return err
} }
+121 -122
View File
@@ -10,12 +10,6 @@ import (
"strings" "strings"
"time" "time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/mohae/deepcopy"
"github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/tw"
"github.com/opencloud-eu/opencloud/pkg/config/configlog" "github.com/opencloud-eu/opencloud/pkg/config/configlog"
zlog "github.com/opencloud-eu/opencloud/pkg/log" zlog "github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/services/storage-users/pkg/config" "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config"
@@ -25,8 +19,15 @@ import (
"github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool"
"github.com/opencloud-eu/reva/v2/pkg/storagespace" "github.com/opencloud-eu/reva/v2/pkg/storagespace"
"github.com/opencloud-eu/reva/v2/pkg/utils" "github.com/opencloud-eu/reva/v2/pkg/utils"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/mohae/deepcopy"
"github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/tw"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"github.com/urfave/cli/v2" "github.com/spf13/cobra"
) )
const ( const (
@@ -35,56 +36,37 @@ const (
KEEP_BOTH KEEP_BOTH
) )
var _optionFlagTmpl = cli.StringFlag{
Name: "option",
Value: "skip",
Aliases: []string{"o"},
Usage: "The restore option defines the behavior for a file to be restored, where the file name already already exists in the target space. Supported values are: 'skip', 'replace' and 'keep-both'.",
DefaultText: "The default value is 'skip' overwriting an existing file",
}
var _verboseFlagTmpl = cli.BoolFlag{
Name: "verbose",
Aliases: []string{"v"},
Usage: "Get more verbose output",
}
var _applyYesFlagTmpl = cli.BoolFlag{
Name: "yes",
Aliases: []string{"y"},
Usage: "Automatic yes to prompts. Assume 'yes' as answer to all prompts and run non-interactively.",
}
// TrashBin wraps trash-bin related sub-commands. // TrashBin wraps trash-bin related sub-commands.
func TrashBin(cfg *config.Config) *cli.Command { func TrashBin(cfg *config.Config) *cobra.Command {
return &cli.Command{ trashBinCmd := &cobra.Command{
Name: "trash-bin", Use: "trash-bin",
Usage: "manage trash-bin's", Short: "manage trash-bin's",
Subcommands: []*cli.Command{
PurgeExpiredResources(cfg),
listTrashBinItems(cfg),
restoreAllTrashBinItems(cfg),
restoreTrashBindItem(cfg),
},
} }
trashBinCmd.AddCommand([]*cobra.Command{
PurgeExpiredResources(cfg),
listTrashBinItems(cfg),
restoreAllTrashBinItems(cfg),
restoreTrashBinItem(cfg),
}...)
return trashBinCmd
} }
// PurgeExpiredResources cli command removes old trash-bin items. // PurgeExpiredResources cli command removes old trash-bin items.
func PurgeExpiredResources(cfg *config.Config) *cli.Command { func PurgeExpiredResources(cfg *config.Config) *cobra.Command {
return &cli.Command{ return &cobra.Command{
Name: "purge-expired", Use: "purge-expired",
Usage: "Purge expired trash-bin items", Short: "Purge expired trash-bin items",
Flags: []cli.Flag{}, PreRunE: func(cmd *cobra.Command, args []string) error {
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg)) return configlog.ReturnFatal(parser.ParseConfig(cfg))
}, },
Action: func(c *cli.Context) error { RunE: func(cmd *cobra.Command, args []string) error {
stream, err := event.NewStream(cfg) stream, err := event.NewStream(cfg)
if err != nil { if err != nil {
return err return err
} }
if err := events.Publish(c.Context, stream, event.PurgeTrashBin{ExecutionTime: time.Now()}); err != nil { if err := events.Publish(cmd.Context(), stream, event.PurgeTrashBin{ExecutionTime: time.Now()}); err != nil {
return err return err
} }
@@ -101,29 +83,24 @@ func PurgeExpiredResources(cfg *config.Config) *cli.Command {
} }
} }
func listTrashBinItems(cfg *config.Config) *cli.Command { func listTrashBinItems(cfg *config.Config) *cobra.Command {
var verboseVal bool listTrashBinItemsCmd := &cobra.Command{
verboseFlag := _verboseFlagTmpl Use: "list",
verboseFlag.Destination = &verboseVal Short: "Print a list of all trash-bin items of a space.",
return &cli.Command{ // TODO: n might need to equal 2 not sure.
Name: "list", Args: cobra.ExactArgs(1),
Usage: "Print a list of all trash-bin items of a space.", PreRunE: func(cmd *cobra.Command, args []string) error {
ArgsUsage: "['spaceID' required]",
Flags: []cli.Flag{
&verboseFlag,
},
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg)) return configlog.ReturnFatal(parser.ParseConfig(cfg))
}, },
Action: func(c *cli.Context) error { RunE: func(cmd *cobra.Command, args []string) error {
log := cliLogger(verboseVal) log := cliLogger(cmd.Flag("verbose").Changed)
var spaceID string var spaceID string
if c.NArg() > 0 { if len(args) > 0 {
spaceID = c.Args().Get(0) spaceID = args[0]
} }
if spaceID == "" { if spaceID == "" {
_ = cli.ShowSubcommandHelp(c) _ = cmd.Help()
return fmt.Errorf("spaceID is requered") return fmt.Errorf("spaceID is requiered")
} }
log.Info().Msgf("Getting trash-bin items for spaceID: '%s' ...", spaceID) log.Info().Msgf("Getting trash-bin items for spaceID: '%s' ...", spaceID)
@@ -153,42 +130,37 @@ func listTrashBinItems(cfg *config.Config) *cli.Command {
return nil return nil
}, },
} }
listTrashBinItemsCmd.Flags().BoolP(
"verbose",
"v",
false,
"Get more verbose output",
)
return listTrashBinItemsCmd
} }
func restoreAllTrashBinItems(cfg *config.Config) *cli.Command { func restoreAllTrashBinItems(cfg *config.Config) *cobra.Command {
var optionFlagVal string
var overwriteOption int var overwriteOption int
optionFlag := _optionFlagTmpl restoreAllTrashBinItemsCmd := &cobra.Command{
optionFlag.Destination = &optionFlagVal Use: "restore-all",
var verboseVal bool Short: "Restore all trash-bin items for a space.",
verboseFlag := _verboseFlagTmpl // TODO: not sure this could also be 2
verboseFlag.Destination = &verboseVal Args: cobra.ExactArgs(1),
var applyYesVal bool PreRunE: func(cmd *cobra.Command, args []string) error {
applyYesFlag := _applyYesFlagTmpl
applyYesFlag.Destination = &applyYesVal
return &cli.Command{
Name: "restore-all",
Usage: "Restore all trash-bin items for a space.",
ArgsUsage: "['spaceID' required]",
Flags: []cli.Flag{
&optionFlag,
&verboseFlag,
&applyYesFlag,
},
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg)) return configlog.ReturnFatal(parser.ParseConfig(cfg))
}, },
Action: func(c *cli.Context) error { RunE: func(cmd *cobra.Command, args []string) error {
log := cliLogger(verboseVal) log := cliLogger(cmd.Flag("verbose").Changed)
var spaceID string var spaceID string
if c.NArg() > 0 { if len(args) > 0 {
spaceID = c.Args().Get(0) spaceID = args[0]
} }
if spaceID == "" { if spaceID == "" {
_ = cli.ShowSubcommandHelp(c) _ = cmd.Help()
return cli.Exit("The spaceID is required", 1) fmt.Errorf("spaceID is requiered")
os.Exit(1)
} }
switch optionFlagVal { switch cmd.Flag("option").Value.String() {
case "skip": case "skip":
overwriteOption = SKIP overwriteOption = SKIP
case "replace": case "replace":
@@ -196,8 +168,9 @@ func restoreAllTrashBinItems(cfg *config.Config) *cli.Command {
case "keep-both": case "keep-both":
overwriteOption = KEEP_BOTH overwriteOption = KEEP_BOTH
default: default:
_ = cli.ShowSubcommandHelp(c) _ = cmd.Help()
return cli.Exit("The option flag is invalid", 1) fmt.Errorf("The option flag is invalid")
os.Exit(1)
} }
log.Info().Msgf("Restoring trash-bin items for spaceID: '%s' ...", spaceID) log.Info().Msgf("Restoring trash-bin items for spaceID: '%s' ...", spaceID)
@@ -218,7 +191,7 @@ func restoreAllTrashBinItems(cfg *config.Config) *cli.Command {
return err return err
} }
if !applyYesVal { if !cmd.Flag("yes").Changed {
for { for {
fmt.Printf("Found %d items that could be restored, continue (Y/n), show the items list (s): ", len(res.GetRecycleItems())) fmt.Printf("Found %d items that could be restored, continue (Y/n), show the items list (s): ", len(res.GetRecycleItems()))
var i string var i string
@@ -241,7 +214,7 @@ func restoreAllTrashBinItems(cfg *config.Config) *cli.Command {
} }
} }
log.Info().Msgf("Run restoring-all with option=%s", optionFlagVal) log.Info().Msgf("Run restoring-all with option=%s", cmd.Flag("option").Value.String())
for _, item := range res.GetRecycleItems() { for _, item := range res.GetRecycleItems() {
log.Info().Msgf("restoring itemID: '%s', path: '%s', type: '%s'", item.GetKey(), item.GetRef().GetPath(), itemType(item.GetType())) log.Info().Msgf("restoring itemID: '%s', path: '%s', type: '%s'", item.GetKey(), item.GetRef().GetPath(), itemType(item.GetType()))
dstRes, err := restore(ctx, client, ref, item, overwriteOption, cfg.CliMaxAttemptsRenameFile, log) dstRes, err := restore(ctx, client, ref, item, overwriteOption, cfg.CliMaxAttemptsRenameFile, log)
@@ -254,43 +227,54 @@ func restoreAllTrashBinItems(cfg *config.Config) *cli.Command {
return nil return nil
}, },
} }
restoreAllTrashBinItemsCmd.Flags().BoolP(
"verbose",
"v",
false,
"Get more verbose output",
)
restoreAllTrashBinItemsCmd.Flags().StringP(
"option",
"o",
"skip",
"The restore option defines the behavior for a file to be restored, where the file name already already exists in the target space. Supported values are: 'skip', 'replace' and 'keep-both'. The default value is 'skip' overwriting an existing file.",
)
restoreAllTrashBinItemsCmd.Flags().BoolP(
"yes",
"y",
false,
"Automatic yes to prompts. Assume 'yes' as answer to all prompts and run non-interactively.",
)
return restoreAllTrashBinItemsCmd
} }
func restoreTrashBindItem(cfg *config.Config) *cli.Command { func restoreTrashBinItem(cfg *config.Config) *cobra.Command {
var optionFlagVal string
var overwriteOption int var overwriteOption int
optionFlag := _optionFlagTmpl restoreTrashBinItemCmd := &cobra.Command{
optionFlag.Destination = &optionFlagVal Use: "restore",
var verboseVal bool Short: "Restore a trash-bin item by ID.",
verboseFlag := _verboseFlagTmpl // TODO: not sure this could also be 2
verboseFlag.Destination = &verboseVal Args: cobra.ExactArgs(1),
return &cli.Command{ PreRunE: func(cmd *cobra.Command, args []string) error {
Name: "restore",
Usage: "Restore a trash-bin item by ID.",
ArgsUsage: "['spaceID' required] ['itemID' required]",
Flags: []cli.Flag{
&optionFlag,
&verboseFlag,
},
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg)) return configlog.ReturnFatal(parser.ParseConfig(cfg))
}, },
Action: func(c *cli.Context) error { RunE: func(cmd *cobra.Command, args []string) error {
log := cliLogger(verboseVal) log := cliLogger(cmd.Flag("verbose").Changed)
var spaceID, itemID string var spaceID, itemID string
if c.NArg() > 1 { if len(args) > 1 {
spaceID = c.Args().Get(0) spaceID = args[0]
itemID = c.Args().Get(1) itemID = args[1]
} }
if spaceID == "" { if spaceID == "" {
_ = cli.ShowSubcommandHelp(c) _ = cmd.Help()
return fmt.Errorf("spaceID is requered") return fmt.Errorf("spaceID is requered")
} }
if itemID == "" { if itemID == "" {
_ = cli.ShowSubcommandHelp(c) _ = cmd.Help()
return fmt.Errorf("itemID is requered") return fmt.Errorf("itemID is requered")
} }
switch optionFlagVal { switch cmd.Flag("option").Value.String() {
case "skip": case "skip":
overwriteOption = SKIP overwriteOption = SKIP
case "replace": case "replace":
@@ -298,8 +282,9 @@ func restoreTrashBindItem(cfg *config.Config) *cli.Command {
case "keep-both": case "keep-both":
overwriteOption = KEEP_BOTH overwriteOption = KEEP_BOTH
default: default:
_ = cli.ShowSubcommandHelp(c) _ = cmd.Help()
return cli.Exit("The option flag is invalid", 1) fmt.Errorf("The option flag is invalid")
os.Exit(1)
} }
log.Info().Msgf("Restoring trash-bin item for spaceID: '%s' itemID: '%s' ...", spaceID, itemID) log.Info().Msgf("Restoring trash-bin item for spaceID: '%s' itemID: '%s' ...", spaceID, itemID)
@@ -332,7 +317,7 @@ func restoreTrashBindItem(cfg *config.Config) *cli.Command {
if !found { if !found {
return fmt.Errorf("itemID '%s' not found", itemID) return fmt.Errorf("itemID '%s' not found", itemID)
} }
log.Info().Msgf("Run restoring with option=%s", optionFlagVal) log.Info().Msgf("Run restoring with option=%s", cmd.Flag("option").Value.String())
log.Info().Msgf("restoring itemID: '%s', path: '%s', type: '%s", itemRef.GetKey(), itemRef.GetRef().GetPath(), itemType(itemRef.GetType())) log.Info().Msgf("restoring itemID: '%s', path: '%s', type: '%s", itemRef.GetKey(), itemRef.GetRef().GetPath(), itemType(itemRef.GetType()))
dstRes, err := restore(ctx, client, ref, itemRef, overwriteOption, cfg.CliMaxAttemptsRenameFile, log) dstRes, err := restore(ctx, client, ref, itemRef, overwriteOption, cfg.CliMaxAttemptsRenameFile, log)
if err != nil { if err != nil {
@@ -342,6 +327,19 @@ func restoreTrashBindItem(cfg *config.Config) *cli.Command {
return nil return nil
}, },
} }
restoreTrashBinItemCmd.Flags().BoolP(
"verbose",
"v",
false,
"Get more verbose output",
)
restoreTrashBinItemCmd.Flags().StringP(
"option",
"o",
"skip",
"The restore option defines the behavior for a file to be restored, where the file name already already exists in the target space. Supported values are: 'skip', 'replace' and 'keep-both'. The default value is 'skip' overwriting an existing file.",
)
return restoreTrashBinItemCmd
} }
func listRecycle(ctx context.Context, client gateway.GatewayAPIClient, ref provider.Reference) (*provider.ListRecycleResponse, error) { func listRecycle(ctx context.Context, client gateway.GatewayAPIClient, ref provider.Reference) (*provider.ListRecycleResponse, error) {
@@ -354,7 +352,8 @@ func listRecycle(ctx context.Context, client gateway.GatewayAPIClient, ref provi
return nil, fmt.Errorf("%s %s", _retrievingErrorMsg, res.Status.Code) return nil, fmt.Errorf("%s %s", _retrievingErrorMsg, res.Status.Code)
} }
if len(res.GetRecycleItems()) == 0 { if len(res.GetRecycleItems()) == 0 {
return res, cli.Exit("The trash-bin is empty. Nothing to restore", 0) fmt.Errorf("The trash-bin is empty. Nothing to restore")
os.Exit(0)
} }
return res, nil return res, nil
} }
+45 -72
View File
@@ -11,7 +11,7 @@ import (
"github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/tw" "github.com/olekukonko/tablewriter/tw"
"github.com/urfave/cli/v2" "github.com/spf13/cobra"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/opencloud-eu/opencloud/pkg/config/configlog" "github.com/opencloud-eu/opencloud/pkg/config/configlog"
@@ -41,64 +41,28 @@ type Session struct {
} }
// Uploads is the entry point for the uploads command // Uploads is the entry point for the uploads command
func Uploads(cfg *config.Config) *cli.Command { func Uploads(cfg *config.Config) *cobra.Command {
return &cli.Command{ uploadsCmd := &cobra.Command{
Use: "uploads",
Name: "uploads", Short: "manage unfinished uploads",
Usage: "manage unfinished uploads",
Subcommands: []*cli.Command{
ListUploadSessions(cfg),
},
} }
uploadsCmd.AddCommand([]*cobra.Command{
ListUploadSessions(cfg),
}...)
return uploadsCmd
} }
// ListUploadSessions prints a list of upload sessiens // ListUploadSessions prints a list of upload sessiens
func ListUploadSessions(cfg *config.Config) *cli.Command { func ListUploadSessions(cfg *config.Config) *cobra.Command {
return &cli.Command{ listUploadSessionsCmd := &cobra.Command{
Name: "sessions", Use: "sessions",
Usage: "Print a list of upload sessions", Short: "Print a list of upload sessions",
Flags: []cli.Flag{ PreRunE: func(cmd *cobra.Command, args []string) error {
&cli.StringFlag{
Name: "id",
DefaultText: "unset",
Usage: "filter sessions by upload session id",
},
&cli.BoolFlag{
Name: "processing",
DefaultText: "unset",
Usage: "filter sessions by processing status",
},
&cli.BoolFlag{
Name: "expired",
DefaultText: "unset",
Usage: "filter sessions by expired status",
},
&cli.BoolFlag{
Name: "has-virus",
DefaultText: "unset",
Usage: "filter sessions by virus scan result",
},
&cli.BoolFlag{
Name: "json",
Usage: "output as json",
},
&cli.BoolFlag{
Name: "restart",
Usage: "send restart event for all listed sessions. Only one of resume/restart/clean can be set.",
},
&cli.BoolFlag{
Name: "resume",
Usage: "send resume event for all listed sessions. Only one of resume/restart/clean can be set.",
},
&cli.BoolFlag{
Name: "clean",
Usage: "remove uploads for all listed sessions. Only one of resume/restart/clean can be set.",
},
},
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg)) return configlog.ReturnFatal(parser.ParseConfig(cfg))
}, },
Action: func(c *cli.Context) error { RunE: func(cmd *cobra.Command, args []string) error {
var err error var err error
f, ok := registry.NewFuncs[cfg.Driver] f, ok := registry.NewFuncs[cfg.Driver]
if !ok { if !ok {
@@ -131,7 +95,7 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
} }
var stream events.Stream var stream events.Stream
if c.Bool("restart") || c.Bool("resume") { if cmd.Flag("restart").Changed || cmd.Flag("resume").Changed {
stream, err = event.NewStream(cfg) stream, err = event.NewStream(cfg)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create event stream: %v\n", err) fmt.Fprintf(os.Stderr, "Failed to create event stream: %v\n", err)
@@ -139,8 +103,8 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
} }
} }
filter := buildFilter(c) filter := buildFilter(cmd)
uploads, err := managingFS.ListUploadSessions(c.Context, filter) uploads, err := managingFS.ListUploadSessions(cmd.Context(), filter)
if err != nil { if err != nil {
return err return err
} }
@@ -150,7 +114,7 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
raw []Session raw []Session
) )
if !c.Bool("json") { if !cmd.Flag("json").Changed {
fmt.Println(buildInfo(filter)) fmt.Println(buildInfo(filter))
table = tablewriter.NewTable(os.Stdout, tablewriter.WithHeaderAutoFormat(tw.Off)) table = tablewriter.NewTable(os.Stdout, tablewriter.WithHeaderAutoFormat(tw.Off))
@@ -175,7 +139,7 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
ScanResult: sr, ScanResult: sr,
} }
if c.Bool("json") { if cmd.Flag("json").Changed {
raw = append(raw, session) raw = append(raw, session)
} else { } else {
table.Append([]string{ table.Append([]string{
@@ -194,7 +158,7 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
} }
switch { switch {
case c.Bool("restart"): case cmd.Flag("restart").Changed:
if err := events.Publish(context.Background(), stream, events.RestartPostprocessing{ if err := events.Publish(context.Background(), stream, events.RestartPostprocessing{
UploadID: u.ID(), UploadID: u.ID(),
Timestamp: utils.TSNow(), Timestamp: utils.TSNow(),
@@ -204,7 +168,7 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
os.Exit(1) os.Exit(1)
} }
case c.Bool("resume"): case cmd.Flag("resume").Changed:
if err := events.Publish(context.Background(), stream, events.ResumePostprocessing{ if err := events.Publish(context.Background(), stream, events.ResumePostprocessing{
UploadID: u.ID(), UploadID: u.ID(),
Timestamp: utils.TSNow(), Timestamp: utils.TSNow(),
@@ -214,15 +178,15 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
os.Exit(1) os.Exit(1)
} }
case c.Bool("clean"): case cmd.Flag("clean").Changed:
if err := u.Purge(c.Context); err != nil { if err := u.Purge(cmd.Context()); err != nil {
fmt.Fprintf(os.Stderr, "Failed to clean upload session '%s'\n", u.ID()) fmt.Fprintf(os.Stderr, "Failed to clean upload session '%s'\n", u.ID())
} }
} }
} }
if !c.Bool("json") { if !cmd.Flag("json").Changed {
table.Render() table.Render()
return nil return nil
} }
@@ -236,24 +200,33 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
return nil return nil
}, },
} }
listUploadSessionsCmd.Flags().String("id", "unset", "filter sessions by upload session id")
listUploadSessionsCmd.Flags().Bool("processing", false, "filter sessions by processing status")
listUploadSessionsCmd.Flags().Bool("expired", false, "filter sessions by expired status")
listUploadSessionsCmd.Flags().Bool("has-virus", false, "filter sessions by virus scan result")
listUploadSessionsCmd.Flags().Bool("json", false, "output as json")
listUploadSessionsCmd.Flags().Bool("restart", false, "send restart event for all listed sessions. Only one of resume/restart/clean can be set.")
listUploadSessionsCmd.Flags().Bool("resume", false, "send resume event for all listed sessions. Only one of resume/restart/clean can be set.")
listUploadSessionsCmd.Flags().Bool("clean", false, "remove uploads for all listed sessions. Only one of resume/restart/clean can be set.")
return listUploadSessionsCmd
} }
func buildFilter(c *cli.Context) storage.UploadSessionFilter { func buildFilter(cmd *cobra.Command) storage.UploadSessionFilter {
filter := storage.UploadSessionFilter{} filter := storage.UploadSessionFilter{}
if c.IsSet("processing") { if cmd.Flag("processing").Changed {
processingValue := c.Bool("processing") processingValue := cmd.Flag("processing").Changed
filter.Processing = &processingValue filter.Processing = &processingValue
} }
if c.IsSet("expired") { if cmd.Flag("expired").Changed {
expiredValue := c.Bool("expired") expiredValue := cmd.Flag("expired").Changed
filter.Expired = &expiredValue filter.Expired = &expiredValue
} }
if c.IsSet("has-virus") { if cmd.Flag("has-virus").Changed {
infectedValue := c.Bool("has-virus") infectedValue := cmd.Flag("has-virus").Changed
filter.HasVirus = &infectedValue filter.HasVirus = &infectedValue
} }
if c.IsSet("id") { if cmd.Flag("id").Changed {
idValue := c.String("id") idValue := cmd.Flag("id").Value.String()
filter.ID = &idValue filter.ID = &idValue
} }
return filter return filter
@@ -6,20 +6,19 @@ import (
"github.com/opencloud-eu/opencloud/pkg/registry" "github.com/opencloud-eu/opencloud/pkg/registry"
"github.com/opencloud-eu/opencloud/pkg/version" "github.com/opencloud-eu/opencloud/pkg/version"
"github.com/opencloud-eu/opencloud/services/storage-users/pkg/config"
"github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/tw" "github.com/olekukonko/tablewriter/tw"
"github.com/opencloud-eu/opencloud/services/storage-users/pkg/config" "github.com/spf13/cobra"
"github.com/urfave/cli/v2"
) )
// Version prints the service versions of all running instances. // Version prints the service versions of all running instances.
func Version(cfg *config.Config) *cli.Command { func Version(cfg *config.Config) *cobra.Command {
return &cli.Command{ return &cobra.Command{
Name: "version", Use: "version",
Usage: "print the version of this binary and the running service instances", Short: "print the version of this binary and the running service instances",
Category: "info", RunE: func(cmd *cobra.Command, args []string) error {
Action: func(c *cli.Context) error {
fmt.Println("Version: " + version.GetString()) fmt.Println("Version: " + version.GetString())
fmt.Printf("Compiled: %s\n", version.Compiled()) fmt.Printf("Compiled: %s\n", version.Compiled())
fmt.Println("") fmt.Println("")