cli/command: remove some import aliases

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2024-06-09 15:53:08 +02:00
parent 851277f966
commit c481c64922
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
5 changed files with 87 additions and 103 deletions

View File

@ -7,7 +7,7 @@ import (
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
apiclient "github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -38,9 +38,9 @@ func NewNodeCommand(dockerCli command.Cli) *cobra.Command {
// Reference returns the reference of a node. The special value "self" for a node // Reference returns the reference of a node. The special value "self" for a node
// reference is mapped to the current node, hence the node ID is retrieved using // reference is mapped to the current node, hence the node ID is retrieved using
// the `/info` endpoint. // the `/info` endpoint.
func Reference(ctx context.Context, client apiclient.APIClient, ref string) (string, error) { func Reference(ctx context.Context, apiClient client.APIClient, ref string) (string, error) {
if ref == "self" { if ref == "self" {
info, err := client.Info(ctx) info, err := apiClient.Info(ctx)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -48,7 +48,7 @@ func Reference(ctx context.Context, client apiclient.APIClient, ref string) (str
// If there's no node ID in /info, the node probably // If there's no node ID in /info, the node probably
// isn't a manager. Call a swarm-specific endpoint to // isn't a manager. Call a swarm-specific endpoint to
// get a more specific error message. // get a more specific error message.
_, err = client.NodeList(ctx, types.NodeListOptions{}) _, err = apiClient.NodeList(ctx, types.NodeListOptions{})
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -14,7 +14,7 @@ import (
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
apiclient "github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/docker/docker/errdefs" "github.com/docker/docker/errdefs"
) )
@ -89,14 +89,14 @@ func getServicesDeclaredNetworks(serviceConfigs []composetypes.ServiceConfig) ma
return serviceNetworks return serviceNetworks
} }
func validateExternalNetworks(ctx context.Context, client apiclient.NetworkAPIClient, externalNetworks []string) error { func validateExternalNetworks(ctx context.Context, apiClient client.NetworkAPIClient, externalNetworks []string) error {
for _, networkName := range externalNetworks { for _, networkName := range externalNetworks {
if !container.NetworkMode(networkName).IsUserDefined() { if !container.NetworkMode(networkName).IsUserDefined() {
// Networks that are not user defined always exist on all nodes as // Networks that are not user defined always exist on all nodes as
// local-scoped networks, so there's no need to inspect them. // local-scoped networks, so there's no need to inspect them.
continue continue
} }
nw, err := client.NetworkInspect(ctx, networkName, network.InspectOptions{}) nw, err := apiClient.NetworkInspect(ctx, networkName, network.InspectOptions{})
switch { switch {
case errdefs.IsNotFound(err): case errdefs.IsNotFound(err):
return fmt.Errorf("network %q is declared as external, but could not be found. You need to create a swarm-scoped network before the stack is deployed", networkName) return fmt.Errorf("network %q is declared as external, but could not be found. You need to create a swarm-scoped network before the stack is deployed", networkName)
@ -110,20 +110,20 @@ func validateExternalNetworks(ctx context.Context, client apiclient.NetworkAPICl
} }
func createSecrets(ctx context.Context, dockerCli command.Cli, secrets []swarm.SecretSpec) error { func createSecrets(ctx context.Context, dockerCli command.Cli, secrets []swarm.SecretSpec) error {
client := dockerCli.Client() apiClient := dockerCli.Client()
for _, secretSpec := range secrets { for _, secretSpec := range secrets {
secret, _, err := client.SecretInspectWithRaw(ctx, secretSpec.Name) secret, _, err := apiClient.SecretInspectWithRaw(ctx, secretSpec.Name)
switch { switch {
case err == nil: case err == nil:
// secret already exists, then we update that // secret already exists, then we update that
if err := client.SecretUpdate(ctx, secret.ID, secret.Meta.Version, secretSpec); err != nil { if err := apiClient.SecretUpdate(ctx, secret.ID, secret.Meta.Version, secretSpec); err != nil {
return fmt.Errorf("failed to update secret %s: %w", secretSpec.Name, err) return fmt.Errorf("failed to update secret %s: %w", secretSpec.Name, err)
} }
case errdefs.IsNotFound(err): case errdefs.IsNotFound(err):
// secret does not exist, then we create a new one. // secret does not exist, then we create a new one.
fmt.Fprintf(dockerCli.Out(), "Creating secret %s\n", secretSpec.Name) fmt.Fprintf(dockerCli.Out(), "Creating secret %s\n", secretSpec.Name)
if _, err := client.SecretCreate(ctx, secretSpec); err != nil { if _, err := apiClient.SecretCreate(ctx, secretSpec); err != nil {
return fmt.Errorf("failed to create secret %s: %w", secretSpec.Name, err) return fmt.Errorf("failed to create secret %s: %w", secretSpec.Name, err)
} }
default: default:
@ -134,20 +134,20 @@ func createSecrets(ctx context.Context, dockerCli command.Cli, secrets []swarm.S
} }
func createConfigs(ctx context.Context, dockerCli command.Cli, configs []swarm.ConfigSpec) error { func createConfigs(ctx context.Context, dockerCli command.Cli, configs []swarm.ConfigSpec) error {
client := dockerCli.Client() apiClient := dockerCli.Client()
for _, configSpec := range configs { for _, configSpec := range configs {
config, _, err := client.ConfigInspectWithRaw(ctx, configSpec.Name) config, _, err := apiClient.ConfigInspectWithRaw(ctx, configSpec.Name)
switch { switch {
case err == nil: case err == nil:
// config already exists, then we update that // config already exists, then we update that
if err := client.ConfigUpdate(ctx, config.ID, config.Meta.Version, configSpec); err != nil { if err := apiClient.ConfigUpdate(ctx, config.ID, config.Meta.Version, configSpec); err != nil {
return fmt.Errorf("failed to update config %s: %w", configSpec.Name, err) return fmt.Errorf("failed to update config %s: %w", configSpec.Name, err)
} }
case errdefs.IsNotFound(err): case errdefs.IsNotFound(err):
// config does not exist, then we create a new one. // config does not exist, then we create a new one.
fmt.Fprintf(dockerCli.Out(), "Creating config %s\n", configSpec.Name) fmt.Fprintf(dockerCli.Out(), "Creating config %s\n", configSpec.Name)
if _, err := client.ConfigCreate(ctx, configSpec); err != nil { if _, err := apiClient.ConfigCreate(ctx, configSpec); err != nil {
return fmt.Errorf("failed to create config %s: %w", configSpec.Name, err) return fmt.Errorf("failed to create config %s: %w", configSpec.Name, err)
} }
default: default:
@ -158,9 +158,9 @@ func createConfigs(ctx context.Context, dockerCli command.Cli, configs []swarm.C
} }
func createNetworks(ctx context.Context, dockerCli command.Cli, namespace convert.Namespace, networks map[string]network.CreateOptions) error { func createNetworks(ctx context.Context, dockerCli command.Cli, namespace convert.Namespace, networks map[string]network.CreateOptions) error {
client := dockerCli.Client() apiClient := dockerCli.Client()
existingNetworks, err := getStackNetworks(ctx, client, namespace.Name()) existingNetworks, err := getStackNetworks(ctx, apiClient, namespace.Name())
if err != nil { if err != nil {
return err return err
} }
@ -180,7 +180,7 @@ func createNetworks(ctx context.Context, dockerCli command.Cli, namespace conver
} }
fmt.Fprintf(dockerCli.Out(), "Creating network %s\n", name) fmt.Fprintf(dockerCli.Out(), "Creating network %s\n", name)
if _, err := client.NetworkCreate(ctx, name, createOpts); err != nil { if _, err := apiClient.NetworkCreate(ctx, name, createOpts); err != nil {
return fmt.Errorf("failed to create network %s: %w", name, err) return fmt.Errorf("failed to create network %s: %w", name, err)
} }
} }

View File

@ -11,37 +11,37 @@ import (
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/api/types/versions" "github.com/docker/docker/api/types/versions"
apiclient "github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
// RunRemove is the swarm implementation of docker stack remove // RunRemove is the swarm implementation of docker stack remove
func RunRemove(ctx context.Context, dockerCli command.Cli, opts options.Remove) error { func RunRemove(ctx context.Context, dockerCli command.Cli, opts options.Remove) error {
client := dockerCli.Client() apiClient := dockerCli.Client()
var errs []string var errs []string
for _, namespace := range opts.Namespaces { for _, namespace := range opts.Namespaces {
services, err := getStackServices(ctx, client, namespace) services, err := getStackServices(ctx, apiClient, namespace)
if err != nil { if err != nil {
return err return err
} }
networks, err := getStackNetworks(ctx, client, namespace) networks, err := getStackNetworks(ctx, apiClient, namespace)
if err != nil { if err != nil {
return err return err
} }
var secrets []swarm.Secret var secrets []swarm.Secret
if versions.GreaterThanOrEqualTo(client.ClientVersion(), "1.25") { if versions.GreaterThanOrEqualTo(apiClient.ClientVersion(), "1.25") {
secrets, err = getStackSecrets(ctx, client, namespace) secrets, err = getStackSecrets(ctx, apiClient, namespace)
if err != nil { if err != nil {
return err return err
} }
} }
var configs []swarm.Config var configs []swarm.Config
if versions.GreaterThanOrEqualTo(client.ClientVersion(), "1.30") { if versions.GreaterThanOrEqualTo(apiClient.ClientVersion(), "1.30") {
configs, err = getStackConfigs(ctx, client, namespace) configs, err = getStackConfigs(ctx, apiClient, namespace)
if err != nil { if err != nil {
return err return err
} }
@ -63,7 +63,7 @@ func RunRemove(ctx context.Context, dockerCli command.Cli, opts options.Remove)
} }
if !opts.Detach { if !opts.Detach {
err = waitOnTasks(ctx, client, namespace) err = waitOnTasks(ctx, apiClient, namespace)
if err != nil { if err != nil {
errs = append(errs, fmt.Sprintf("Failed to wait on tasks of stack: %s: %s", namespace, err)) errs = append(errs, fmt.Sprintf("Failed to wait on tasks of stack: %s: %s", namespace, err))
} }
@ -82,11 +82,7 @@ func sortServiceByName(services []swarm.Service) func(i, j int) bool {
} }
} }
func removeServices( func removeServices(ctx context.Context, dockerCli command.Cli, services []swarm.Service) bool {
ctx context.Context,
dockerCli command.Cli,
services []swarm.Service,
) bool {
var hasError bool var hasError bool
sort.Slice(services, sortServiceByName(services)) sort.Slice(services, sortServiceByName(services))
for _, service := range services { for _, service := range services {
@ -99,11 +95,7 @@ func removeServices(
return hasError return hasError
} }
func removeNetworks( func removeNetworks(ctx context.Context, dockerCli command.Cli, networks []network.Summary) bool {
ctx context.Context,
dockerCli command.Cli,
networks []network.Summary,
) bool {
var hasError bool var hasError bool
for _, nw := range networks { for _, nw := range networks {
fmt.Fprintf(dockerCli.Out(), "Removing network %s\n", nw.Name) fmt.Fprintf(dockerCli.Out(), "Removing network %s\n", nw.Name)
@ -115,11 +107,7 @@ func removeNetworks(
return hasError return hasError
} }
func removeSecrets( func removeSecrets(ctx context.Context, dockerCli command.Cli, secrets []swarm.Secret) bool {
ctx context.Context,
dockerCli command.Cli,
secrets []swarm.Secret,
) bool {
var hasError bool var hasError bool
for _, secret := range secrets { for _, secret := range secrets {
fmt.Fprintf(dockerCli.Out(), "Removing secret %s\n", secret.Spec.Name) fmt.Fprintf(dockerCli.Out(), "Removing secret %s\n", secret.Spec.Name)
@ -131,11 +119,7 @@ func removeSecrets(
return hasError return hasError
} }
func removeConfigs( func removeConfigs(ctx context.Context, dockerCli command.Cli, configs []swarm.Config) bool {
ctx context.Context,
dockerCli command.Cli,
configs []swarm.Config,
) bool {
var hasError bool var hasError bool
for _, config := range configs { for _, config := range configs {
fmt.Fprintf(dockerCli.Out(), "Removing config %s\n", config.Spec.Name) fmt.Fprintf(dockerCli.Out(), "Removing config %s\n", config.Spec.Name)
@ -167,10 +151,10 @@ func terminalState(state swarm.TaskState) bool {
return numberedStates[state] > numberedStates[swarm.TaskStateRunning] return numberedStates[state] > numberedStates[swarm.TaskStateRunning]
} }
func waitOnTasks(ctx context.Context, client apiclient.APIClient, namespace string) error { func waitOnTasks(ctx context.Context, apiClient client.APIClient, namespace string) error {
terminalStatesReached := 0 terminalStatesReached := 0
for { for {
tasks, err := getStackTasks(ctx, client, namespace) tasks, err := getStackTasks(ctx, apiClient, namespace)
if err != nil { if err != nil {
return fmt.Errorf("failed to get tasks: %w", err) return fmt.Errorf("failed to get tasks: %w", err)
} }

View File

@ -13,9 +13,9 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/system" "github.com/docker/docker/api/types/system"
apiclient "github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/theupdateframework/notary" "github.com/theupdateframework/notary"
"github.com/theupdateframework/notary/client" notaryclient "github.com/theupdateframework/notary/client"
"github.com/theupdateframework/notary/tuf/data" "github.com/theupdateframework/notary/tuf/data"
"github.com/theupdateframework/notary/tuf/utils" "github.com/theupdateframework/notary/tuf/utils"
"gotest.tools/v3/assert" "gotest.tools/v3/assert"
@ -26,7 +26,7 @@ import (
// TODO(n4ss): remove common tests with the regular inspect command // TODO(n4ss): remove common tests with the regular inspect command
type fakeClient struct { type fakeClient struct {
apiclient.Client client.Client
} }
func (c *fakeClient) Info(context.Context) (system.Info, error) { func (c *fakeClient) Info(context.Context) (system.Info, error) {
@ -212,7 +212,7 @@ func mockDelegationRoleWithName(name string) data.DelegationRole {
func TestMatchEmptySignatures(t *testing.T) { func TestMatchEmptySignatures(t *testing.T) {
// first try empty targets // first try empty targets
emptyTgts := []client.TargetSignedStruct{} emptyTgts := []notaryclient.TargetSignedStruct{}
matchedSigRows := matchReleasedSignatures(emptyTgts) matchedSigRows := matchReleasedSignatures(emptyTgts)
assert.Check(t, is.Len(matchedSigRows, 0)) assert.Check(t, is.Len(matchedSigRows, 0))
@ -220,11 +220,11 @@ func TestMatchEmptySignatures(t *testing.T) {
func TestMatchUnreleasedSignatures(t *testing.T) { func TestMatchUnreleasedSignatures(t *testing.T) {
// try an "unreleased" target with 3 signatures, 0 rows will appear // try an "unreleased" target with 3 signatures, 0 rows will appear
unreleasedTgts := []client.TargetSignedStruct{} unreleasedTgts := []notaryclient.TargetSignedStruct{}
tgt := client.Target{Name: "unreleased", Hashes: data.Hashes{notary.SHA256: []byte("hash")}} tgt := notaryclient.Target{Name: "unreleased", Hashes: data.Hashes{notary.SHA256: []byte("hash")}}
for _, unreleasedRole := range []string{"targets/a", "targets/b", "targets/c"} { for _, unreleasedRole := range []string{"targets/a", "targets/b", "targets/c"} {
unreleasedTgts = append(unreleasedTgts, client.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: tgt}) unreleasedTgts = append(unreleasedTgts, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: tgt})
} }
matchedSigRows := matchReleasedSignatures(unreleasedTgts) matchedSigRows := matchReleasedSignatures(unreleasedTgts)
@ -233,16 +233,16 @@ func TestMatchUnreleasedSignatures(t *testing.T) {
func TestMatchOneReleasedSingleSignature(t *testing.T) { func TestMatchOneReleasedSingleSignature(t *testing.T) {
// now try only 1 "released" target with no additional sigs, 1 row will appear with 0 signers // now try only 1 "released" target with no additional sigs, 1 row will appear with 0 signers
oneReleasedTgt := []client.TargetSignedStruct{} oneReleasedTgt := []notaryclient.TargetSignedStruct{}
// make and append the "released" target to our mock input // make and append the "released" target to our mock input
releasedTgt := client.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}} releasedTgt := notaryclient.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}}
oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: releasedTgt}) oneReleasedTgt = append(oneReleasedTgt, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: releasedTgt})
// make and append 3 non-released signatures on the "unreleased" target // make and append 3 non-released signatures on the "unreleased" target
unreleasedTgt := client.Target{Name: "unreleased", Hashes: data.Hashes{notary.SHA256: []byte("hash")}} unreleasedTgt := notaryclient.Target{Name: "unreleased", Hashes: data.Hashes{notary.SHA256: []byte("hash")}}
for _, unreleasedRole := range []string{"targets/a", "targets/b", "targets/c"} { for _, unreleasedRole := range []string{"targets/a", "targets/b", "targets/c"} {
oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: unreleasedTgt}) oneReleasedTgt = append(oneReleasedTgt, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: unreleasedTgt})
} }
matchedSigRows := matchReleasedSignatures(oneReleasedTgt) matchedSigRows := matchReleasedSignatures(oneReleasedTgt)
@ -257,17 +257,17 @@ func TestMatchOneReleasedSingleSignature(t *testing.T) {
func TestMatchOneReleasedMultiSignature(t *testing.T) { func TestMatchOneReleasedMultiSignature(t *testing.T) {
// now try only 1 "released" target with 3 additional sigs, 1 row will appear with 3 signers // now try only 1 "released" target with 3 additional sigs, 1 row will appear with 3 signers
oneReleasedTgt := []client.TargetSignedStruct{} oneReleasedTgt := []notaryclient.TargetSignedStruct{}
// make and append the "released" target to our mock input // make and append the "released" target to our mock input
releasedTgt := client.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}} releasedTgt := notaryclient.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}}
oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: releasedTgt}) oneReleasedTgt = append(oneReleasedTgt, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: releasedTgt})
// make and append 3 non-released signatures on both the "released" and "unreleased" targets // make and append 3 non-released signatures on both the "released" and "unreleased" targets
unreleasedTgt := client.Target{Name: "unreleased", Hashes: data.Hashes{notary.SHA256: []byte("hash")}} unreleasedTgt := notaryclient.Target{Name: "unreleased", Hashes: data.Hashes{notary.SHA256: []byte("hash")}}
for _, unreleasedRole := range []string{"targets/a", "targets/b", "targets/c"} { for _, unreleasedRole := range []string{"targets/a", "targets/b", "targets/c"} {
oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: unreleasedTgt}) oneReleasedTgt = append(oneReleasedTgt, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: unreleasedTgt})
oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: releasedTgt}) oneReleasedTgt = append(oneReleasedTgt, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: releasedTgt})
} }
matchedSigRows := matchReleasedSignatures(oneReleasedTgt) matchedSigRows := matchReleasedSignatures(oneReleasedTgt)
@ -285,29 +285,29 @@ func TestMatchMultiReleasedMultiSignature(t *testing.T) {
// target-a is signed by targets/releases and targets/a - a will be the signer // target-a is signed by targets/releases and targets/a - a will be the signer
// target-b is signed by targets/releases, targets/a, targets/b - a and b will be the signers // target-b is signed by targets/releases, targets/a, targets/b - a and b will be the signers
// target-c is signed by targets/releases, targets/a, targets/b, targets/c - a, b, and c will be the signers // target-c is signed by targets/releases, targets/a, targets/b, targets/c - a, b, and c will be the signers
multiReleasedTgts := []client.TargetSignedStruct{} multiReleasedTgts := []notaryclient.TargetSignedStruct{}
// make target-a, target-b, and target-c // make target-a, target-b, and target-c
targetA := client.Target{Name: "target-a", Hashes: data.Hashes{notary.SHA256: []byte("target-a-hash")}} targetA := notaryclient.Target{Name: "target-a", Hashes: data.Hashes{notary.SHA256: []byte("target-a-hash")}}
targetB := client.Target{Name: "target-b", Hashes: data.Hashes{notary.SHA256: []byte("target-b-hash")}} targetB := notaryclient.Target{Name: "target-b", Hashes: data.Hashes{notary.SHA256: []byte("target-b-hash")}}
targetC := client.Target{Name: "target-c", Hashes: data.Hashes{notary.SHA256: []byte("target-c-hash")}} targetC := notaryclient.Target{Name: "target-c", Hashes: data.Hashes{notary.SHA256: []byte("target-c-hash")}}
// have targets/releases "sign" on all of these targets so they are released // have targets/releases "sign" on all of these targets so they are released
multiReleasedTgts = append(multiReleasedTgts, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: targetA}) multiReleasedTgts = append(multiReleasedTgts, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: targetA})
multiReleasedTgts = append(multiReleasedTgts, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: targetB}) multiReleasedTgts = append(multiReleasedTgts, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: targetB})
multiReleasedTgts = append(multiReleasedTgts, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: targetC}) multiReleasedTgts = append(multiReleasedTgts, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: targetC})
// targets/a signs off on all three targets (target-a, target-b, target-c): // targets/a signs off on all three targets (target-a, target-b, target-c):
for _, tgt := range []client.Target{targetA, targetB, targetC} { for _, tgt := range []notaryclient.Target{targetA, targetB, targetC} {
multiReleasedTgts = append(multiReleasedTgts, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/a"), Target: tgt}) multiReleasedTgts = append(multiReleasedTgts, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/a"), Target: tgt})
} }
// targets/b signs off on the final two targets (target-b, target-c): // targets/b signs off on the final two targets (target-b, target-c):
for _, tgt := range []client.Target{targetB, targetC} { for _, tgt := range []notaryclient.Target{targetB, targetC} {
multiReleasedTgts = append(multiReleasedTgts, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/b"), Target: tgt}) multiReleasedTgts = append(multiReleasedTgts, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/b"), Target: tgt})
} }
// targets/c only signs off on the last target (target-c): // targets/c only signs off on the last target (target-c):
multiReleasedTgts = append(multiReleasedTgts, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/c"), Target: targetC}) multiReleasedTgts = append(multiReleasedTgts, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/c"), Target: targetC})
matchedSigRows := matchReleasedSignatures(multiReleasedTgts) matchedSigRows := matchReleasedSignatures(multiReleasedTgts)
assert.Check(t, is.Len(matchedSigRows, 3)) assert.Check(t, is.Len(matchedSigRows, 3))
@ -331,10 +331,10 @@ func TestMatchMultiReleasedMultiSignature(t *testing.T) {
func TestMatchReleasedSignatureFromTargets(t *testing.T) { func TestMatchReleasedSignatureFromTargets(t *testing.T) {
// now try only 1 "released" target with no additional sigs, one rows will appear // now try only 1 "released" target with no additional sigs, one rows will appear
oneReleasedTgt := []client.TargetSignedStruct{} oneReleasedTgt := []notaryclient.TargetSignedStruct{}
// make and append the "released" target to our mock input // make and append the "released" target to our mock input
releasedTgt := client.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}} releasedTgt := notaryclient.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}}
oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName(data.CanonicalTargetsRole.String()), Target: releasedTgt}) oneReleasedTgt = append(oneReleasedTgt, notaryclient.TargetSignedStruct{Role: mockDelegationRoleWithName(data.CanonicalTargetsRole.String()), Target: releasedTgt})
matchedSigRows := matchReleasedSignatures(oneReleasedTgt) matchedSigRows := matchReleasedSignatures(oneReleasedTgt)
assert.Check(t, is.Len(matchedSigRows, 1)) assert.Check(t, is.Len(matchedSigRows, 1))
outputRow := matchedSigRows[0] outputRow := matchedSigRows[0]
@ -405,7 +405,7 @@ func TestFormatAdminRole(t *testing.T) {
}, },
Name: "targets/alice", Name: "targets/alice",
} }
aliceRoleWithSigs := client.RoleWithSignatures{Role: aliceRole, Signatures: nil} aliceRoleWithSigs := notaryclient.RoleWithSignatures{Role: aliceRole, Signatures: nil}
assert.Check(t, is.Equal("", formatAdminRole(aliceRoleWithSigs))) assert.Check(t, is.Equal("", formatAdminRole(aliceRoleWithSigs)))
releasesRole := data.Role{ releasesRole := data.Role{
@ -414,7 +414,7 @@ func TestFormatAdminRole(t *testing.T) {
}, },
Name: "targets/releases", Name: "targets/releases",
} }
releasesRoleWithSigs := client.RoleWithSignatures{Role: releasesRole, Signatures: nil} releasesRoleWithSigs := notaryclient.RoleWithSignatures{Role: releasesRole, Signatures: nil}
assert.Check(t, is.Equal("", formatAdminRole(releasesRoleWithSigs))) assert.Check(t, is.Equal("", formatAdminRole(releasesRoleWithSigs)))
timestampRole := data.Role{ timestampRole := data.Role{
@ -423,7 +423,7 @@ func TestFormatAdminRole(t *testing.T) {
}, },
Name: data.CanonicalTimestampRole, Name: data.CanonicalTimestampRole,
} }
timestampRoleWithSigs := client.RoleWithSignatures{Role: timestampRole, Signatures: nil} timestampRoleWithSigs := notaryclient.RoleWithSignatures{Role: timestampRole, Signatures: nil}
assert.Check(t, is.Equal("", formatAdminRole(timestampRoleWithSigs))) assert.Check(t, is.Equal("", formatAdminRole(timestampRoleWithSigs)))
snapshotRole := data.Role{ snapshotRole := data.Role{
@ -432,7 +432,7 @@ func TestFormatAdminRole(t *testing.T) {
}, },
Name: data.CanonicalSnapshotRole, Name: data.CanonicalSnapshotRole,
} }
snapshotRoleWithSigs := client.RoleWithSignatures{Role: snapshotRole, Signatures: nil} snapshotRoleWithSigs := notaryclient.RoleWithSignatures{Role: snapshotRole, Signatures: nil}
assert.Check(t, is.Equal("", formatAdminRole(snapshotRoleWithSigs))) assert.Check(t, is.Equal("", formatAdminRole(snapshotRoleWithSigs)))
rootRole := data.Role{ rootRole := data.Role{
@ -441,7 +441,7 @@ func TestFormatAdminRole(t *testing.T) {
}, },
Name: data.CanonicalRootRole, Name: data.CanonicalRootRole,
} }
rootRoleWithSigs := client.RoleWithSignatures{Role: rootRole, Signatures: nil} rootRoleWithSigs := notaryclient.RoleWithSignatures{Role: rootRole, Signatures: nil}
assert.Check(t, is.Equal("Root Key:\tkey11\n", formatAdminRole(rootRoleWithSigs))) assert.Check(t, is.Equal("Root Key:\tkey11\n", formatAdminRole(rootRoleWithSigs)))
targetsRole := data.Role{ targetsRole := data.Role{
@ -450,7 +450,7 @@ func TestFormatAdminRole(t *testing.T) {
}, },
Name: data.CanonicalTargetsRole, Name: data.CanonicalTargetsRole,
} }
targetsRoleWithSigs := client.RoleWithSignatures{Role: targetsRole, Signatures: nil} targetsRoleWithSigs := notaryclient.RoleWithSignatures{Role: targetsRole, Signatures: nil}
assert.Check(t, is.Equal("Repository Key:\tabc, key11, key99\n", formatAdminRole(targetsRoleWithSigs))) assert.Check(t, is.Equal("Repository Key:\tabc, key11, key99\n", formatAdminRole(targetsRoleWithSigs)))
} }

View File

@ -14,10 +14,10 @@ import (
"github.com/docker/cli/cli/trust" "github.com/docker/cli/cli/trust"
imagetypes "github.com/docker/docker/api/types/image" imagetypes "github.com/docker/docker/api/types/image"
registrytypes "github.com/docker/docker/api/types/registry" registrytypes "github.com/docker/docker/api/types/registry"
apiclient "github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/theupdateframework/notary/client" notaryclient "github.com/theupdateframework/notary/client"
"github.com/theupdateframework/notary/tuf/data" "github.com/theupdateframework/notary/tuf/data"
) )
@ -64,7 +64,7 @@ func runSignImage(ctx context.Context, dockerCLI command.Cli, options signOption
// get the latest repository metadata so we can figure out which roles to sign // get the latest repository metadata so we can figure out which roles to sign
if _, err = notaryRepo.ListTargets(); err != nil { if _, err = notaryRepo.ListTargets(); err != nil {
switch err.(type) { switch err.(type) {
case client.ErrRepoNotInitialized, client.ErrRepositoryNotExist: case notaryclient.ErrRepoNotInitialized, notaryclient.ErrRepositoryNotExist:
// before initializing a new repo, check that the image exists locally: // before initializing a new repo, check that the image exists locally:
if err := checkLocalImageExistence(ctx, dockerCLI.Client(), imageName); err != nil { if err := checkLocalImageExistence(ctx, dockerCLI.Client(), imageName); err != nil {
return err return err
@ -86,7 +86,7 @@ func runSignImage(ctx context.Context, dockerCLI command.Cli, options signOption
if err != nil || options.local { if err != nil || options.local {
switch err := err.(type) { switch err := err.(type) {
// If the error is nil then the local flag is set // If the error is nil then the local flag is set
case client.ErrNoSuchTarget, client.ErrRepositoryNotExist, nil: case notaryclient.ErrNoSuchTarget, notaryclient.ErrRepositoryNotExist, nil:
// Fail fast if the image doesn't exist locally // Fail fast if the image doesn't exist locally
if err := checkLocalImageExistence(ctx, dockerCLI.Client(), imageName); err != nil { if err := checkLocalImageExistence(ctx, dockerCLI.Client(), imageName); err != nil {
return err return err
@ -110,7 +110,7 @@ func runSignImage(ctx context.Context, dockerCLI command.Cli, options signOption
return signAndPublishToTarget(dockerCLI.Out(), imgRefAndAuth, notaryRepo, target) return signAndPublishToTarget(dockerCLI.Out(), imgRefAndAuth, notaryRepo, target)
} }
func signAndPublishToTarget(out io.Writer, imgRefAndAuth trust.ImageRefAndAuth, notaryRepo client.Repository, target client.Target) error { func signAndPublishToTarget(out io.Writer, imgRefAndAuth trust.ImageRefAndAuth, notaryRepo notaryclient.Repository, target notaryclient.Target) error {
tag := imgRefAndAuth.Tag() tag := imgRefAndAuth.Tag()
fmt.Fprintf(out, "Signing and pushing trust metadata for %s\n", imgRefAndAuth.Name()) fmt.Fprintf(out, "Signing and pushing trust metadata for %s\n", imgRefAndAuth.Name())
existingSigInfo, err := getExistingSignatureInfoForReleasedTag(notaryRepo, tag) existingSigInfo, err := getExistingSignatureInfoForReleasedTag(notaryRepo, tag)
@ -140,13 +140,13 @@ func validateTag(imgRefAndAuth trust.ImageRefAndAuth) error {
return nil return nil
} }
func checkLocalImageExistence(ctx context.Context, apiClient apiclient.APIClient, imageName string) error { func checkLocalImageExistence(ctx context.Context, apiClient client.APIClient, imageName string) error {
_, _, err := apiClient.ImageInspectWithRaw(ctx, imageName) _, _, err := apiClient.ImageInspectWithRaw(ctx, imageName)
return err return err
} }
func createTarget(notaryRepo client.Repository, tag string) (client.Target, error) { func createTarget(notaryRepo notaryclient.Repository, tag string) (notaryclient.Target, error) {
target := &client.Target{} target := &notaryclient.Target{}
var err error var err error
if tag == "" { if tag == "" {
return *target, errors.New("no tag specified") return *target, errors.New("no tag specified")
@ -156,7 +156,7 @@ func createTarget(notaryRepo client.Repository, tag string) (client.Target, erro
return *target, err return *target, err
} }
func getSignedManifestHashAndSize(notaryRepo client.Repository, tag string) (data.Hashes, int64, error) { func getSignedManifestHashAndSize(notaryRepo notaryclient.Repository, tag string) (data.Hashes, int64, error) {
targets, err := notaryRepo.GetAllTargetMetadataByName(tag) targets, err := notaryRepo.GetAllTargetMetadataByName(tag)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
@ -164,16 +164,16 @@ func getSignedManifestHashAndSize(notaryRepo client.Repository, tag string) (dat
return getReleasedTargetHashAndSize(targets, tag) return getReleasedTargetHashAndSize(targets, tag)
} }
func getReleasedTargetHashAndSize(targets []client.TargetSignedStruct, tag string) (data.Hashes, int64, error) { func getReleasedTargetHashAndSize(targets []notaryclient.TargetSignedStruct, tag string) (data.Hashes, int64, error) {
for _, tgt := range targets { for _, tgt := range targets {
if isReleasedTarget(tgt.Role.Name) { if isReleasedTarget(tgt.Role.Name) {
return tgt.Target.Hashes, tgt.Target.Length, nil return tgt.Target.Hashes, tgt.Target.Length, nil
} }
} }
return nil, 0, client.ErrNoSuchTarget(tag) return nil, 0, notaryclient.ErrNoSuchTarget(tag)
} }
func getExistingSignatureInfoForReleasedTag(notaryRepo client.Repository, tag string) (trustTagRow, error) { func getExistingSignatureInfoForReleasedTag(notaryRepo notaryclient.Repository, tag string) (trustTagRow, error) {
targets, err := notaryRepo.GetAllTargetMetadataByName(tag) targets, err := notaryRepo.GetAllTargetMetadataByName(tag)
if err != nil { if err != nil {
return trustTagRow{}, err return trustTagRow{}, err
@ -191,7 +191,7 @@ func prettyPrintExistingSignatureInfo(out io.Writer, existingSigInfo trustTagRow
fmt.Fprintf(out, "Existing signatures for tag %s digest %s from:\n%s\n", existingSigInfo.SignedTag, existingSigInfo.Digest, joinedSigners) fmt.Fprintf(out, "Existing signatures for tag %s digest %s from:\n%s\n", existingSigInfo.SignedTag, existingSigInfo.Digest, joinedSigners)
} }
func initNotaryRepoWithSigners(notaryRepo client.Repository, newSigner data.RoleName) error { func initNotaryRepoWithSigners(notaryRepo notaryclient.Repository, newSigner data.RoleName) error {
rootKey, err := getOrGenerateNotaryKey(notaryRepo, data.CanonicalRootRole) rootKey, err := getOrGenerateNotaryKey(notaryRepo, data.CanonicalRootRole)
if err != nil { if err != nil {
return err return err
@ -215,7 +215,7 @@ func initNotaryRepoWithSigners(notaryRepo client.Repository, newSigner data.Role
} }
// generates an ECDSA key without a GUN for the specified role // generates an ECDSA key without a GUN for the specified role
func getOrGenerateNotaryKey(notaryRepo client.Repository, role data.RoleName) (data.PublicKey, error) { func getOrGenerateNotaryKey(notaryRepo notaryclient.Repository, role data.RoleName) (data.PublicKey, error) {
// use the signer name in the PEM headers if this is a delegation key // use the signer name in the PEM headers if this is a delegation key
if data.IsDelegation(role) { if data.IsDelegation(role) {
role = data.RoleName(notaryRoleToSigner(role)) role = data.RoleName(notaryRoleToSigner(role))
@ -242,7 +242,7 @@ func getOrGenerateNotaryKey(notaryRepo client.Repository, role data.RoleName) (d
} }
// stages changes to add a signer with the specified name and key(s). Adds to targets/<name> and targets/releases // stages changes to add a signer with the specified name and key(s). Adds to targets/<name> and targets/releases
func addStagedSigner(notaryRepo client.Repository, newSigner data.RoleName, signerKeys []data.PublicKey) error { func addStagedSigner(notaryRepo notaryclient.Repository, newSigner data.RoleName, signerKeys []data.PublicKey) error {
// create targets/<username> // create targets/<username>
if err := notaryRepo.AddDelegationRoleAndKeys(newSigner, signerKeys); err != nil { if err := notaryRepo.AddDelegationRoleAndKeys(newSigner, signerKeys); err != nil {
return err return err