[#665] cli: Set non-zero exit codes in err cases

Signed-off-by: Pavel Karpy <carpawell@nspcc.ru>
This commit is contained in:
Pavel Karpy 2021-07-06 15:27:54 +03:00 committed by Leonard Lyubich
parent 8965e70463
commit 3a7d7bdecd
8 changed files with 245 additions and 742 deletions

View file

@ -34,38 +34,23 @@ var accountingBalanceCmd = &cobra.Command{
) )
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
if balanceOwner == "" { if balanceOwner == "" {
wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey) wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
oid = owner.NewIDFromNeo3Wallet(wallet) oid = owner.NewIDFromNeo3Wallet(wallet)
} else { } else {
oid, err = ownerFromString(balanceOwner) oid, err = ownerFromString(balanceOwner)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
} }
response, err = cli.GetBalance(ctx, oid, globalCallOptions()...) response, err = cli.GetBalance(ctx, oid, globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
// print to stdout // print to stdout
prettyPrintDecimal(cmd, response) prettyPrintDecimal(cmd, response)

View file

@ -67,6 +67,12 @@ var (
eaclPathFrom string eaclPathFrom string
) )
var (
errDeleteTimeout = errors.New("timeout: container has not been removed from sidechain")
errCreateTimeout = errors.New("timeout: container has not been persisted on sidechain")
errSetEACLTimeout = errors.New("timeout: EACL has not been persisted on sidechain")
)
// containerCmd represents the container command // containerCmd represents the container command
var containerCmd = &cobra.Command{ var containerCmd = &cobra.Command{
Use: "container", Use: "container",
@ -87,38 +93,23 @@ var listContainersCmd = &cobra.Command{
) )
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
if containerOwner == "" { if containerOwner == "" {
wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey) wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
oid = owner.NewIDFromNeo3Wallet(wallet) oid = owner.NewIDFromNeo3Wallet(wallet)
} else { } else {
oid, err = ownerFromString(containerOwner) oid, err = ownerFromString(containerOwner)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
} }
response, err = cli.ListContainers(ctx, oid, globalCallOptions()...) response, err = cli.ListContainers(ctx, oid, globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
// print to stdout // print to stdout
prettyPrintContainerList(cmd, response) prettyPrintContainerList(cmd, response)
@ -134,46 +125,25 @@ It will be stored in sidechain when inner ring will accepts it.`,
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
placementPolicy, err := parseContainerPolicy(containerPolicy) placementPolicy, err := parseContainerPolicy(containerPolicy)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
attributes, err := parseAttributes(containerAttributes) attributes, err := parseAttributes(containerAttributes)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
basicACL, err := parseBasicACL(containerACL) basicACL, err := parseBasicACL(containerACL)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
nonce, err := parseNonce(containerNonce) nonce, err := parseNonce(containerNonce)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
tok, err := getSessionToken(sessionTokenPath) tok, err := getSessionToken(sessionTokenPath)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cnr := container.New() cnr := container.New()
cnr.SetPlacementPolicy(placementPolicy) cnr.SetPlacementPolicy(placementPolicy)
@ -184,10 +154,7 @@ It will be stored in sidechain when inner ring will accepts it.`,
cnr.SetOwnerID(tok.OwnerID()) cnr.SetOwnerID(tok.OwnerID())
id, err := cli.PutContainer(ctx, cnr, globalCallOptions()...) id, err := cli.PutContainer(ctx, cnr, globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
cmd.Println("container ID:", id) cmd.Println("container ID:", id)
@ -204,7 +171,7 @@ It will be stored in sidechain when inner ring will accepts it.`,
} }
} }
cmd.PrintErrln("timeout: container has not been persisted on sidechain") exitOnErr(cmd, errCreateTimeout)
} }
}, },
} }
@ -218,28 +185,16 @@ Only owner of the container has a permission to remove container.`,
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
tok, err := getSessionToken(sessionTokenPath) tok, err := getSessionToken(sessionTokenPath)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
callOpts := globalCallOptions() callOpts := globalCallOptions()
@ -248,10 +203,7 @@ Only owner of the container has a permission to remove container.`,
} }
err = cli.DeleteContainer(ctx, id, callOpts...) err = cli.DeleteContainer(ctx, id, callOpts...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
cmd.Println("container delete method invoked") cmd.Println("container delete method invoked")
@ -268,7 +220,7 @@ Only owner of the container has a permission to remove container.`,
} }
} }
cmd.PrintErrln("timeout: container has not been removed from sidechain") exitOnErr(cmd, errDeleteTimeout)
} }
}, },
} }
@ -281,28 +233,16 @@ var listContainerObjectsCmd = &cobra.Command{
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
sessionToken, err := cli.CreateSession(ctx, math.MaxUint64) sessionToken, err := cli.CreateSession(ctx, math.MaxUint64)
if err != nil { exitOnErr(cmd, errf("can't create session token: %w", err))
cmd.PrintErrln(fmt.Errorf("can't create session token: %w", err))
return
}
filters := new(object.SearchFilters) filters := new(object.SearchFilters)
filters.AddRootFilter() // search only user created objects filters.AddRootFilter() // search only user created objects
@ -316,10 +256,7 @@ var listContainerObjectsCmd = &cobra.Command{
client.WithSession(sessionToken), client.WithSession(sessionToken),
)..., )...,
) )
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
for i := range objectIDs { for i := range objectIDs {
cmd.Println(objectIDs[i]) cmd.Println(objectIDs[i])
@ -340,40 +277,23 @@ var getContainerInfoCmd = &cobra.Command{
if containerPathFrom != "" { if containerPathFrom != "" {
data, err := os.ReadFile(containerPathFrom) data, err := os.ReadFile(containerPathFrom)
if err != nil { exitOnErr(cmd, errf("can't read file: %w", err))
cmd.PrintErrln(fmt.Errorf("can't read file: %w", err))
return
}
cnr = container.New() cnr = container.New()
if err := cnr.Unmarshal(data); err != nil { err = cnr.Unmarshal(data)
cmd.PrintErrln(fmt.Errorf("can't unmarshal container: %w", err)) exitOnErr(cmd, errf("can't unmarshal container: %w", err))
return
}
} else { } else {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cnr, err = cli.GetContainer(ctx, id, globalCallOptions()...) cnr, err = cli.GetContainer(ctx, id, globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
} }
prettyPrintContainer(cmd, cnr, containerJSON) prettyPrintContainer(cmd, cnr, containerJSON)
@ -386,23 +306,14 @@ var getContainerInfoCmd = &cobra.Command{
if containerJSON { if containerJSON {
data, err = cnr.MarshalJSON() data, err = cnr.MarshalJSON()
if err != nil { exitOnErr(cmd, errf("can't JSON encode container: %w", err))
cmd.PrintErrln(fmt.Errorf("can't JSON encode container: %w", err))
return
}
} else { } else {
data, err = cnr.Marshal() data, err = cnr.Marshal()
if err != nil { exitOnErr(cmd, errf("can't binary encode container: %w", err))
cmd.PrintErrln(fmt.Errorf("can't binary encode container: %w", err))
return
}
} }
err = os.WriteFile(containerPathTo, data, 0644) err = os.WriteFile(containerPathTo, data, 0644)
if err != nil { exitOnErr(cmd, errf("can't write container to file: %w", err))
cmd.PrintErrln(fmt.Errorf("can't write container to file: %w", err))
return
}
} }
}, },
} }
@ -415,28 +326,16 @@ var getExtendedACLCmd = &cobra.Command{
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
res, err := cli.GetEACL(ctx, id, globalCallOptions()...) res, err := cli.GetEACL(ctx, id, globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
eaclTable := res.EACL() eaclTable := res.EACL()
sig := eaclTable.Signature() sig := eaclTable.Signature()
@ -455,16 +354,10 @@ var getExtendedACLCmd = &cobra.Command{
if containerJSON { if containerJSON {
data, err = eaclTable.MarshalJSON() data, err = eaclTable.MarshalJSON()
if err != nil { exitOnErr(cmd, errf("can't enode to JSON: %w", err))
cmd.PrintErrln(fmt.Errorf("can't enode to JSON: %w", err))
return
}
} else { } else {
data, err = eaclTable.Marshal() data, err = eaclTable.Marshal()
if err != nil { exitOnErr(cmd, errf("can't enode to binary: %w", err))
cmd.PrintErrln(fmt.Errorf("can't enode to binary: %w", err))
return
}
} }
cmd.Println("dumping data to file:", containerPathTo) cmd.Println("dumping data to file:", containerPathTo)
@ -472,9 +365,8 @@ var getExtendedACLCmd = &cobra.Command{
cmd.Println("Signature:") cmd.Println("Signature:")
printJSONMarshaler(cmd, sig, "signature") printJSONMarshaler(cmd, sig, "signature")
if err = os.WriteFile(containerPathTo, data, 0644); err != nil { err = os.WriteFile(containerPathTo, data, 0644)
cmd.PrintErrln(err) exitOnErr(cmd, err)
}
}, },
} }
@ -487,50 +379,29 @@ Container ID in EACL table will be substituted with ID from the CLI.`,
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
eaclTable, err := parseEACL(eaclPathFrom) eaclTable, err := parseEACL(eaclPathFrom)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
tok, err := getSessionToken(sessionTokenPath) tok, err := getSessionToken(sessionTokenPath)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
eaclTable.SetCID(id) eaclTable.SetCID(id)
eaclTable.SetSessionToken(tok) eaclTable.SetSessionToken(tok)
err = cli.SetEACL(ctx, eaclTable, globalCallOptions()...) err = cli.SetEACL(ctx, eaclTable, globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
if containerAwait { if containerAwait {
exp, err := eaclTable.Marshal() exp, err := eaclTable.Marshal()
if err != nil { exitOnErr(cmd, errf("broken EACL table: %w", err))
cmd.PrintErrln("broken EACL table")
return
}
cmd.Println("awaiting...") cmd.Println("awaiting...")
@ -552,8 +423,7 @@ Container ID in EACL table will be substituted with ID from the CLI.`,
} }
} }
cmd.PrintErrln("timeout: EACL has not been persisted on sidechain") exitOnErr(cmd, errSetEACLTimeout)
return
} }
}, },
} }

View file

@ -85,16 +85,10 @@ func init() {
func healthCheck(cmd *cobra.Command, _ []string) { func healthCheck(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
if healthCheckIRVar { if healthCheckIRVar {
healthCheckIR(cmd, key, cli) healthCheckIR(cmd, key, cli)
@ -105,25 +99,21 @@ func healthCheck(cmd *cobra.Command, _ []string) {
req.SetBody(new(control.HealthCheckRequest_Body)) req.SetBody(new(control.HealthCheckRequest_Body))
if err := controlSvc.SignMessage(key, req); err != nil { err = controlSvc.SignMessage(key, req)
cmd.PrintErrln(err) exitOnErr(cmd, err)
return
}
resp, err := control.HealthCheck(cli.Raw(), req) resp, err := control.HealthCheck(cli.Raw(), req)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
sign := resp.GetSignature() sign := resp.GetSignature()
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { err = signature.VerifyDataWithSource(
resp,
func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { },
cmd.PrintErrln(err) )
return exitOnErr(cmd, err)
}
cmd.Printf("Network status: %s\n", resp.GetBody().GetNetmapStatus()) cmd.Printf("Network status: %s\n", resp.GetBody().GetNetmapStatus())
cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus()) cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus())
@ -134,42 +124,34 @@ func healthCheckIR(cmd *cobra.Command, key *ecdsa.PrivateKey, c client.Client) {
req.SetBody(new(ircontrol.HealthCheckRequest_Body)) req.SetBody(new(ircontrol.HealthCheckRequest_Body))
if err := ircontrolsrv.SignMessage(key, req); err != nil { err := ircontrolsrv.SignMessage(key, req)
cmd.PrintErrln(fmt.Errorf("could not sign request: %w", err)) exitOnErr(cmd, errf("could not sign request: %w", err))
return
}
resp, err := ircontrol.HealthCheck(c.Raw(), req) resp, err := ircontrol.HealthCheck(c.Raw(), req)
if err != nil { exitOnErr(cmd, errf("rpc failure: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc failure: %w", err))
return
}
sign := resp.GetSignature() sign := resp.GetSignature()
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { err = signature.VerifyDataWithSource(
resp,
func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { },
cmd.PrintErrln(fmt.Errorf("invalid response signature: %w", err)) )
return exitOnErr(cmd, errf("invalid response signature: %w", err))
}
cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus()) cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus())
} }
func setNetmapStatus(cmd *cobra.Command, _ []string) { func setNetmapStatus(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
var status control.NetmapStatus var status control.NetmapStatus
switch netmapStatus { switch netmapStatus {
default: default:
cmd.PrintErrln(fmt.Errorf("unsupported status %s", netmapStatus)) exitOnErr(cmd, fmt.Errorf("unsupported status %s", netmapStatus))
return
case netmapStatusOnline: case netmapStatusOnline:
status = control.NetmapStatus_ONLINE status = control.NetmapStatus_ONLINE
case netmapStatusOffline: case netmapStatusOffline:
@ -183,31 +165,24 @@ func setNetmapStatus(cmd *cobra.Command, _ []string) {
body.SetStatus(status) body.SetStatus(status)
if err := controlSvc.SignMessage(key, req); err != nil { err = controlSvc.SignMessage(key, req)
cmd.PrintErrln(err) exitOnErr(cmd, err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
resp, err := control.SetNetmapStatus(cli.Raw(), req) resp, err := control.SetNetmapStatus(cli.Raw(), req)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
sign := resp.GetSignature() sign := resp.GetSignature()
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { err = signature.VerifyDataWithSource(
resp,
func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { },
cmd.PrintErrln(err) )
return exitOnErr(cmd, err)
}
cmd.Println("Network status update request successfully sent.") cmd.Println("Network status update request successfully sent.")
} }
@ -222,10 +197,7 @@ var dropObjectsCmd = &cobra.Command{
Long: "Drop objects from the node's local storage", Long: "Drop objects from the node's local storage",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
binAddrList := make([][]byte, 0, len(dropObjectsList)) binAddrList := make([][]byte, 0, len(dropObjectsList))
@ -234,15 +206,11 @@ var dropObjectsCmd = &cobra.Command{
err := a.Parse(dropObjectsList[i]) err := a.Parse(dropObjectsList[i])
if err != nil { if err != nil {
cmd.PrintErrln(fmt.Errorf("could not parse address #%d: %w", i, err)) exitOnErr(cmd, fmt.Errorf("could not parse address #%d: %w", i, err))
return
} }
binAddr, err := a.Marshal() binAddr, err := a.Marshal()
if err != nil { exitOnErr(cmd, errf("could not marshal the address: %w", err))
cmd.PrintErrln(fmt.Errorf("could not marshal the address: %w", err))
return
}
binAddrList = append(binAddrList, binAddr) binAddrList = append(binAddrList, binAddr)
} }
@ -254,31 +222,24 @@ var dropObjectsCmd = &cobra.Command{
body.SetAddressList(binAddrList) body.SetAddressList(binAddrList)
if err := controlSvc.SignMessage(key, req); err != nil { err = controlSvc.SignMessage(key, req)
cmd.PrintErrln(err) exitOnErr(cmd, err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
resp, err := control.DropObjects(cli.Raw(), req) resp, err := control.DropObjects(cli.Raw(), req)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
sign := resp.GetSignature() sign := resp.GetSignature()
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { err = signature.VerifyDataWithSource(
resp,
func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { },
cmd.PrintErrln(err) )
return exitOnErr(cmd, err)
}
cmd.Println("Objects were successfully marked to be removed.") cmd.Println("Objects were successfully marked to be removed.")
}, },
@ -290,39 +251,29 @@ var snapshotCmd = &cobra.Command{
Long: "Get network map snapshot", Long: "Get network map snapshot",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
req := new(control.NetmapSnapshotRequest) req := new(control.NetmapSnapshotRequest)
req.SetBody(new(control.NetmapSnapshotRequest_Body)) req.SetBody(new(control.NetmapSnapshotRequest_Body))
if err := controlSvc.SignMessage(key, req); err != nil { err = controlSvc.SignMessage(key, req)
cmd.PrintErrln(err) exitOnErr(cmd, err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
resp, err := control.NetmapSnapshot(cli.Raw(), req) resp, err := control.NetmapSnapshot(cli.Raw(), req)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
sign := resp.GetSignature() sign := resp.GetSignature()
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { err = signature.VerifyDataWithSource(
resp,
func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { },
cmd.PrintErrln(err) )
return exitOnErr(cmd, err)
}
prettyPrintNetmap(cmd, resp.GetBody().GetNetmap(), netmapSnapshotJSON) prettyPrintNetmap(cmd, resp.GetBody().GetNetmap(), netmapSnapshotJSON)
}, },

View file

@ -3,7 +3,6 @@ package cmd
import ( import (
"context" "context"
"encoding/hex" "encoding/hex"
"fmt"
"github.com/mr-tron/base58" "github.com/mr-tron/base58"
"github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/config/netmode"
@ -43,22 +42,13 @@ var getEpochCmd = &cobra.Command{
Long: "Get current epoch number", Long: "Get current epoch number",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...) netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
cmd.Println(netInfo.CurrentEpoch()) cmd.Println(netInfo.CurrentEpoch())
}, },
@ -70,22 +60,13 @@ var localNodeInfoCmd = &cobra.Command{
Long: `Get local node info`, Long: `Get local node info`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
nodeInfo, err := cli.EndpointInfo(context.Background(), globalCallOptions()...) nodeInfo, err := cli.EndpointInfo(context.Background(), globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
prettyPrintNodeInfo(cmd, nodeInfo.NodeInfo(), nodeInfoJSON) prettyPrintNodeInfo(cmd, nodeInfo.NodeInfo(), nodeInfoJSON)
}, },
@ -97,22 +78,13 @@ var netInfoCmd = &cobra.Command{
Long: "Get information about NeoFS network", Long: "Get information about NeoFS network",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...) netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...)
if err != nil { exitOnErr(cmd, errf("rpc error: %w", err))
cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
}
cmd.Printf("Epoch: %d\n", netInfo.CurrentEpoch()) cmd.Printf("Epoch: %d\n", netInfo.CurrentEpoch())

View file

@ -208,34 +208,21 @@ func initSession(ctx context.Context, key *ecdsa.PrivateKey) (client.Client, *se
func putObject(cmd *cobra.Command, _ []string) { func putObject(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
ownerID, err := getOwnerID(key) ownerID, err := getOwnerID(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
filename := cmd.Flag("file").Value.String() filename := cmd.Flag("file").Value.String()
f, err := os.OpenFile(filename, os.O_RDONLY, os.ModePerm) f, err := os.OpenFile(filename, os.O_RDONLY, os.ModePerm)
if err != nil { if err != nil {
cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err)) exitOnErr(cmd, fmt.Errorf("can't open file '%s': %w", filename, err))
return
} }
attrs, err := parseObjectAttrs(cmd) attrs, err := parseObjectAttrs(cmd)
if err != nil { exitOnErr(cmd, errf("can't parse object attributes: %w", err))
cmd.PrintErrln(fmt.Errorf("can't parse object attributes: %w", err))
return
}
expiresOn, _ := cmd.Flags().GetUint64(putExpiresOnFlag) expiresOn, _ := cmd.Flags().GetUint64(putExpiresOnFlag)
if expiresOn > 0 { if expiresOn > 0 {
@ -264,15 +251,9 @@ func putObject(cmd *cobra.Command, _ []string) {
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
oid, err := cli.PutObject(ctx, oid, err := cli.PutObject(ctx,
new(client.PutObjectParams). new(client.PutObjectParams).
WithObject(obj.Object()). WithObject(obj.Object()).
@ -282,10 +263,7 @@ func putObject(cmd *cobra.Command, _ []string) {
client.WithBearer(btok), client.WithBearer(btok),
)..., )...,
) )
if err != nil { exitOnErr(cmd, errf("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("[%s] Object successfully stored\n", filename)
cmd.Printf(" ID: %s\n CID: %s\n", oid, cid) cmd.Printf(" ID: %s\n CID: %s\n", oid, cid)
@ -293,28 +271,16 @@ func putObject(cmd *cobra.Command, _ []string) {
func deleteObject(cmd *cobra.Command, _ []string) { func deleteObject(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
tombstoneAddr, err := client.DeleteObject(ctx, cli, tombstoneAddr, err := client.DeleteObject(ctx, cli,
new(client.DeleteObjectParams).WithAddress(objAddr), new(client.DeleteObjectParams).WithAddress(objAddr),
@ -323,10 +289,7 @@ func deleteObject(cmd *cobra.Command, _ []string) {
client.WithBearer(btok), client.WithBearer(btok),
)..., )...,
) )
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cmd.Println("Object removed successfully.") cmd.Println("Object removed successfully.")
cmd.Printf(" ID: %s\n CID: %s\n", tombstoneAddr.ObjectID(), tombstoneAddr.ContainerID()) cmd.Printf(" ID: %s\n CID: %s\n", tombstoneAddr.ObjectID(), tombstoneAddr.ContainerID())
@ -334,16 +297,10 @@ func deleteObject(cmd *cobra.Command, _ []string) {
func getObject(cmd *cobra.Command, _ []string) { func getObject(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
var out io.Writer var out io.Writer
filename := cmd.Flag("file").Value.String() filename := cmd.Flag("file").Value.String()
@ -352,24 +309,19 @@ func getObject(cmd *cobra.Command, _ []string) {
} else { } else {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm) f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil { if err != nil {
cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err)) exitOnErr(cmd, fmt.Errorf("can't open file '%s': %w", filename, err))
return
} }
defer f.Close() defer f.Close()
out = f out = f
} }
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
raw, _ := cmd.Flags().GetBool(rawFlag) raw, _ := cmd.Flags().GetBool(rawFlag)
@ -388,8 +340,7 @@ func getObject(cmd *cobra.Command, _ []string) {
return return
} }
cmd.PrintErrln(fmt.Errorf("can't get object: %w", err)) exitOnErr(cmd, fmt.Errorf("can't get object: %w", err))
return
} }
if filename != "" { if filename != "" {
@ -399,37 +350,23 @@ func getObject(cmd *cobra.Command, _ []string) {
// Print header only if file is not streamed to stdout. // Print header only if file is not streamed to stdout.
hdrFile := cmd.Flag("header").Value.String() hdrFile := cmd.Flag("header").Value.String()
if filename != "" || hdrFile != "" { if filename != "" || hdrFile != "" {
if err = saveAndPrintHeader(cmd, obj, hdrFile); err != nil { err = saveAndPrintHeader(cmd, obj, hdrFile)
cmd.PrintErrln(err) exitOnErr(cmd, err)
return
}
} }
} }
func getObjectHeader(cmd *cobra.Command, _ []string) { func getObjectHeader(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ps := new(client.ObjectHeaderParams).WithAddress(objAddr) ps := new(client.ObjectHeaderParams).WithAddress(objAddr)
if ok, _ := cmd.Flags().GetBool("main-only"); ok { if ok, _ := cmd.Flags().GetBool("main-only"); ok {
ps = ps.WithMainFields() ps = ps.WithMainFields()
@ -449,46 +386,28 @@ func getObjectHeader(cmd *cobra.Command, _ []string) {
return return
} }
cmd.PrintErrln(fmt.Errorf("can't get object header: %w", err)) exitOnErr(cmd, fmt.Errorf("can't get object header: %w", err))
return
} }
if err = saveAndPrintHeader(cmd, obj, cmd.Flag("file").Value.String()); err != nil { err = saveAndPrintHeader(cmd, obj, cmd.Flag("file").Value.String())
cmd.PrintErrln(err) exitOnErr(cmd, err)
return
}
} }
func searchObject(cmd *cobra.Command, _ []string) { func searchObject(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
sf, err := parseSearchFilters(cmd) sf, err := parseSearchFilters(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ps := new(client.SearchObjectParams).WithContainerID(cid).WithSearchFilters(sf) ps := new(client.SearchObjectParams).WithContainerID(cid).WithSearchFilters(sf)
ids, err := cli.SearchObject(ctx, ps, ids, err := cli.SearchObject(ctx, ps,
append(globalCallOptions(), append(globalCallOptions(),
@ -496,10 +415,7 @@ func searchObject(cmd *cobra.Command, _ []string) {
client.WithBearer(btok), client.WithBearer(btok),
)..., )...,
) )
if err != nil { exitOnErr(cmd, errf("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)) cmd.Printf("Found %d objects.\n", len(ids))
for _, id := range ids { for _, id := range ids {
cmd.Println(id) cmd.Println(id)
@ -508,46 +424,25 @@ func searchObject(cmd *cobra.Command, _ []string) {
func getObjectHash(cmd *cobra.Command, _ []string) { func getObjectHash(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ranges, err := getRangeList(cmd) ranges, err := getRangeList(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
typ, err := getHashType(cmd) typ, err := getHashType(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
strSalt := strings.TrimPrefix(cmd.Flag(getRangeHashSaltFlag).Value.String(), "0x") strSalt := strings.TrimPrefix(cmd.Flag(getRangeHashSaltFlag).Value.String(), "0x")
salt, err := hex.DecodeString(strSalt) salt, err := hex.DecodeString(strSalt)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
if len(ranges) == 0 { // hash of full payload if len(ranges) == 0 { // hash of full payload
obj, err := cli.GetObjectHeader(ctx, obj, err := cli.GetObjectHeader(ctx,
new(client.ObjectHeaderParams).WithAddress(objAddr), new(client.ObjectHeaderParams).WithAddress(objAddr),
@ -556,10 +451,7 @@ func getObjectHash(cmd *cobra.Command, _ []string) {
client.WithBearer(btok), client.WithBearer(btok),
)..., )...,
) )
if err != nil { exitOnErr(cmd, errf("can't get object header: %w", err))
cmd.PrintErrln(fmt.Errorf("can't get object header: %w", err))
return
}
switch typ { switch typ {
case hashSha256: case hashSha256:
cmd.Println(hex.EncodeToString(obj.PayloadChecksum().Sum())) cmd.Println(hex.EncodeToString(obj.PayloadChecksum().Sum()))
@ -582,10 +474,7 @@ func getObjectHash(cmd *cobra.Command, _ []string) {
client.WithBearer(btok), client.WithBearer(btok),
)..., )...,
) )
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
for i := range res { for i := range res {
cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(), cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(),
hex.EncodeToString(res[i][:])) hex.EncodeToString(res[i][:]))
@ -597,10 +486,7 @@ func getObjectHash(cmd *cobra.Command, _ []string) {
client.WithBearer(btok), client.WithBearer(btok),
)..., )...,
) )
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
for i := range res { for i := range res {
cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(), cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(),
hex.EncodeToString(res[i][:])) hex.EncodeToString(res[i][:]))
@ -926,24 +812,16 @@ func getBearerToken(cmd *cobra.Command, flagname string) (*token.BearerToken, er
func getObjectRange(cmd *cobra.Command, _ []string) { func getObjectRange(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ranges, err := getRangeList(cmd) ranges, err := getRangeList(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return if len(ranges) != 1 {
} else if len(ranges) != 1 { exitOnErr(cmd, fmt.Errorf("exactly one range must be specified, got: %d", len(ranges)))
cmd.PrintErrln(err)
return
} }
var out io.Writer var out io.Writer
@ -954,8 +832,7 @@ func getObjectRange(cmd *cobra.Command, _ []string) {
} else { } else {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm) f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil { if err != nil {
cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err)) exitOnErr(cmd, fmt.Errorf("can't open file '%s': %w", filename, err))
return
} }
defer f.Close() defer f.Close()
@ -966,16 +843,10 @@ func getObjectRange(cmd *cobra.Command, _ []string) {
ctx := context.Background() ctx := context.Background()
c, sessionToken, err := initSession(ctx, key) c, sessionToken, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
bearerToken, err := getBearerToken(cmd, "bearer") bearerToken, err := getBearerToken(cmd, "bearer")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
raw, _ := cmd.Flags().GetBool(rawFlag) raw, _ := cmd.Flags().GetBool(rawFlag)
@ -995,8 +866,7 @@ func getObjectRange(cmd *cobra.Command, _ []string) {
return return
} }
cmd.PrintErrln(fmt.Errorf("can't get object payload range: %w", err)) exitOnErr(cmd, fmt.Errorf("can't get object payload range: %w", err))
return
} }
if filename != "" { if filename != "" {

View file

@ -63,9 +63,8 @@ var (
// Execute adds all child commands to the root command and sets flags appropriately. // Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd. // This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() { func Execute() {
if err := rootCmd.Execute(); err != nil { err := rootCmd.Execute()
os.Exit(1) exitOnErr(rootCmd, err)
}
} }
func init() { func init() {
@ -136,10 +135,7 @@ func initConfig() {
} else { } else {
// Find home directory. // Find home directory.
home, err := homedir.Dir() home, err := homedir.Dir()
if err != nil { exitOnErr(rootCmd, err)
fmt.Println(err)
os.Exit(1)
}
// Search config in `$HOME/.config/neofs-cli/` with name "config.yaml" // Search config in `$HOME/.config/neofs-cli/` with name "config.yaml"
viper.AddConfigPath(filepath.Join(home, ".config", "neofs-cli")) viper.AddConfigPath(filepath.Join(home, ".config", "neofs-cli"))

View file

@ -3,7 +3,6 @@ package cmd
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"github.com/nspcc-dev/neofs-api-go/pkg/client" "github.com/nspcc-dev/neofs-api-go/pkg/client"
objectSDK "github.com/nspcc-dev/neofs-api-go/pkg/object" objectSDK "github.com/nspcc-dev/neofs-api-go/pkg/object"
@ -129,48 +128,32 @@ func sgBearerToken(cmd *cobra.Command) (*token.BearerToken, error) {
func putSG(cmd *cobra.Command, _ []string) { func putSG(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
ownerID, err := getOwnerID(key) ownerID, err := getOwnerID(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
members := make([]*objectSDK.ID, 0, len(sgMembers)) members := make([]*objectSDK.ID, 0, len(sgMembers))
for i := range sgMembers { for i := range sgMembers {
id := objectSDK.NewID() id := objectSDK.NewID()
if err := id.Parse(sgMembers[i]); err != nil {
cmd.PrintErrln(err) err = id.Parse(sgMembers[i])
return exitOnErr(cmd, err)
}
members = append(members, id) members = append(members, id)
} }
bearerToken, err := sgBearerToken(cmd) bearerToken, err := sgBearerToken(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
sg, err := storagegroup.CollectMembers(&sgHeadReceiver{ sg, err := storagegroup.CollectMembers(&sgHeadReceiver{
ctx: ctx, ctx: ctx,
@ -178,16 +161,10 @@ func putSG(cmd *cobra.Command, _ []string) {
c: cli, c: cli,
bearerToken: bearerToken, bearerToken: bearerToken,
}, cid, members) }, cid, members)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
sgContent, err := sg.Marshal() sgContent, err := sg.Marshal()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
obj := objectSDK.NewRaw() obj := objectSDK.NewRaw()
obj.SetContainerID(cid) obj.SetContainerID(cid)
@ -203,10 +180,7 @@ func putSG(cmd *cobra.Command, _ []string) {
client.WithBearer(bearerToken), client.WithBearer(bearerToken),
)..., )...,
) )
if err != nil { exitOnErr(cmd, errf("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.Println("Storage group successfully stored")
cmd.Printf(" ID: %s\n CID: %s\n", oid, cid) cmd.Printf(" ID: %s\n CID: %s\n", oid, cid)
@ -221,28 +195,16 @@ func getSGID() (*objectSDK.ID, error) {
func getSG(cmd *cobra.Command, _ []string) { func getSG(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
id, err := getSGID() id, err := getSGID()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
bearerToken, err := sgBearerToken(cmd) bearerToken, err := sgBearerToken(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
addr := objectSDK.NewAddress() addr := objectSDK.NewAddress()
addr.SetContainerID(cid) addr.SetContainerID(cid)
@ -251,10 +213,7 @@ func getSG(cmd *cobra.Command, _ []string) {
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
obj, err := cli.GetObject(ctx, obj, err := cli.GetObject(ctx,
new(client.GetObjectParams). new(client.GetObjectParams).
@ -264,16 +223,12 @@ func getSG(cmd *cobra.Command, _ []string) {
client.WithBearer(bearerToken), client.WithBearer(bearerToken),
)..., )...,
) )
if err != nil { exitOnErr(cmd, errf("can't get storage group: %w", err))
cmd.PrintErrln(fmt.Errorf("can't get storage group: %w", err))
return
}
sg := storagegroupAPI.New() sg := storagegroupAPI.New()
if err := sg.Unmarshal(obj.Payload()); err != nil {
cmd.PrintErrln(err) err = sg.Unmarshal(obj.Payload())
return exitOnErr(cmd, err)
}
cmd.Printf("Expiration epoch: %d\n", sg.ExpirationEpoch()) cmd.Printf("Expiration epoch: %d\n", sg.ExpirationEpoch())
cmd.Printf("Group size: %d\n", sg.ValidationDataSize()) cmd.Printf("Group size: %d\n", sg.ValidationDataSize())
@ -290,30 +245,18 @@ func getSG(cmd *cobra.Command, _ []string) {
func listSG(cmd *cobra.Command, _ []string) { func listSG(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
bearerToken, err := sgBearerToken(cmd) bearerToken, err := sgBearerToken(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ids, err := cli.SearchObject(ctx, ids, err := cli.SearchObject(ctx,
new(client.SearchObjectParams). new(client.SearchObjectParams).
@ -324,10 +267,7 @@ func listSG(cmd *cobra.Command, _ []string) {
client.WithBearer(bearerToken), client.WithBearer(bearerToken),
)..., )...,
) )
if err != nil { exitOnErr(cmd, errf("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)) cmd.Printf("Found %d storage groups.\n", len(ids))
@ -338,36 +278,21 @@ func listSG(cmd *cobra.Command, _ []string) {
func delSG(cmd *cobra.Command, _ []string) { func delSG(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("can't fetch private key: %w", err))
cmd.PrintErrln(fmt.Errorf("can't fetch private key: %w", err))
return
}
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
id, err := getSGID() id, err := getSGID()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
bearerToken, err := sgBearerToken(cmd) bearerToken, err := sgBearerToken(cmd)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx, key) cli, tok, err := initSession(ctx, key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
addr := objectSDK.NewAddress() addr := objectSDK.NewAddress()
addr.SetContainerID(cid) addr.SetContainerID(cid)
@ -381,10 +306,7 @@ func delSG(cmd *cobra.Command, _ []string) {
client.WithBearer(bearerToken), client.WithBearer(bearerToken),
)..., )...,
) )
if err != nil { exitOnErr(cmd, errf("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.Println("Storage group removed successfully.")
cmd.Printf(" Tombstone: %s\n", tombstone.ObjectID()) cmd.Printf(" Tombstone: %s\n", tombstone.ObjectID())

View file

@ -118,10 +118,7 @@ var (
}) })
err := targetDB.Open() err := targetDB.Open()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
defer targetDB.Close() defer targetDB.Close()
@ -131,10 +128,7 @@ var (
} }
err = locodedb.FillDatabase(locodeDB, airportDB, continentsDB, names, targetDB) err = locodedb.FillDatabase(locodeDB, airportDB, continentsDB, names, targetDB)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
}, },
} }
) )
@ -157,18 +151,12 @@ var (
}) })
err := targetDB.Open() err := targetDB.Open()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
defer targetDB.Close() defer targetDB.Close()
record, err := locodedb.LocodeRecord(targetDB, locodeInfoCode) record, err := locodedb.LocodeRecord(targetDB, locodeInfoCode)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
cmd.Printf("Country: %s\n", record.CountryName()) cmd.Printf("Country: %s\n", record.CountryName())
cmd.Printf("Location: %s\n", record.LocationName()) cmd.Printf("Location: %s\n", record.LocationName())
@ -255,28 +243,16 @@ func init() {
func signBearerToken(cmd *cobra.Command, _ []string) { func signBearerToken(cmd *cobra.Command, _ []string) {
btok, err := getBearerToken(cmd, "from") btok, err := getBearerToken(cmd, "from")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
err = completeBearerToken(btok) err = completeBearerToken(btok)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
err = btok.SignToken(key) err = btok.SignToken(key)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
to := cmd.Flag("to").Value.String() to := cmd.Flag("to").Value.String()
jsonFlag, _ := cmd.Flags().GetBool("json") jsonFlag, _ := cmd.Flags().GetBool("json")
@ -284,16 +260,10 @@ func signBearerToken(cmd *cobra.Command, _ []string) {
var data []byte var data []byte
if jsonFlag || len(to) == 0 { if jsonFlag || len(to) == 0 {
data, err = btok.MarshalJSON() data, err = btok.MarshalJSON()
if err != nil { exitOnErr(cmd, errf("can't JSON encode bearer token: %w", err))
cmd.PrintErrln(fmt.Errorf("can't JSON encode bearer token: %w", err))
return
}
} else { } else {
data, err = btok.Marshal() data, err = btok.Marshal()
if err != nil { exitOnErr(cmd, errf("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 { if len(to) == 0 {
@ -303,44 +273,28 @@ func signBearerToken(cmd *cobra.Command, _ []string) {
} }
err = os.WriteFile(to, data, 0644) err = os.WriteFile(to, data, 0644)
if err != nil { exitOnErr(cmd, errf("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) cmd.Printf("signed bearer token was successfully dumped to %s\n", to)
} }
func signSessionToken(cmd *cobra.Command, _ []string) { func signSessionToken(cmd *cobra.Command, _ []string) {
path, err := cmd.Flags().GetString("from") path, err := cmd.Flags().GetString("from")
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
stok, err := getSessionToken(path) stok, err := getSessionToken(path)
if err != nil { if err != nil {
cmd.PrintErrln(fmt.Errorf("can't read session token from %s: %w", path, err)) exitOnErr(cmd, fmt.Errorf("can't read session token from %s: %w", path, err))
return
} }
key, err := getKey() key, err := getKey()
if err != nil { exitOnErr(cmd, errf("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) err = stok.Sign(key)
if err != nil { exitOnErr(cmd, errf("can't sign token: %w", err))
cmd.PrintErrln(fmt.Errorf("can't sign token: %w", err))
return
}
data, err := stok.MarshalJSON() data, err := stok.MarshalJSON()
if err != nil { exitOnErr(cmd, errf("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() to := cmd.Flag("to").Value.String()
if len(to) == 0 { if len(to) == 0 {
@ -350,8 +304,7 @@ func signSessionToken(cmd *cobra.Command, _ []string) {
err = os.WriteFile(to, data, 0644) err = os.WriteFile(to, data, 0644)
if err != nil { if err != nil {
cmd.PrintErrln(fmt.Errorf("can't write signed session token to %s: %w", to, err)) exitOnErr(cmd, fmt.Errorf("can't write signed session token to %s: %w", to, err))
return
} }
cmd.Printf("signed session token saved in %s\n", to) cmd.Printf("signed session token saved in %s\n", to)
@ -363,24 +316,15 @@ func convertEACLTable(cmd *cobra.Command, _ []string) {
jsonFlag, _ := cmd.Flags().GetBool("json") jsonFlag, _ := cmd.Flags().GetBool("json")
table, err := parseEACL(pathFrom) table, err := parseEACL(pathFrom)
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
var data []byte var data []byte
if jsonFlag || len(to) == 0 { if jsonFlag || len(to) == 0 {
data, err = table.MarshalJSON() data, err = table.MarshalJSON()
if err != nil { exitOnErr(cmd, errf("can't JSON encode extended ACL table: %w", err))
cmd.PrintErrln(fmt.Errorf("can't JSON encode extended ACL table: %w", err))
return
}
} else { } else {
data, err = table.Marshal() data, err = table.Marshal()
if err != nil { exitOnErr(cmd, errf("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 { if len(to) == 0 {
@ -389,10 +333,7 @@ func convertEACLTable(cmd *cobra.Command, _ []string) {
} }
err = os.WriteFile(to, data, 0644) err = os.WriteFile(to, data, 0644)
if err != nil { exitOnErr(cmd, errf("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) cmd.Printf("extended ACL table was successfully dumped to %s\n", to)
} }
@ -412,8 +353,7 @@ func processKeyer(cmd *cobra.Command, args []string) {
err = result.ParseMultiSig(args) err = result.ParseMultiSig(args)
} else { } else {
if len(args) > 1 { if len(args) > 1 {
cmd.PrintErrln(errKeyerSingleArgument) exitOnErr(cmd, errKeyerSingleArgument)
return
} }
var argument string var argument string
@ -431,10 +371,7 @@ func processKeyer(cmd *cobra.Command, args []string) {
} }
} }
if err != nil { exitOnErr(cmd, err)
cmd.PrintErrln(err)
return
}
result.PrettyPrint(uncompressed, useHex) result.PrettyPrint(uncompressed, useHex)
} }