[#624] cli: Do not print help on any failure

Change usage function to `Run`(does not return
err). Log errors with `cmd.PrintErrln`. Change
all `fmt.Print*` to `cmd.Print*`.

Signed-off-by: Pavel Karpy <carpawell@nspcc.ru>
This commit is contained in:
Pavel Karpy 2021-06-21 02:02:56 +03:00 committed by Alex Vanin
parent af72412b77
commit 02ca1c4cc1
7 changed files with 479 additions and 360 deletions

View file

@ -25,48 +25,50 @@ var accountingBalanceCmd = &cobra.Command{
Use: "balance",
Short: "Get internal balance of NeoFS account",
Long: `Get internal balance of NeoFS account`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
var (
response *accounting.Decimal
oid *owner.ID
err error
ctx = context.Background()
)
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
if balanceOwner == "" {
wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
oid = owner.NewIDFromNeo3Wallet(wallet)
} else {
oid, err = ownerFromString(balanceOwner)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
}
response, err = cli.GetBalance(ctx, oid, globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
// print to stdout
prettyPrintDecimal(response)
return nil
prettyPrintDecimal(cmd, response)
},
}
@ -87,14 +89,14 @@ func init() {
accountingBalanceCmd.Flags().StringVar(&balanceOwner, "owner", "", "owner of balance account (omit to use owner from private key)")
}
func prettyPrintDecimal(decimal *accounting.Decimal) {
func prettyPrintDecimal(cmd *cobra.Command, decimal *accounting.Decimal) {
if decimal == nil {
return
}
if verbose {
fmt.Println("value:", decimal.Value())
fmt.Println("precision:", decimal.Precision())
cmd.Println("value:", decimal.Value())
cmd.Println("precision:", decimal.Precision())
} else {
// divider = 10^{precision}; v:365, p:2 => 365 / 10^2 = 3.65
divider := math.Pow(10, float64(decimal.Precision()))
@ -102,6 +104,6 @@ func prettyPrintDecimal(decimal *accounting.Decimal) {
// %0.8f\n for precision 8
format := fmt.Sprintf("%%0.%df\n", decimal.Precision())
fmt.Printf(format, float64(decimal.Value())/divider)
cmd.Printf(format, float64(decimal.Value())/divider)
}
}

View file

@ -78,48 +78,50 @@ var listContainersCmd = &cobra.Command{
Use: "list",
Short: "List all created containers",
Long: "List all created containers",
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
var (
response []*cid.ID
oid *owner.ID
err error
ctx = context.Background()
)
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
if containerOwner == "" {
wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
oid = owner.NewIDFromNeo3Wallet(wallet)
} else {
oid, err = ownerFromString(containerOwner)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
}
response, err = cli.ListContainers(ctx, oid, globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
// print to stdout
prettyPrintContainerList(response)
return nil
prettyPrintContainerList(cmd, response)
},
}
@ -128,42 +130,49 @@ var createContainerCmd = &cobra.Command{
Short: "Create new container",
Long: `Create new container and register it in the NeoFS.
It will be stored in sidechain when inner ring will accepts it.`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
placementPolicy, err := parseContainerPolicy(containerPolicy)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
attributes, err := parseAttributes(containerAttributes)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
basicACL, err := parseBasicACL(containerACL)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
nonce, err := parseNonce(containerNonce)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
tok, err := getSessionToken(sessionTokenPath)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cnr := container.New()
@ -176,28 +185,27 @@ It will be stored in sidechain when inner ring will accepts it.`,
id, err := cli.PutContainer(ctx, cnr, globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
fmt.Println("container ID:", id)
cmd.Println("container ID:", id)
if containerAwait {
fmt.Println("awaiting...")
cmd.Println("awaiting...")
for i := 0; i < awaitTimeout; i++ {
time.Sleep(1 * time.Second)
_, err := cli.GetContainer(ctx, id, globalCallOptions()...)
if err == nil {
fmt.Println("container has been persisted on sidechain")
return nil
cmd.Println("container has been persisted on sidechain")
return
}
}
return errors.New("timeout: container has not been persisted on sidechain")
cmd.PrintErrln("timeout: container has not been persisted on sidechain")
}
return nil
},
}
@ -206,27 +214,31 @@ var deleteContainerCmd = &cobra.Command{
Short: "Delete existing container",
Long: `Delete existing container.
Only owner of the container has a permission to remove container.`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
tok, err := getSessionToken(sessionTokenPath)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
callOpts := globalCallOptions()
@ -237,28 +249,27 @@ Only owner of the container has a permission to remove container.`,
err = cli.DeleteContainer(ctx, id, callOpts...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
fmt.Println("container delete method invoked")
cmd.Println("container delete method invoked")
if containerAwait {
fmt.Println("awaiting...")
cmd.Println("awaiting...")
for i := 0; i < awaitTimeout; i++ {
time.Sleep(1 * time.Second)
_, err := cli.GetContainer(ctx, id, globalCallOptions()...)
if err != nil {
fmt.Println("container has been removed:", containerID)
return nil
cmd.Println("container has been removed:", containerID)
return
}
}
return errors.New("timeout: container has not been removed from sidechain")
cmd.PrintErrln("timeout: container has not been removed from sidechain")
}
return nil
},
}
@ -266,27 +277,31 @@ var listContainerObjectsCmd = &cobra.Command{
Use: "list-objects",
Short: "List existing objects in container",
Long: `List existing objects in container`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
sessionToken, err := cli.CreateSession(ctx, math.MaxUint64)
if err != nil {
return fmt.Errorf("can't create session token: %w", err)
cmd.PrintErrln(fmt.Errorf("can't create session token: %w", err))
return
}
filters := new(object.SearchFilters)
@ -302,14 +317,13 @@ var listContainerObjectsCmd = &cobra.Command{
)...,
)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
for i := range objectIDs {
fmt.Println(objectIDs[i])
cmd.Println(objectIDs[i])
}
return nil
},
}
@ -317,7 +331,7 @@ var getContainerInfoCmd = &cobra.Command{
Use: "get",
Short: "Get container field info",
Long: `Get container field info`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
var (
cnr *container.Container
@ -327,36 +341,42 @@ var getContainerInfoCmd = &cobra.Command{
if containerPathFrom != "" {
data, err := ioutil.ReadFile(containerPathFrom)
if err != nil {
return fmt.Errorf("can't read file: %w", err)
cmd.PrintErrln(fmt.Errorf("can't read file: %w", err))
return
}
cnr = container.New()
if err := cnr.Unmarshal(data); err != nil {
return fmt.Errorf("can't unmarshal container: %w", err)
cmd.PrintErrln(fmt.Errorf("can't unmarshal container: %w", err))
return
}
} else {
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cnr, err = cli.GetContainer(ctx, id, globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
}
prettyPrintContainer(cnr, containerJSON)
prettyPrintContainer(cmd, cnr, containerJSON)
if containerPathTo != "" {
var (
@ -367,22 +387,23 @@ var getContainerInfoCmd = &cobra.Command{
if containerJSON {
data, err = cnr.MarshalJSON()
if err != nil {
return fmt.Errorf("can't JSON encode container: %w", err)
cmd.PrintErrln(fmt.Errorf("can't JSON encode container: %w", err))
return
}
} else {
data, err = cnr.Marshal()
if err != nil {
return fmt.Errorf("can't binary encode container: %w", err)
cmd.PrintErrln(fmt.Errorf("can't binary encode container: %w", err))
return
}
}
err = ioutil.WriteFile(containerPathTo, data, 0644)
if err != nil {
return fmt.Errorf("can't write container to file: %w", err)
cmd.PrintErrln(fmt.Errorf("can't write container to file: %w", err))
return
}
}
return nil
},
}
@ -390,40 +411,44 @@ var getExtendedACLCmd = &cobra.Command{
Use: "get-eacl",
Short: "Get extended ACL table of container",
Long: `Get extended ACL talbe of container`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
res, err := cli.GetEACL(ctx, id, globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
eaclTable := res.EACL()
sig := eaclTable.Signature()
if containerPathTo == "" {
fmt.Println("eACL: ")
prettyPrintEACL(eaclTable)
cmd.Println("eACL: ")
prettyPrintEACL(cmd, eaclTable)
fmt.Println("Signature:")
printJSONMarshaler(sig, "signature")
cmd.Println("Signature:")
printJSONMarshaler(cmd, sig, "signature")
return nil
return
}
var data []byte
@ -431,21 +456,25 @@ var getExtendedACLCmd = &cobra.Command{
if containerJSON {
data, err = eaclTable.MarshalJSON()
if err != nil {
return fmt.Errorf("can't enode to JSON: %w", err)
cmd.PrintErrln(fmt.Errorf("can't enode to JSON: %w", err))
return
}
} else {
data, err = eaclTable.Marshal()
if err != nil {
return fmt.Errorf("can't enode to binary: %w", err)
cmd.PrintErrln(fmt.Errorf("can't enode to binary: %w", err))
return
}
}
fmt.Println("dumping data to file:", containerPathTo)
cmd.Println("dumping data to file:", containerPathTo)
fmt.Println("Signature:")
printJSONMarshaler(sig, "signature")
cmd.Println("Signature:")
printJSONMarshaler(cmd, sig, "signature")
return ioutil.WriteFile(containerPathTo, data, 0644)
if err = ioutil.WriteFile(containerPathTo, data, 0644); err != nil {
cmd.PrintErrln(err)
}
},
}
@ -454,32 +483,37 @@ var setExtendedACLCmd = &cobra.Command{
Short: "Set new extended ACL table for container",
Long: `Set new extended ACL table for container.
Container ID in EACL table will be substituted with ID from the CLI.`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
eaclTable, err := parseEACL(eaclPathFrom)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
tok, err := getSessionToken(sessionTokenPath)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
eaclTable.SetCID(id)
@ -487,16 +521,18 @@ Container ID in EACL table will be substituted with ID from the CLI.`,
err = cli.SetEACL(ctx, eaclTable, globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
if containerAwait {
exp, err := eaclTable.Marshal()
if err != nil {
return errors.New("broken EACL table")
cmd.PrintErrln("broken EACL table")
return
}
fmt.Println("awaiting...")
cmd.Println("awaiting...")
for i := 0; i < awaitTimeout; i++ {
time.Sleep(1 * time.Second)
@ -510,16 +546,15 @@ Container ID in EACL table will be substituted with ID from the CLI.`,
}
if bytes.Equal(exp, got) {
fmt.Println("EACL has been persisted on sidechain")
return nil
cmd.Println("EACL has been persisted on sidechain")
return
}
}
}
return errors.New("timeout: EACL has not been persisted on sidechain")
cmd.PrintErrln("timeout: EACL has not been persisted on sidechain")
return
}
return nil
},
}
@ -615,9 +650,9 @@ func getSessionToken(path string) (*session.Token, error) {
return tok, nil
}
func prettyPrintContainerList(list []*cid.ID) {
func prettyPrintContainerList(cmd *cobra.Command, list []*cid.ID) {
for i := range list {
fmt.Println(list[i])
cmd.Println(list[i])
}
}
@ -730,7 +765,7 @@ func parseContainerID(idStr string) (*cid.ID, error) {
return id, nil
}
func prettyPrintContainer(cnr *container.Container, jsonEncoding bool) {
func prettyPrintContainer(cmd *cobra.Command, cnr *container.Container, jsonEncoding bool) {
if cnr == nil {
return
}
@ -746,35 +781,35 @@ func prettyPrintContainer(cnr *container.Container, jsonEncoding bool) {
printVerbose("Can't pretty print json: %w", err)
}
fmt.Println(buf)
cmd.Println(buf)
return
}
id := container.CalculateID(cnr)
fmt.Println("container ID:", id)
cmd.Println("container ID:", id)
version := cnr.Version()
fmt.Printf("version: %d.%d\n", version.Major(), version.Minor())
cmd.Printf("version: %d.%d\n", version.Major(), version.Minor())
fmt.Println("owner ID:", cnr.OwnerID())
cmd.Println("owner ID:", cnr.OwnerID())
basicACL := cnr.BasicACL()
fmt.Printf("basic ACL: %s", strconv.FormatUint(uint64(basicACL), 16))
cmd.Printf("basic ACL: %s", strconv.FormatUint(uint64(basicACL), 16))
switch basicACL {
case acl.PublicBasicRule:
fmt.Printf(" (%s)\n", basicACLPublic)
cmd.Printf(" (%s)\n", basicACLPublic)
case acl.PrivateBasicRule:
fmt.Printf(" (%s)\n", basicACLPrivate)
cmd.Printf(" (%s)\n", basicACLPrivate)
case acl.ReadOnlyBasicRule:
fmt.Printf(" (%s)\n", basicACLReadOnly)
cmd.Printf(" (%s)\n", basicACLReadOnly)
default:
fmt.Println()
cmd.Println()
}
for _, attribute := range cnr.Attributes() {
if attribute.Key() == container.AttributeTimestamp {
fmt.Printf("attribute: %s=%s (%s)\n",
cmd.Printf("attribute: %s=%s (%s)\n",
attribute.Key(),
attribute.Value(),
prettyPrintUnixTime(attribute.Value()))
@ -782,18 +817,18 @@ func prettyPrintContainer(cnr *container.Container, jsonEncoding bool) {
continue
}
fmt.Printf("attribute: %s=%s\n", attribute.Key(), attribute.Value())
cmd.Printf("attribute: %s=%s\n", attribute.Key(), attribute.Value())
}
nonce, err := cnr.NonceUUID()
if err == nil {
fmt.Println("nonce:", nonce)
cmd.Println("nonce:", nonce)
} else {
fmt.Println("invalid nonce:", err)
cmd.Println("invalid nonce:", err)
}
fmt.Println("placement policy:")
fmt.Println(strings.Join(policy.Encode(cnr.PlacementPolicy()), "\n"))
cmd.Println("placement policy:")
cmd.Println(strings.Join(policy.Encode(cnr.PlacementPolicy()), "\n"))
}
func parseEACL(eaclPath string) (*eacl.Table, error) {
@ -823,11 +858,11 @@ func parseEACL(eaclPath string) (*eacl.Table, error) {
return nil, fmt.Errorf("can't parse EACL table: %w", err)
}
func prettyPrintEACL(table *eacl.Table) {
printJSONMarshaler(table, "eACL")
func prettyPrintEACL(cmd *cobra.Command, table *eacl.Table) {
printJSONMarshaler(cmd, table, "eACL")
}
func printJSONMarshaler(j json.Marshaler, entity string) {
func printJSONMarshaler(cmd *cobra.Command, j json.Marshaler, entity string) {
data, err := j.MarshalJSON()
if err != nil {
printVerbose("Can't convert %s to json: %w", entity, err)
@ -838,5 +873,5 @@ func printJSONMarshaler(j json.Marshaler, entity string) {
printVerbose("Can't pretty print json: %w", err)
return
}
fmt.Println(buf)
cmd.Println(buf)
}

View file

@ -24,14 +24,14 @@ var healthCheckCmd = &cobra.Command{
Use: "healthcheck",
Short: "Health check of the storage node",
Long: "Health check of the storage node",
RunE: healthCheck,
Run: healthCheck,
}
var setNetmapStatusCmd = &cobra.Command{
Use: "set-status",
Short: "Set status of the storage node in NeoFS network map",
Long: "Set status of the storage node in NeoFS network map",
RunE: setNetmapStatus,
Run: setNetmapStatus,
}
const (
@ -79,20 +79,22 @@ func init() {
healthCheckCmd.Flags().BoolVar(&healthCheckIRVar, healthcheckIRFlag, false, "Communicate with IR node")
}
func healthCheck(cmd *cobra.Command, _ []string) error {
func healthCheck(cmd *cobra.Command, _ []string) {
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
if healthCheckIRVar {
healthCheckIR(cmd, key, cli)
return nil
return
}
req := new(control.HealthCheckRequest)
@ -100,12 +102,14 @@ func healthCheck(cmd *cobra.Command, _ []string) error {
req.SetBody(new(control.HealthCheckRequest_Body))
if err := controlSvc.SignMessage(key, req); err != nil {
return err
cmd.PrintErrln(err)
return
}
resp, err := control.HealthCheck(cli.Raw(), req)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
sign := resp.GetSignature()
@ -113,13 +117,12 @@ func healthCheck(cmd *cobra.Command, _ []string) error {
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign()
}); err != nil {
return err
cmd.PrintErrln(err)
return
}
cmd.Printf("Network status: %s\n", resp.GetBody().GetNetmapStatus())
cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus())
return nil
}
func healthCheckIR(cmd *cobra.Command, key *ecdsa.PrivateKey, c client.Client) {
@ -150,17 +153,19 @@ func healthCheckIR(cmd *cobra.Command, key *ecdsa.PrivateKey, c client.Client) {
cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus())
}
func setNetmapStatus(cmd *cobra.Command, _ []string) error {
func setNetmapStatus(cmd *cobra.Command, _ []string) {
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
var status control.NetmapStatus
switch netmapStatus {
default:
return fmt.Errorf("unsupported status %s", netmapStatus)
cmd.PrintErrln(fmt.Errorf("unsupported status %s", netmapStatus))
return
case netmapStatusOnline:
status = control.NetmapStatus_ONLINE
case netmapStatusOffline:
@ -175,17 +180,20 @@ func setNetmapStatus(cmd *cobra.Command, _ []string) error {
body.SetStatus(status)
if err := controlSvc.SignMessage(key, req); err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
resp, err := control.SetNetmapStatus(cli.Raw(), req)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
sign := resp.GetSignature()
@ -193,12 +201,11 @@ func setNetmapStatus(cmd *cobra.Command, _ []string) error {
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign()
}); err != nil {
return err
cmd.PrintErrln(err)
return
}
cmd.Println("Network status update request successfully sent.")
return nil
}
const dropObjectsFlag = "objects"
@ -209,10 +216,11 @@ var dropObjectsCmd = &cobra.Command{
Use: "drop-objects",
Short: "Drop objects from the node's local storage",
Long: "Drop objects from the node's local storage",
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
binAddrList := make([][]byte, 0, len(dropObjectsList))
@ -222,12 +230,14 @@ var dropObjectsCmd = &cobra.Command{
err := a.Parse(dropObjectsList[i])
if err != nil {
return fmt.Errorf("could not parse address #%d: %w", i, err)
cmd.PrintErrln(fmt.Errorf("could not parse address #%d: %w", i, err))
return
}
binAddr, err := a.Marshal()
if err != nil {
return fmt.Errorf("could not marshal the address: %w", err)
cmd.PrintErrln(fmt.Errorf("could not marshal the address: %w", err))
return
}
binAddrList = append(binAddrList, binAddr)
@ -241,17 +251,20 @@ var dropObjectsCmd = &cobra.Command{
body.SetAddressList(binAddrList)
if err := controlSvc.SignMessage(key, req); err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
resp, err := control.DropObjects(cli.Raw(), req)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
sign := resp.GetSignature()
@ -259,11 +272,10 @@ var dropObjectsCmd = &cobra.Command{
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign()
}); err != nil {
return err
cmd.PrintErrln(err)
return
}
cmd.Println("Objects were successfully marked to be removed.")
return nil
},
}

View file

@ -4,7 +4,6 @@ import (
"context"
"encoding/hex"
"fmt"
"github.com/mr-tron/base58"
"github.com/nspcc-dev/neo-go/pkg/config/netmode"
"github.com/nspcc-dev/neofs-api-go/pkg/netmap"
@ -47,25 +46,26 @@ var getEpochCmd = &cobra.Command{
Use: "epoch",
Short: "Get current epoch number",
Long: "Get current epoch number",
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
fmt.Println(netInfo.CurrentEpoch())
return nil
cmd.Println(netInfo.CurrentEpoch())
},
}
@ -73,25 +73,26 @@ var localNodeInfoCmd = &cobra.Command{
Use: "nodeinfo",
Short: "Get local node info",
Long: `Get local node info`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
nodeInfo, err := cli.EndpointInfo(context.Background(), globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
prettyPrintNodeInfo(nodeInfo.NodeInfo(), nodeInfoJSON)
return nil
prettyPrintNodeInfo(cmd, nodeInfo.NodeInfo(), nodeInfoJSON)
},
}
@ -99,27 +100,31 @@ var snapshotCmd = &cobra.Command{
Use: "snapshot",
Short: "Get network map snapshot",
Long: "Get network map snapshot",
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
req := new(control.NetmapSnapshotRequest)
req.SetBody(new(control.NetmapSnapshotRequest_Body))
if err := controlSvc.SignMessage(key, req); err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
resp, err := control.NetmapSnapshot(cli.Raw(), req)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
sign := resp.GetSignature()
@ -127,12 +132,11 @@ var snapshotCmd = &cobra.Command{
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign()
}); err != nil {
return err
cmd.PrintErrln(err)
return
}
prettyPrintNetmap(resp.GetBody().GetNetmap(), netmapSnapshotJSON)
return nil
prettyPrintNetmap(cmd, resp.GetBody().GetNetmap(), netmapSnapshotJSON)
},
}
@ -140,63 +144,64 @@ var netInfoCmd = &cobra.Command{
Use: "netinfo",
Short: "Get information about NeoFS network",
Long: "Get information about NeoFS network",
RunE: func(cmd *cobra.Command, args []string) error {
Run: func(cmd *cobra.Command, args []string) {
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...)
if err != nil {
return fmt.Errorf("rpc error: %w", err)
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
cmd.Printf("Epoch: %d\n", netInfo.CurrentEpoch())
magic := netInfo.MagicNumber()
cmd.Printf("Network magic: [%s] %d\n", netmode.Magic(magic), magic)
return nil
},
}
func prettyPrintNodeInfo(i *netmap.NodeInfo, jsonEncoding bool) {
func prettyPrintNodeInfo(cmd *cobra.Command, i *netmap.NodeInfo, jsonEncoding bool) {
if jsonEncoding {
printJSONMarshaler(i, "node info")
printJSONMarshaler(cmd, i, "node info")
return
}
fmt.Println("key:", hex.EncodeToString(i.PublicKey()))
fmt.Println("address:", i.Address())
fmt.Println("state:", i.State())
cmd.Println("key:", hex.EncodeToString(i.PublicKey()))
cmd.Println("address:", i.Address())
cmd.Println("state:", i.State())
for _, attribute := range i.Attributes() {
fmt.Printf("attribute: %s=%s\n", attribute.Key(), attribute.Value())
cmd.Printf("attribute: %s=%s\n", attribute.Key(), attribute.Value())
}
}
func prettyPrintNetmap(nm *control.Netmap, jsonEncoding bool) {
func prettyPrintNetmap(cmd *cobra.Command, nm *control.Netmap, jsonEncoding bool) {
if jsonEncoding {
printJSONMarshaler(nm, "netmap")
printJSONMarshaler(cmd, nm, "netmap")
return
}
fmt.Println("Epoch:", nm.GetEpoch())
cmd.Println("Epoch:", nm.GetEpoch())
for i, node := range nm.GetNodes() {
fmt.Printf("Node %d: %s %s %s\n", i+1,
cmd.Printf("Node %d: %s %s %s\n", i+1,
base58.Encode(node.GetPublicKey()),
node.GetAddress(),
node.GetState(),
)
for _, attr := range node.GetAttributes() {
fmt.Printf("\t%s: %s\n", attr.GetKey(), attr.GetValue())
cmd.Printf("\t%s: %s\n", attr.GetKey(), attr.GetValue())
}
}
}

View file

@ -48,14 +48,14 @@ var (
Use: "put",
Short: "Put object to NeoFS",
Long: "Put object to NeoFS",
RunE: putObject,
Run: putObject,
}
objectGetCmd = &cobra.Command{
Use: "get",
Short: "Get object from NeoFS",
Long: "Get object from NeoFS",
RunE: getObject,
Run: getObject,
}
objectDelCmd = &cobra.Command{
@ -63,7 +63,7 @@ var (
Aliases: []string{"del"},
Short: "Delete object from NeoFS",
Long: "Delete object from NeoFS",
RunE: deleteObject,
Run: deleteObject,
}
searchFilters []string
@ -72,28 +72,28 @@ var (
Use: "search",
Short: "Search object",
Long: "Search object",
RunE: searchObject,
Run: searchObject,
}
objectHeadCmd = &cobra.Command{
Use: "head",
Short: "Get object header",
Long: "Get object header",
RunE: getObjectHeader,
Run: getObjectHeader,
}
objectHashCmd = &cobra.Command{
Use: "hash",
Short: "Get object hash",
Long: "Get object hash",
RunE: getObjectHash,
Run: getObjectHash,
}
objectRangeCmd = &cobra.Command{
Use: getRangeCmdUse,
Short: getRangeCmdShortDesc,
Long: getRangeCmdLongDesc,
RunE: getObjectRange,
Run: getObjectRange,
}
)
@ -210,25 +210,29 @@ func initSession(ctx context.Context) (client.Client, *session.Token, error) {
return cli, tok, nil
}
func putObject(cmd *cobra.Command, _ []string) error {
func putObject(cmd *cobra.Command, _ []string) {
ownerID, err := getOwnerID()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cid, err := getCID(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
filename := cmd.Flag("file").Value.String()
f, err := os.OpenFile(filename, os.O_RDONLY, os.ModePerm)
if err != nil {
return fmt.Errorf("can't open file '%s': %w", filename, err)
cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err))
return
}
attrs, err := parseObjectAttrs(cmd)
if err != nil {
return fmt.Errorf("can't parse object attributes: %w", err)
cmd.PrintErrln(fmt.Errorf("can't parse object attributes: %w", err))
return
}
expiresOn, _ := cmd.Flags().GetUint64(putExpiresOnFlag)
@ -259,11 +263,13 @@ func putObject(cmd *cobra.Command, _ []string) error {
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
oid, err := cli.PutObject(ctx,
new(client.PutObjectParams).
@ -275,28 +281,31 @@ func putObject(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return fmt.Errorf("can't put object: %w", err)
cmd.PrintErrln(fmt.Errorf("can't put object: %w", err))
return
}
cmd.Printf("[%s] Object successfully stored\n", filename)
cmd.Printf(" ID: %s\n CID: %s\n", oid, cid)
return nil
}
func deleteObject(cmd *cobra.Command, _ []string) error {
func deleteObject(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
tombstoneAddr, err := client.DeleteObject(ctx, cli,
@ -307,18 +316,19 @@ func deleteObject(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cmd.Println("Object removed successfully.")
cmd.Printf(" ID: %s\n CID: %s\n", tombstoneAddr.ObjectID(), tombstoneAddr.ContainerID())
return nil
}
func getObject(cmd *cobra.Command, _ []string) error {
func getObject(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
var out io.Writer
@ -328,7 +338,8 @@ func getObject(cmd *cobra.Command, _ []string) error {
} else {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
return fmt.Errorf("can't open file '%s': %w", filename, err)
cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err))
return
}
defer f.Close()
out = f
@ -337,11 +348,13 @@ func getObject(cmd *cobra.Command, _ []string) error {
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
raw, _ := cmd.Flags().GetBool(rawFlag)
@ -358,10 +371,11 @@ func getObject(cmd *cobra.Command, _ []string) error {
)
if err != nil {
if ok := printSplitInfoErr(cmd, err); ok {
return nil
return
}
return fmt.Errorf("can't get object: %w", err)
cmd.PrintErrln(fmt.Errorf("can't get object: %w", err))
return
}
if filename != "" {
@ -371,25 +385,30 @@ func getObject(cmd *cobra.Command, _ []string) error {
// Print header only if file is not streamed to stdout.
hdrFile := cmd.Flag("header").Value.String()
if filename != "" || hdrFile != "" {
return saveAndPrintHeader(cmd, obj, hdrFile)
if err = saveAndPrintHeader(cmd, obj, hdrFile); err != nil {
cmd.PrintErrln(err)
return
}
}
return nil
}
func getObjectHeader(cmd *cobra.Command, _ []string) error {
func getObjectHeader(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ps := new(client.ObjectHeaderParams).WithAddress(objAddr)
if ok, _ := cmd.Flags().GetBool("main-only"); ok {
@ -407,34 +426,42 @@ func getObjectHeader(cmd *cobra.Command, _ []string) error {
)
if err != nil {
if ok := printSplitInfoErr(cmd, err); ok {
return nil
return
}
return fmt.Errorf("can't get object header: %w", err)
cmd.PrintErrln(fmt.Errorf("can't get object header: %w", err))
return
}
return saveAndPrintHeader(cmd, obj, cmd.Flag("file").Value.String())
if err = saveAndPrintHeader(cmd, obj, cmd.Flag("file").Value.String()); err != nil {
cmd.PrintErrln(err)
return
}
}
func searchObject(cmd *cobra.Command, _ []string) error {
func searchObject(cmd *cobra.Command, _ []string) {
cid, err := getCID(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
sf, err := parseSearchFilters(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ps := new(client.SearchObjectParams).WithContainerID(cid).WithSearchFilters(sf)
ids, err := cli.SearchObject(ctx, ps,
@ -444,44 +471,50 @@ func searchObject(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return fmt.Errorf("can't search object: %w", err)
cmd.PrintErrln(fmt.Errorf("can't search object: %w", err))
return
}
cmd.Printf("Found %d objects.\n", len(ids))
for _, id := range ids {
cmd.Println(id)
}
return nil
}
func getObjectHash(cmd *cobra.Command, _ []string) error {
func getObjectHash(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ranges, err := getRangeList(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
typ, err := getHashType(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
strSalt := strings.TrimPrefix(cmd.Flag(getRangeHashSaltFlag).Value.String(), "0x")
salt, err := hex.DecodeString(strSalt)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
if len(ranges) == 0 { // hash of full payload
obj, err := cli.GetObjectHeader(ctx,
@ -492,7 +525,8 @@ func getObjectHash(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return fmt.Errorf("can't get object header: %w", err)
cmd.PrintErrln(fmt.Errorf("can't get object header: %w", err))
return
}
switch typ {
case hashSha256:
@ -500,7 +534,7 @@ func getObjectHash(cmd *cobra.Command, _ []string) error {
case hashTz:
cmd.Println(hex.EncodeToString(obj.PayloadHomomorphicHash().Sum()))
}
return nil
return
}
ps := new(client.RangeChecksumParams).
@ -517,7 +551,8 @@ func getObjectHash(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
for i := range res {
cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(),
@ -531,14 +566,14 @@ func getObjectHash(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
for i := range res {
cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(),
hex.EncodeToString(res[i][:]))
}
}
return nil
}
func getOwnerID() (*owner.ID, error) {
@ -861,17 +896,20 @@ func getBearerToken(cmd *cobra.Command, flagname string) (*token.BearerToken, er
return tok, nil
}
func getObjectRange(cmd *cobra.Command, _ []string) error {
func getObjectRange(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ranges, err := getRangeList(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
} else if len(ranges) != 1 {
return errors.New("exactly one range must be specified")
cmd.PrintErrln(err)
return
}
var out io.Writer
@ -882,7 +920,8 @@ func getObjectRange(cmd *cobra.Command, _ []string) error {
} else {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
return fmt.Errorf("can't open file '%s': %w", filename, err)
cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err))
return
}
defer f.Close()
@ -894,12 +933,14 @@ func getObjectRange(cmd *cobra.Command, _ []string) error {
c, sessionToken, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
bearerToken, err := getBearerToken(cmd, "bearer")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
raw, _ := cmd.Flags().GetBool(rawFlag)
@ -917,17 +958,16 @@ func getObjectRange(cmd *cobra.Command, _ []string) error {
)
if err != nil {
if ok := printSplitInfoErr(cmd, err); ok {
return nil
return
}
return fmt.Errorf("can't get object payload range: %w", err)
cmd.PrintErrln(fmt.Errorf("can't get object payload range: %w", err))
return
}
if filename != "" {
cmd.Printf("[%s] Payload successfully saved\n", filename)
}
return nil
}
func printSplitInfoErr(cmd *cobra.Command, err error) bool {

View file

@ -26,28 +26,28 @@ var sgPutCmd = &cobra.Command{
Use: "put",
Short: "Put storage group to NeoFS",
Long: "Put storage group to NeoFS",
RunE: putSG,
Run: putSG,
}
var sgGetCmd = &cobra.Command{
Use: "get",
Short: "Get storage group from NeoFS",
Long: "Get storage group from NeoFS",
RunE: getSG,
Run: getSG,
}
var sgListCmd = &cobra.Command{
Use: "list",
Short: "List storage groups in NeoFS container",
Long: "List storage groups in NeoFS container",
RunE: listSG,
Run: listSG,
}
var sgDelCmd = &cobra.Command{
Use: "delete",
Short: "Delete storage group from NeoFS",
Long: "Delete storage group from NeoFS",
RunE: delSG,
Run: delSG,
}
const (
@ -127,15 +127,17 @@ func sgBearerToken(cmd *cobra.Command) (*token.BearerToken, error) {
return getBearerToken(cmd, sgBearerFlag)
}
func putSG(cmd *cobra.Command, _ []string) error {
func putSG(cmd *cobra.Command, _ []string) {
ownerID, err := getOwnerID()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
cid, err := getCID(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
members := make([]*objectSDK.ID, 0, len(sgMembers))
@ -143,7 +145,8 @@ func putSG(cmd *cobra.Command, _ []string) error {
for i := range sgMembers {
id := objectSDK.NewID()
if err := id.Parse(sgMembers[i]); err != nil {
return err
cmd.PrintErrln(err)
return
}
members = append(members, id)
@ -151,14 +154,16 @@ func putSG(cmd *cobra.Command, _ []string) error {
bearerToken, err := sgBearerToken(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
sg, err := storagegroup.CollectMembers(&sgHeadReceiver{
@ -168,12 +173,14 @@ func putSG(cmd *cobra.Command, _ []string) error {
bearerToken: bearerToken,
}, cid, members)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
sgContent, err := sg.Marshal()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
obj := objectSDK.NewRaw()
@ -191,13 +198,12 @@ func putSG(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return fmt.Errorf("can't put storage group: %w", err)
cmd.PrintErrln(fmt.Errorf("can't put storage group: %w", err))
return
}
cmd.Println("Storage group successfully stored")
cmd.Printf(" ID: %s\n CID: %s\n", oid, cid)
return nil
}
func getSGID() (*objectSDK.ID, error) {
@ -207,20 +213,23 @@ func getSGID() (*objectSDK.ID, error) {
return oid, err
}
func getSG(cmd *cobra.Command, _ []string) error {
func getSG(cmd *cobra.Command, _ []string) {
cid, err := getCID(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
id, err := getSGID()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
bearerToken, err := sgBearerToken(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
addr := objectSDK.NewAddress()
@ -231,7 +240,8 @@ func getSG(cmd *cobra.Command, _ []string) error {
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
obj, err := cli.GetObject(ctx,
@ -243,12 +253,14 @@ func getSG(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return fmt.Errorf("can't get storage group: %w", err)
cmd.PrintErrln(fmt.Errorf("can't get storage group: %w", err))
return
}
sg := storagegroupAPI.New()
if err := sg.Unmarshal(obj.Payload()); err != nil {
return err
cmd.PrintErrln(err)
return
}
cmd.Printf("Expiration epoch: %d\n", sg.ExpirationEpoch())
@ -262,26 +274,27 @@ func getSG(cmd *cobra.Command, _ []string) error {
cmd.Printf("\t%s\n", members[i])
}
}
return nil
}
func listSG(cmd *cobra.Command, _ []string) error {
func listSG(cmd *cobra.Command, _ []string) {
cid, err := getCID(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
bearerToken, err := sgBearerToken(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ids, err := cli.SearchObject(ctx,
@ -294,7 +307,8 @@ func listSG(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return fmt.Errorf("can't search storage groups: %w", err)
cmd.PrintErrln(fmt.Errorf("can't search storage groups: %w", err))
return
}
cmd.Printf("Found %d storage groups.\n", len(ids))
@ -302,31 +316,33 @@ func listSG(cmd *cobra.Command, _ []string) error {
for _, id := range ids {
cmd.Println(id)
}
return nil
}
func delSG(cmd *cobra.Command, _ []string) error {
func delSG(cmd *cobra.Command, _ []string) {
cid, err := getCID(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
id, err := getSGID()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
bearerToken, err := sgBearerToken(cmd)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
ctx := context.Background()
cli, tok, err := initSession(ctx)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
addr := objectSDK.NewAddress()
@ -342,11 +358,10 @@ func delSG(cmd *cobra.Command, _ []string) error {
)...,
)
if err != nil {
return fmt.Errorf("can't get storage group: %w", err)
cmd.PrintErrln(fmt.Errorf("can't get storage group: %w", err))
return
}
cmd.Println("Storage group removed successfully.")
cmd.Printf(" Tombstone: %s\n", tombstone.ObjectID())
return nil
}

View file

@ -38,13 +38,13 @@ var (
signBearerCmd = &cobra.Command{
Use: "bearer-token",
Short: "Sign bearer token to use it in requests",
RunE: signBearerToken,
Run: signBearerToken,
}
signSessionCmd = &cobra.Command{
Use: "session-token",
Short: "Sign session token to use it in requests",
RunE: signSessionToken,
Run: signSessionToken,
}
convertCmd = &cobra.Command{
@ -55,13 +55,13 @@ var (
convertEACLCmd = &cobra.Command{
Use: "eacl",
Short: "Convert representation of extended ACL table",
RunE: convertEACLTable,
Run: convertEACLTable,
}
keyerCmd = &cobra.Command{
Use: "keyer",
Short: "Generate or print information about keys",
RunE: processKeyer,
Run: processKeyer,
}
)
@ -96,7 +96,7 @@ var (
locodeGenerateCmd = &cobra.Command{
Use: "generate",
Short: "generate UN/LOCODE database for NeoFS",
RunE: func(cmd *cobra.Command, _ []string) error {
Run: func(cmd *cobra.Command, _ []string) {
locodeDB := csvlocode.New(
csvlocode.Prm{
Path: locodeGenerateInPaths[0],
@ -120,7 +120,8 @@ var (
err := targetDB.Open()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
defer targetDB.Close()
@ -132,10 +133,9 @@ var (
err = locodedb.FillDatabase(locodeDB, airportDB, continentsDB, names, targetDB)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
return nil
},
}
)
@ -152,34 +152,34 @@ var (
locodeInfoCmd = &cobra.Command{
Use: "info",
Short: "print information about UN/LOCODE from NeoFS database",
RunE: func(cmd *cobra.Command, _ []string) error {
Run: func(cmd *cobra.Command, _ []string) {
targetDB := locodebolt.New(locodebolt.Prm{
Path: locodeInfoDBPath,
})
err := targetDB.Open()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
defer targetDB.Close()
record, err := locodedb.LocodeRecord(targetDB, locodeInfoCode)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
fmt.Printf("Country: %s\n", record.CountryName())
fmt.Printf("Location: %s\n", record.LocationName())
fmt.Printf("Continent: %s\n", record.Continent())
cmd.Printf("Country: %s\n", record.CountryName())
cmd.Printf("Location: %s\n", record.LocationName())
cmd.Printf("Continent: %s\n", record.Continent())
if subDivCode := record.SubDivCode(); subDivCode != "" {
fmt.Printf("Subdivision: [%s] %s\n", subDivCode, record.SubDivName())
cmd.Printf("Subdivision: [%s] %s\n", subDivCode, record.SubDivName())
}
geoPoint := record.GeoPoint()
fmt.Printf("Coordinates: %0.2f, %0.2f\n", geoPoint.Latitude(), geoPoint.Longitude())
return nil
cmd.Printf("Coordinates: %0.2f, %0.2f\n", geoPoint.Latitude(), geoPoint.Longitude())
},
}
)
@ -254,25 +254,29 @@ func init() {
_ = locodeGenerateCmd.MarkFlagRequired(locodeInfoCodeFlag)
}
func signBearerToken(cmd *cobra.Command, _ []string) error {
func signBearerToken(cmd *cobra.Command, _ []string) {
btok, err := getBearerToken(cmd, "from")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
key, err := getKey()
if err != nil {
return err
cmd.PrintErrln(err)
return
}
err = completeBearerToken(btok)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
err = btok.SignToken(key)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
to := cmd.Flag("to").Value.String()
@ -282,113 +286,119 @@ func signBearerToken(cmd *cobra.Command, _ []string) error {
if jsonFlag || len(to) == 0 {
data, err = btok.MarshalJSON()
if err != nil {
return fmt.Errorf("can't JSON encode bearer token: %w", err)
cmd.PrintErrln(fmt.Errorf("can't JSON encode bearer token: %w", err))
return
}
} else {
data, err = btok.Marshal()
if err != nil {
return fmt.Errorf("can't binary encode bearer token: %w", err)
cmd.PrintErrln(fmt.Errorf("can't binary encode bearer token: %w", err))
return
}
}
if len(to) == 0 {
prettyPrintJSON(cmd, data)
return nil
return
}
err = ioutil.WriteFile(to, data, 0644)
if err != nil {
return fmt.Errorf("can't write signed bearer token to file: %w", err)
cmd.PrintErrln(fmt.Errorf("can't write signed bearer token to file: %w", err))
return
}
cmd.Printf("signed bearer token was successfully dumped to %s\n", to)
return nil
}
func signSessionToken(cmd *cobra.Command, _ []string) error {
func signSessionToken(cmd *cobra.Command, _ []string) {
path, err := cmd.Flags().GetString("from")
if err != nil {
return err
cmd.PrintErrln(err)
return
}
stok, err := getSessionToken(path)
if err != nil {
return fmt.Errorf("can't read session token from %s: %w", path, err)
cmd.PrintErrln(fmt.Errorf("can't read session token from %s: %w", path, err))
return
}
key, err := getKey()
if err != nil {
return fmt.Errorf("can't get private key, make sure it is provided: %w", err)
cmd.PrintErrln(fmt.Errorf("can't get private key, make sure it is provided: %w", err))
return
}
err = stok.Sign(key)
if err != nil {
return fmt.Errorf("can't sign token: %w", err)
cmd.PrintErrln(fmt.Errorf("can't sign token: %w", err))
return
}
data, err := stok.MarshalJSON()
if err != nil {
return fmt.Errorf("can't encode session token: %w", err)
cmd.PrintErrln(fmt.Errorf("can't encode session token: %w", err))
return
}
to := cmd.Flag("to").Value.String()
if len(to) == 0 {
prettyPrintJSON(cmd, data)
return nil
return
}
err = ioutil.WriteFile(to, data, 0644)
if err != nil {
return fmt.Errorf("can't write signed session token to %s: %w", to, err)
cmd.PrintErrln(fmt.Errorf("can't write signed session token to %s: %w", to, err))
return
}
fmt.Printf("signed session token saved in %s\n", to)
return nil
cmd.Printf("signed session token saved in %s\n", to)
}
func convertEACLTable(cmd *cobra.Command, _ []string) error {
func convertEACLTable(cmd *cobra.Command, _ []string) {
pathFrom := cmd.Flag("from").Value.String()
to := cmd.Flag("to").Value.String()
jsonFlag, _ := cmd.Flags().GetBool("json")
table, err := parseEACL(pathFrom)
if err != nil {
return err
cmd.PrintErrln(err)
return
}
var data []byte
if jsonFlag || len(to) == 0 {
data, err = table.MarshalJSON()
if err != nil {
return fmt.Errorf("can't JSON encode extended ACL table: %w", err)
cmd.PrintErrln(fmt.Errorf("can't JSON encode extended ACL table: %w", err))
return
}
} else {
data, err = table.Marshal()
if err != nil {
return fmt.Errorf("can't binary encode extended ACL table: %w", err)
cmd.PrintErrln(fmt.Errorf("can't binary encode extended ACL table: %w", err))
return
}
}
if len(to) == 0 {
prettyPrintJSON(cmd, data)
return nil
return
}
err = ioutil.WriteFile(to, data, 0644)
if err != nil {
return fmt.Errorf("can't write exteded ACL table to file: %w", err)
cmd.PrintErrln(fmt.Errorf("can't write exteded ACL table to file: %w", err))
return
}
cmd.Printf("extended ACL table was successfully dumped to %s\n", to)
return nil
}
func processKeyer(cmd *cobra.Command, args []string) error {
func processKeyer(cmd *cobra.Command, args []string) {
var (
err error
@ -403,7 +413,8 @@ func processKeyer(cmd *cobra.Command, args []string) error {
err = result.ParseMultiSig(args)
} else {
if len(args) > 1 {
return errKeyerSingleArgument
cmd.PrintErrln(errKeyerSingleArgument)
return
}
var argument string
@ -422,12 +433,11 @@ func processKeyer(cmd *cobra.Command, args []string) error {
}
if err != nil {
return err
cmd.PrintErrln(err)
return
}
result.PrettyPrint(uncompressed, useHex)
return nil
}
func completeBearerToken(btok *token.BearerToken) error {