diff --git a/api/ca.pb.go b/api/ca.pb.go index caaa06cc83..42d7149f28 100644 --- a/api/ca.pb.go +++ b/api/ca.pb.go @@ -235,6 +235,7 @@ import ( import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -984,12 +985,12 @@ func NewRaftProxyCAServer(local CAServer, connSelector raftselector.ConnProvider redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) @@ -1126,12 +1127,12 @@ func NewRaftProxyNodeCAServer(local NodeCAServer, connSelector raftselector.Conn redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/api/control.pb.go b/api/control.pb.go index 13ef4822cb..fb28c5d330 100644 --- a/api/control.pb.go +++ b/api/control.pb.go @@ -19,6 +19,7 @@ import ( import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -5859,12 +5860,12 @@ func NewRaftProxyControlServer(local ControlServer, connSelector raftselector.Co redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/api/dispatcher.pb.go b/api/dispatcher.pb.go index 8e9b038cad..120df8811f 100644 --- a/api/dispatcher.pb.go +++ b/api/dispatcher.pb.go @@ -24,6 +24,7 @@ import github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -1602,12 +1603,12 @@ func NewRaftProxyDispatcherServer(local DispatcherServer, connSelector raftselec redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/api/health.pb.go b/api/health.pb.go index 757db6acbf..ed7df73054 100644 --- a/api/health.pb.go +++ b/api/health.pb.go @@ -17,6 +17,7 @@ import ( import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -286,12 +287,12 @@ func NewRaftProxyHealthServer(local HealthServer, connSelector raftselector.Conn redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/api/logbroker.pb.go b/api/logbroker.pb.go index 58515aa11e..1108088fba 100644 --- a/api/logbroker.pb.go +++ b/api/logbroker.pb.go @@ -20,6 +20,7 @@ import ( import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -1273,12 +1274,12 @@ func NewRaftProxyLogsServer(local LogsServer, connSelector raftselector.ConnProv redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) @@ -1396,12 +1397,12 @@ func NewRaftProxyLogBrokerServer(local LogBrokerServer, connSelector raftselecto redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/api/raft.pb.go b/api/raft.pb.go index 4710ee6b01..1d72a7d84d 100644 --- a/api/raft.pb.go +++ b/api/raft.pb.go @@ -21,6 +21,7 @@ import ( import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -1488,12 +1489,12 @@ func NewRaftProxyRaftServer(local RaftServer, connSelector raftselector.ConnProv redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) @@ -1630,12 +1631,12 @@ func NewRaftProxyRaftMembershipServer(local RaftMembershipServer, connSelector r redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/api/resource.pb.go b/api/resource.pb.go index ead5d27ef4..d4e27f3362 100644 --- a/api/resource.pb.go +++ b/api/resource.pb.go @@ -19,6 +19,7 @@ import ( import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -403,12 +404,12 @@ func NewRaftProxyResourceAllocatorServer(local ResourceAllocatorServer, connSele redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/api/watch.pb.go b/api/watch.pb.go index 58fa8917e5..78f0014c7a 100644 --- a/api/watch.pb.go +++ b/api/watch.pb.go @@ -19,6 +19,7 @@ import ( import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -2043,12 +2044,12 @@ func NewRaftProxyWatchServer(local WatchServer, connSelector raftselector.ConnPr redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/ca/auth.go b/ca/auth.go index 488d34dd33..df4547fb13 100644 --- a/ca/auth.go +++ b/ca/auth.go @@ -10,10 +10,10 @@ import ( "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/log" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/peer" + "google.golang.org/grpc/status" ) type localRequestKeyType struct{} @@ -52,13 +52,13 @@ func LogTLSState(ctx context.Context, tlsState *tls.ConnectionState) { // getCertificateSubject extracts the subject from a verified client certificate func getCertificateSubject(tlsState *tls.ConnectionState) (pkix.Name, error) { if tlsState == nil { - return pkix.Name{}, grpc.Errorf(codes.PermissionDenied, "request is not using TLS") + return pkix.Name{}, status.Errorf(codes.PermissionDenied, "request is not using TLS") } if len(tlsState.PeerCertificates) == 0 { - return pkix.Name{}, grpc.Errorf(codes.PermissionDenied, "no client certificates in request") + return pkix.Name{}, status.Errorf(codes.PermissionDenied, "no client certificates in request") } if len(tlsState.VerifiedChains) == 0 { - return pkix.Name{}, grpc.Errorf(codes.PermissionDenied, "no verified chains for remote certificate") + return pkix.Name{}, status.Errorf(codes.PermissionDenied, "no verified chains for remote certificate") } return tlsState.VerifiedChains[0][0].Subject, nil @@ -67,11 +67,11 @@ func getCertificateSubject(tlsState *tls.ConnectionState) (pkix.Name, error) { func tlsConnStateFromContext(ctx context.Context) (*tls.ConnectionState, error) { peer, ok := peer.FromContext(ctx) if !ok { - return nil, grpc.Errorf(codes.PermissionDenied, "Permission denied: no peer info") + return nil, status.Errorf(codes.PermissionDenied, "Permission denied: no peer info") } tlsInfo, ok := peer.AuthInfo.(credentials.TLSInfo) if !ok { - return nil, grpc.Errorf(codes.PermissionDenied, "Permission denied: peer didn't not present valid peer certificate") + return nil, status.Errorf(codes.PermissionDenied, "Permission denied: peer didn't not present valid peer certificate") } return &tlsInfo.State, nil } @@ -98,21 +98,21 @@ func AuthorizeOrgAndRole(ctx context.Context, org string, blacklistedCerts map[s return authorizeOrg(certSubj, org, blacklistedCerts) } - return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of OUs: %v", ou) + return "", status.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of OUs: %v", ou) } // authorizeOrg takes in a certificate subject and an organization, and returns // the Node ID of the node. func authorizeOrg(certSubj pkix.Name, org string, blacklistedCerts map[string]*api.BlacklistedCertificate) (string, error) { if _, ok := blacklistedCerts[certSubj.CommonName]; ok { - return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: node %s was removed from swarm", certSubj.CommonName) + return "", status.Errorf(codes.PermissionDenied, "Permission denied: node %s was removed from swarm", certSubj.CommonName) } if len(certSubj.Organization) > 0 && certSubj.Organization[0] == org { return certSubj.CommonName, nil } - return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of organization: %s", org) + return "", status.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of organization: %s", org) } // AuthorizeForwardedRoleAndOrg checks for proper roles and organization of caller. The RPC may have @@ -123,7 +123,7 @@ func AuthorizeForwardedRoleAndOrg(ctx context.Context, authorizedRoles, forwarde if isForwardedRequest(ctx) { _, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, forwarderRoles...) if err != nil { - return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarder role: %v", err) + return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarder role: %v", err) } // This was a forwarded request. Authorize the forwarder, and @@ -132,15 +132,15 @@ func AuthorizeForwardedRoleAndOrg(ctx context.Context, authorizedRoles, forwarde _, forwardedID, forwardedOrg, forwardedOUs := forwardedTLSInfoFromContext(ctx) if len(forwardedOUs) == 0 || forwardedID == "" || forwardedOrg == "" { - return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request") + return "", status.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request") } if !intersectArrays(forwardedOUs, authorizedRoles) { - return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarded role, expecting: %v", authorizedRoles) + return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarded role, expecting: %v", authorizedRoles) } if forwardedOrg != org { - return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: organization mismatch, expecting: %s", org) + return "", status.Errorf(codes.PermissionDenied, "Permission denied: organization mismatch, expecting: %s", org) } return forwardedID, nil @@ -152,7 +152,7 @@ func AuthorizeForwardedRoleAndOrg(ctx context.Context, authorizedRoles, forwarde return nodeID, nil } - return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: unauthorized peer role: %v", err) + return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized peer role: %v", err) } // intersectArrays returns true when there is at least one element in common @@ -219,7 +219,7 @@ func RemoteNode(ctx context.Context) (RemoteNodeInfo, error) { peer, ok := peer.FromContext(ctx) if !ok { - return RemoteNodeInfo{}, grpc.Errorf(codes.PermissionDenied, "Permission denied: no peer info") + return RemoteNodeInfo{}, status.Errorf(codes.PermissionDenied, "Permission denied: no peer info") } directInfo := RemoteNodeInfo{ @@ -232,7 +232,7 @@ func RemoteNode(ctx context.Context) (RemoteNodeInfo, error) { if isForwardedRequest(ctx) { remoteAddr, cn, org, ous := forwardedTLSInfoFromContext(ctx) if len(ous) == 0 || cn == "" || org == "" { - return RemoteNodeInfo{}, grpc.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request") + return RemoteNodeInfo{}, status.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request") } return RemoteNodeInfo{ Roles: ous, diff --git a/ca/server.go b/ca/server.go index 16dbedc8da..a456df7900 100644 --- a/ca/server.go +++ b/ca/server.go @@ -16,8 +16,8 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) const ( @@ -149,7 +149,7 @@ func (s *Server) GetUnlockKey(ctx context.Context, request *api.GetUnlockKeyRequ // NodeCertificateStatus returns the current issuance status of an issuance request identified by the nodeID func (s *Server) NodeCertificateStatus(ctx context.Context, request *api.NodeCertificateStatusRequest) (*api.NodeCertificateStatusResponse, error) { if request.NodeID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, codes.InvalidArgument.String()) + return nil, status.Errorf(codes.InvalidArgument, codes.InvalidArgument.String()) } serverCtx, err := s.isRunningLocked() @@ -180,7 +180,7 @@ func (s *Server) NodeCertificateStatus(ctx context.Context, request *api.NodeCer // This node ID doesn't exist if node == nil { - return nil, grpc.Errorf(codes.NotFound, codes.NotFound.String()) + return nil, status.Errorf(codes.NotFound, codes.NotFound.String()) } log.G(ctx).WithFields(logrus.Fields{ @@ -236,7 +236,7 @@ func (s *Server) NodeCertificateStatus(ctx context.Context, request *api.NodeCer func (s *Server) IssueNodeCertificate(ctx context.Context, request *api.IssueNodeCertificateRequest) (*api.IssueNodeCertificateResponse, error) { // First, let's see if the remote node is presenting a non-empty CSR if len(request.CSR) == 0 { - return nil, grpc.Errorf(codes.InvalidArgument, codes.InvalidArgument.String()) + return nil, status.Errorf(codes.InvalidArgument, codes.InvalidArgument.String()) } if err := s.isReadyLocked(); err != nil { @@ -295,7 +295,7 @@ func (s *Server) IssueNodeCertificate(ctx context.Context, request *api.IssueNod s.mu.Unlock() if role < 0 { - return nil, grpc.Errorf(codes.InvalidArgument, "A valid join token is necessary to join this cluster") + return nil, status.Errorf(codes.InvalidArgument, "A valid join token is necessary to join this cluster") } // Max number of collisions of ID or CN to tolerate before giving up @@ -369,7 +369,7 @@ func (s *Server) issueRenewCertificate(ctx context.Context, nodeID string, csr [ "method": "issueRenewCertificate", }).Warnf("node does not exist") // If this node doesn't exist, we shouldn't be renewing a certificate for it - return grpc.Errorf(codes.NotFound, "node %s not found when attempting to renew certificate", nodeID) + return status.Errorf(codes.NotFound, "node %s not found when attempting to renew certificate", nodeID) } // Create a new Certificate entry for this node with the new CSR and a RENEW state @@ -594,7 +594,7 @@ func (s *Server) isRunningLocked() (context.Context, error) { s.mu.Lock() if !s.isRunning() { s.mu.Unlock() - return nil, grpc.Errorf(codes.Aborted, "CA signer is stopped") + return nil, status.Errorf(codes.Aborted, "CA signer is stopped") } ctx := s.ctx s.mu.Unlock() @@ -605,10 +605,10 @@ func (s *Server) isReadyLocked() error { s.mu.Lock() defer s.mu.Unlock() if !s.isRunning() { - return grpc.Errorf(codes.Aborted, "CA signer is stopped") + return status.Errorf(codes.Aborted, "CA signer is stopped") } if s.joinTokens == nil { - return grpc.Errorf(codes.Aborted, "CA signer is still starting") + return status.Errorf(codes.Aborted, "CA signer is still starting") } return nil } diff --git a/manager/controlapi/ca_rotation.go b/manager/controlapi/ca_rotation.go index 5e8fa43ce3..d39c7d2b69 100644 --- a/manager/controlapi/ca_rotation.go +++ b/manager/controlapi/ca_rotation.go @@ -10,13 +10,12 @@ import ( "net/url" "time" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "github.com/cloudflare/cfssl/helpers" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/ca" "github.com/docker/swarmkit/log" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) var minRootExpiration = 1 * helpers.OneYear @@ -60,7 +59,7 @@ func newRootRotationObject(ctx context.Context, securityConfig *ca.SecurityConfi crossSignedCert, err = oldRootCA.CrossSignCACertificate(rootCert) } case !newRootHasSigner: // the original CA and the new CA both require external CAs - return nil, grpc.Errorf(codes.InvalidArgument, "rotating from one external CA to a different external CA is not supported") + return nil, status.Errorf(codes.InvalidArgument, "rotating from one external CA to a different external CA is not supported") default: // We need the same credentials but to connect to the original URLs (in case we are in the middle of a root rotation already) var urls []string @@ -70,7 +69,7 @@ func newRootRotationObject(ctx context.Context, securityConfig *ca.SecurityConfi } } if len(urls) == 0 { - return nil, grpc.Errorf(codes.InvalidArgument, + return nil, status.Errorf(codes.InvalidArgument, "must provide an external CA for the current external root CA to generate a cross-signed certificate") } rootPool := x509.NewCertPool() @@ -83,7 +82,7 @@ func newRootRotationObject(ctx context.Context, securityConfig *ca.SecurityConfi if err != nil { log.G(ctx).WithError(err).Error("unable to generate a cross-signed certificate for root rotation") - return nil, grpc.Errorf(codes.Internal, "unable to generate a cross-signed certificate for root rotation") + return nil, status.Errorf(codes.Internal, "unable to generate a cross-signed certificate for root rotation") } copied := apiRootCA.Copy() @@ -146,7 +145,7 @@ func validateHasAtLeastOneExternalCA(ctx context.Context, externalCAs map[string } } } - return nil, grpc.Errorf(codes.InvalidArgument, "there must be at least one valid, reachable external CA corresponding to the %s CA certificate", desc) + return nil, status.Errorf(codes.InvalidArgument, "there must be at least one valid, reachable external CA corresponding to the %s CA certificate", desc) } // validates that the list of external CAs have valid certs associated with them, and produce a mapping of subject/pubkey:external @@ -193,7 +192,7 @@ func validateCAConfig(ctx context.Context, securityConfig *ca.SecurityConfig, cl newConfig.SigningCACert = ca.NormalizePEMs(newConfig.SigningCACert) // ensure this is normalized before we use it if len(newConfig.SigningCAKey) > 0 && len(newConfig.SigningCACert) == 0 { - return nil, grpc.Errorf(codes.InvalidArgument, "if a signing CA key is provided, the signing CA cert must also be provided") + return nil, status.Errorf(codes.InvalidArgument, "if a signing CA key is provided, the signing CA cert must also be provided") } normalizedRootCA := ca.NormalizePEMs(cluster.RootCA.CACert) @@ -216,7 +215,7 @@ func validateCAConfig(ctx context.Context, securityConfig *ca.SecurityConfig, cl if cluster.RootCA.LastForcedRotation != newConfig.ForceRotate { newRootCA, err := ca.CreateRootCA(ca.DefaultRootCN) if err != nil { - return nil, grpc.Errorf(codes.Internal, err.Error()) + return nil, status.Errorf(codes.Internal, err.Error()) } return newRootRotationObject(ctx, securityConfig, &cluster.RootCA, newRootCA, oldCertExtCAs, newConfig.ForceRotate) } @@ -240,21 +239,21 @@ func validateCAConfig(ctx context.Context, securityConfig *ca.SecurityConfig, cl } newRootCA, err := ca.NewRootCA(newConfig.SigningCACert, signingCert, newConfig.SigningCAKey, ca.DefaultNodeCertExpiration, nil) if err != nil { - return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) + return nil, status.Errorf(codes.InvalidArgument, err.Error()) } if len(newRootCA.Pool.Subjects()) != 1 { - return nil, grpc.Errorf(codes.InvalidArgument, "the desired CA certificate cannot contain multiple certificates") + return nil, status.Errorf(codes.InvalidArgument, "the desired CA certificate cannot contain multiple certificates") } parsedCert, err := helpers.ParseCertificatePEM(newConfig.SigningCACert) if err != nil { - return nil, grpc.Errorf(codes.InvalidArgument, "could not parse the desired CA certificate") + return nil, status.Errorf(codes.InvalidArgument, "could not parse the desired CA certificate") } // The new certificate's expiry must be at least one year away if parsedCert.NotAfter.Before(time.Now().Add(minRootExpiration)) { - return nil, grpc.Errorf(codes.InvalidArgument, "CA certificate expires too soon") + return nil, status.Errorf(codes.InvalidArgument, "CA certificate expires too soon") } if !hasSigningKey(newConfig) { diff --git a/manager/controlapi/cluster.go b/manager/controlapi/cluster.go index de41f49dd4..0876113d70 100644 --- a/manager/controlapi/cluster.go +++ b/manager/controlapi/cluster.go @@ -11,8 +11,8 @@ import ( "github.com/docker/swarmkit/manager/state/store" gogotypes "github.com/gogo/protobuf/types" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) const ( @@ -23,17 +23,17 @@ const ( func validateClusterSpec(spec *api.ClusterSpec) error { if spec == nil { - return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } // Validate that expiry time being provided is valid, and over our minimum if spec.CAConfig.NodeCertExpiry != nil { expiry, err := gogotypes.DurationFromProto(spec.CAConfig.NodeCertExpiry) if err != nil { - return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if expiry < ca.MinNodeCertExpiration { - return grpc.Errorf(codes.InvalidArgument, "minimum certificate expiry time is: %s", ca.MinNodeCertExpiration) + return status.Errorf(codes.InvalidArgument, "minimum certificate expiry time is: %s", ca.MinNodeCertExpiration) } } @@ -42,7 +42,7 @@ func validateClusterSpec(spec *api.ClusterSpec) error { if len(spec.AcceptancePolicy.Policies) > 0 { for _, policy := range spec.AcceptancePolicy.Policies { if policy.Secret != nil && strings.ToLower(policy.Secret.Alg) != "bcrypt" { - return grpc.Errorf(codes.InvalidArgument, "hashing algorithm is not supported: %s", policy.Secret.Alg) + return status.Errorf(codes.InvalidArgument, "hashing algorithm is not supported: %s", policy.Secret.Alg) } } } @@ -51,15 +51,15 @@ func validateClusterSpec(spec *api.ClusterSpec) error { if spec.Dispatcher.HeartbeatPeriod != nil { heartbeatPeriod, err := gogotypes.DurationFromProto(spec.Dispatcher.HeartbeatPeriod) if err != nil { - return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if heartbeatPeriod < 0 { - return grpc.Errorf(codes.InvalidArgument, "heartbeat time period cannot be a negative duration") + return status.Errorf(codes.InvalidArgument, "heartbeat time period cannot be a negative duration") } } if spec.Annotations.Name != store.DefaultClusterName { - return grpc.Errorf(codes.InvalidArgument, "modification of cluster name is not allowed") + return status.Errorf(codes.InvalidArgument, "modification of cluster name is not allowed") } return nil @@ -70,7 +70,7 @@ func validateClusterSpec(spec *api.ClusterSpec) error { // - Returns `NotFound` if the Cluster is not found. func (s *Server) GetCluster(ctx context.Context, request *api.GetClusterRequest) (*api.GetClusterResponse, error) { if request.ClusterID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var cluster *api.Cluster @@ -78,7 +78,7 @@ func (s *Server) GetCluster(ctx context.Context, request *api.GetClusterRequest) cluster = store.GetCluster(tx, request.ClusterID) }) if cluster == nil { - return nil, grpc.Errorf(codes.NotFound, "cluster %s not found", request.ClusterID) + return nil, status.Errorf(codes.NotFound, "cluster %s not found", request.ClusterID) } redactedClusters := redactClusters([]*api.Cluster{cluster}) @@ -96,7 +96,7 @@ func (s *Server) GetCluster(ctx context.Context, request *api.GetClusterRequest) // - Returns an error if the update fails. func (s *Server) UpdateCluster(ctx context.Context, request *api.UpdateClusterRequest) (*api.UpdateClusterResponse, error) { if request.ClusterID == "" || request.ClusterVersion == nil { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if err := validateClusterSpec(request.Spec); err != nil { return nil, err @@ -106,7 +106,7 @@ func (s *Server) UpdateCluster(ctx context.Context, request *api.UpdateClusterRe err := s.store.Update(func(tx store.Tx) error { cluster = store.GetCluster(tx, request.ClusterID) if cluster == nil { - return grpc.Errorf(codes.NotFound, "cluster %s not found", request.ClusterID) + return status.Errorf(codes.NotFound, "cluster %s not found", request.ClusterID) } // This ensures that we have the current rootCA with which to generate tokens (expiration doesn't matter // for generating the tokens) @@ -114,7 +114,7 @@ func (s *Server) UpdateCluster(ctx context.Context, request *api.UpdateClusterRe if err != nil { log.G(ctx).WithField( "method", "(*controlapi.Server).UpdateCluster").WithError(err).Error("invalid cluster root CA") - return grpc.Errorf(codes.Internal, "error loading cluster rootCA for update") + return status.Errorf(codes.Internal, "error loading cluster rootCA for update") } cluster.Meta.Version = *request.ClusterVersion diff --git a/manager/controlapi/common.go b/manager/controlapi/common.go index c01662379e..9e52179464 100644 --- a/manager/controlapi/common.go +++ b/manager/controlapi/common.go @@ -10,8 +10,8 @@ import ( "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/manager/allocator" "github.com/docker/swarmkit/manager/state/store" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) var isValidDNSName = regexp.MustCompile(`^[a-zA-Z0-9](?:[-_]*[A-Za-z0-9]+)*$`) @@ -70,25 +70,25 @@ func filterMatchLabels(match map[string]string, candidates map[string]string) bo func validateAnnotations(m api.Annotations) error { if m.Name == "" { - return grpc.Errorf(codes.InvalidArgument, "meta: name must be provided") + return status.Errorf(codes.InvalidArgument, "meta: name must be provided") } if !isValidDNSName.MatchString(m.Name) { // if the name doesn't match the regex - return grpc.Errorf(codes.InvalidArgument, "name must be valid as a DNS name component") + return status.Errorf(codes.InvalidArgument, "name must be valid as a DNS name component") } if len(m.Name) > 63 { // DNS labels are limited to 63 characters - return grpc.Errorf(codes.InvalidArgument, "name must be 63 characters or fewer") + return status.Errorf(codes.InvalidArgument, "name must be 63 characters or fewer") } return nil } func validateConfigOrSecretAnnotations(m api.Annotations) error { if m.Name == "" { - return grpc.Errorf(codes.InvalidArgument, "name must be provided") + return status.Errorf(codes.InvalidArgument, "name must be provided") } else if len(m.Name) > 64 || !isValidConfigOrSecretName.MatchString(m.Name) { // if the name doesn't match the regex - return grpc.Errorf(codes.InvalidArgument, + return status.Errorf(codes.InvalidArgument, "invalid name, only 64 [a-zA-Z0-9-_.] characters allowed, and the start and end character must be [a-zA-Z0-9]") } return nil @@ -102,7 +102,7 @@ func validateDriver(driver *api.Driver, pg plugingetter.PluginGetter, pluginType } if driver.Name == "" { - return grpc.Errorf(codes.InvalidArgument, "driver name: if driver is specified name is required") + return status.Errorf(codes.InvalidArgument, "driver name: if driver is specified name is required") } // First check against the known drivers @@ -119,16 +119,16 @@ func validateDriver(driver *api.Driver, pg plugingetter.PluginGetter, pluginType } if pg == nil { - return grpc.Errorf(codes.InvalidArgument, "plugin %s not supported", driver.Name) + return status.Errorf(codes.InvalidArgument, "plugin %s not supported", driver.Name) } p, err := pg.Get(driver.Name, pluginType, plugingetter.Lookup) if err != nil { - return grpc.Errorf(codes.InvalidArgument, "error during lookup of plugin %s", driver.Name) + return status.Errorf(codes.InvalidArgument, "error during lookup of plugin %s", driver.Name) } if p.IsV1() { - return grpc.Errorf(codes.InvalidArgument, "legacy plugin %s of type %s is not supported in swarm mode", driver.Name, pluginType) + return status.Errorf(codes.InvalidArgument, "legacy plugin %s of type %s is not supported in swarm mode", driver.Name, pluginType) } return nil diff --git a/manager/controlapi/config.go b/manager/controlapi/config.go index d0fe8a56c1..ae08885b00 100644 --- a/manager/controlapi/config.go +++ b/manager/controlapi/config.go @@ -10,8 +10,8 @@ import ( "github.com/docker/swarmkit/manager/state/store" "github.com/sirupsen/logrus" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // MaxConfigSize is the maximum byte length of the `Config.Spec.Data` field. @@ -32,7 +32,7 @@ func configFromConfigSpec(spec *api.ConfigSpec) *api.Config { // - Returns an error if getting fails. func (s *Server) GetConfig(ctx context.Context, request *api.GetConfigRequest) (*api.GetConfigResponse, error) { if request.ConfigID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, "config ID must be provided") + return nil, status.Errorf(codes.InvalidArgument, "config ID must be provided") } var config *api.Config @@ -41,7 +41,7 @@ func (s *Server) GetConfig(ctx context.Context, request *api.GetConfigRequest) ( }) if config == nil { - return nil, grpc.Errorf(codes.NotFound, "config %s not found", request.ConfigID) + return nil, status.Errorf(codes.NotFound, "config %s not found", request.ConfigID) } return &api.GetConfigResponse{Config: config}, nil @@ -53,21 +53,21 @@ func (s *Server) GetConfig(ctx context.Context, request *api.GetConfigRequest) ( // - Returns an error if the update fails. func (s *Server) UpdateConfig(ctx context.Context, request *api.UpdateConfigRequest) (*api.UpdateConfigResponse, error) { if request.ConfigID == "" || request.ConfigVersion == nil { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var config *api.Config err := s.store.Update(func(tx store.Tx) error { config = store.GetConfig(tx, request.ConfigID) if config == nil { - return grpc.Errorf(codes.NotFound, "config %s not found", request.ConfigID) + return status.Errorf(codes.NotFound, "config %s not found", request.ConfigID) } // Check if the Name is different than the current name, or the config is non-nil and different // than the current config if config.Spec.Annotations.Name != request.Spec.Annotations.Name || (request.Spec.Data != nil && !bytes.Equal(request.Spec.Data, config.Spec.Data)) { - return grpc.Errorf(codes.InvalidArgument, "only updates to Labels are allowed") + return status.Errorf(codes.InvalidArgument, "only updates to Labels are allowed") } // We only allow updating Labels @@ -164,7 +164,7 @@ func (s *Server) CreateConfig(ctx context.Context, request *api.CreateConfigRequ switch err { case store.ErrNameConflict: - return nil, grpc.Errorf(codes.AlreadyExists, "config %s already exists", request.Spec.Annotations.Name) + return nil, status.Errorf(codes.AlreadyExists, "config %s already exists", request.Spec.Annotations.Name) case nil: log.G(ctx).WithFields(logrus.Fields{ "config.Name": request.Spec.Annotations.Name, @@ -184,20 +184,20 @@ func (s *Server) CreateConfig(ctx context.Context, request *api.CreateConfigRequ // - Returns an error if the deletion fails. func (s *Server) RemoveConfig(ctx context.Context, request *api.RemoveConfigRequest) (*api.RemoveConfigResponse, error) { if request.ConfigID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, "config ID must be provided") + return nil, status.Errorf(codes.InvalidArgument, "config ID must be provided") } err := s.store.Update(func(tx store.Tx) error { // Check if the config exists config := store.GetConfig(tx, request.ConfigID) if config == nil { - return grpc.Errorf(codes.NotFound, "could not find config %s", request.ConfigID) + return status.Errorf(codes.NotFound, "could not find config %s", request.ConfigID) } // Check if any services currently reference this config, return error if so services, err := store.FindServices(tx, store.ByReferencedConfigID(request.ConfigID)) if err != nil { - return grpc.Errorf(codes.Internal, "could not find services using config %s: %v", request.ConfigID, err) + return status.Errorf(codes.Internal, "could not find services using config %s: %v", request.ConfigID, err) } if len(services) != 0 { @@ -213,14 +213,14 @@ func (s *Server) RemoveConfig(ctx context.Context, request *api.RemoveConfigRequ serviceStr = "service" } - return grpc.Errorf(codes.InvalidArgument, "config '%s' is in use by the following %s: %v", configName, serviceStr, serviceNameStr) + return status.Errorf(codes.InvalidArgument, "config '%s' is in use by the following %s: %v", configName, serviceStr, serviceNameStr) } return store.DeleteConfig(tx, request.ConfigID) }) switch err { case store.ErrNotExist: - return nil, grpc.Errorf(codes.NotFound, "config %s not found", request.ConfigID) + return nil, status.Errorf(codes.NotFound, "config %s not found", request.ConfigID) case nil: log.G(ctx).WithFields(logrus.Fields{ "config.ID": request.ConfigID, @@ -235,14 +235,14 @@ func (s *Server) RemoveConfig(ctx context.Context, request *api.RemoveConfigRequ func validateConfigSpec(spec *api.ConfigSpec) error { if spec == nil { - return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if err := validateConfigOrSecretAnnotations(spec.Annotations); err != nil { return err } if len(spec.Data) >= MaxConfigSize || len(spec.Data) < 1 { - return grpc.Errorf(codes.InvalidArgument, "config data must be larger than 0 and less than %d bytes", MaxConfigSize) + return status.Errorf(codes.InvalidArgument, "config data must be larger than 0 and less than %d bytes", MaxConfigSize) } return nil } diff --git a/manager/controlapi/network.go b/manager/controlapi/network.go index b150de0e78..481b0cfe4b 100644 --- a/manager/controlapi/network.go +++ b/manager/controlapi/network.go @@ -12,39 +12,39 @@ import ( "github.com/docker/swarmkit/manager/allocator/networkallocator" "github.com/docker/swarmkit/manager/state/store" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) func validateIPAMConfiguration(ipamConf *api.IPAMConfig) error { if ipamConf == nil { - return grpc.Errorf(codes.InvalidArgument, "ipam configuration: cannot be empty") + return status.Errorf(codes.InvalidArgument, "ipam configuration: cannot be empty") } _, subnet, err := net.ParseCIDR(ipamConf.Subnet) if err != nil { - return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid subnet %s", ipamConf.Subnet) + return status.Errorf(codes.InvalidArgument, "ipam configuration: invalid subnet %s", ipamConf.Subnet) } if ipamConf.Range != "" { ip, _, err := net.ParseCIDR(ipamConf.Range) if err != nil { - return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid range %s", ipamConf.Range) + return status.Errorf(codes.InvalidArgument, "ipam configuration: invalid range %s", ipamConf.Range) } if !subnet.Contains(ip) { - return grpc.Errorf(codes.InvalidArgument, "ipam configuration: subnet %s does not contain range %s", ipamConf.Subnet, ipamConf.Range) + return status.Errorf(codes.InvalidArgument, "ipam configuration: subnet %s does not contain range %s", ipamConf.Subnet, ipamConf.Range) } } if ipamConf.Gateway != "" { ip := net.ParseIP(ipamConf.Gateway) if ip == nil { - return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid gateway %s", ipamConf.Gateway) + return status.Errorf(codes.InvalidArgument, "ipam configuration: invalid gateway %s", ipamConf.Gateway) } if !subnet.Contains(ip) { - return grpc.Errorf(codes.InvalidArgument, "ipam configuration: subnet %s does not contain gateway %s", ipamConf.Subnet, ipamConf.Gateway) + return status.Errorf(codes.InvalidArgument, "ipam configuration: subnet %s does not contain gateway %s", ipamConf.Subnet, ipamConf.Gateway) } } @@ -73,15 +73,15 @@ func validateIPAM(ipam *api.IPAMOptions, pg plugingetter.PluginGetter) error { func validateNetworkSpec(spec *api.NetworkSpec, pg plugingetter.PluginGetter) error { if spec == nil { - return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if spec.Ingress && spec.DriverConfig != nil && spec.DriverConfig.Name != "overlay" { - return grpc.Errorf(codes.Unimplemented, "only overlay driver is currently supported for ingress network") + return status.Errorf(codes.Unimplemented, "only overlay driver is currently supported for ingress network") } if spec.Attachable && spec.Ingress { - return grpc.Errorf(codes.InvalidArgument, "ingress network cannot be attachable") + return status.Errorf(codes.InvalidArgument, "ingress network cannot be attachable") } if err := validateAnnotations(spec.Annotations); err != nil { @@ -89,7 +89,7 @@ func validateNetworkSpec(spec *api.NetworkSpec, pg plugingetter.PluginGetter) er } if _, ok := spec.Annotations.Labels[networkallocator.PredefinedLabel]; ok { - return grpc.Errorf(codes.PermissionDenied, "label %s is for internally created predefined networks and cannot be applied by users", + return status.Errorf(codes.PermissionDenied, "label %s is for internally created predefined networks and cannot be applied by users", networkallocator.PredefinedLabel) } if err := validateDriver(spec.DriverConfig, pg, driverapi.NetworkPluginEndpointType); err != nil { @@ -117,9 +117,9 @@ func (s *Server) CreateNetwork(ctx context.Context, request *api.CreateNetworkRe err := s.store.Update(func(tx store.Tx) error { if request.Spec.Ingress { if n, err := allocator.GetIngressNetwork(s.store); err == nil { - return grpc.Errorf(codes.AlreadyExists, "ingress network (%s) is already present", n.ID) + return status.Errorf(codes.AlreadyExists, "ingress network (%s) is already present", n.ID) } else if err != allocator.ErrNoIngress { - return grpc.Errorf(codes.Internal, "failed ingress network presence check: %v", err) + return status.Errorf(codes.Internal, "failed ingress network presence check: %v", err) } } return store.CreateNetwork(tx, n) @@ -138,7 +138,7 @@ func (s *Server) CreateNetwork(ctx context.Context, request *api.CreateNetworkRe // - Returns `NotFound` if the Network is not found. func (s *Server) GetNetwork(ctx context.Context, request *api.GetNetworkRequest) (*api.GetNetworkResponse, error) { if request.NetworkID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var n *api.Network @@ -146,7 +146,7 @@ func (s *Server) GetNetwork(ctx context.Context, request *api.GetNetworkRequest) n = store.GetNetwork(tx, request.NetworkID) }) if n == nil { - return nil, grpc.Errorf(codes.NotFound, "network %s not found", request.NetworkID) + return nil, status.Errorf(codes.NotFound, "network %s not found", request.NetworkID) } return &api.GetNetworkResponse{ Network: n, @@ -159,7 +159,7 @@ func (s *Server) GetNetwork(ctx context.Context, request *api.GetNetworkRequest) // - Returns an error if the deletion fails. func (s *Server) RemoveNetwork(ctx context.Context, request *api.RemoveNetworkRequest) (*api.RemoveNetworkResponse, error) { if request.NetworkID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var ( @@ -171,7 +171,7 @@ func (s *Server) RemoveNetwork(ctx context.Context, request *api.RemoveNetworkRe n = store.GetNetwork(tx, request.NetworkID) }) if n == nil { - return nil, grpc.Errorf(codes.NotFound, "network %s not found", request.NetworkID) + return nil, status.Errorf(codes.NotFound, "network %s not found", request.NetworkID) } if allocator.IsIngressNetwork(n) { @@ -179,13 +179,13 @@ func (s *Server) RemoveNetwork(ctx context.Context, request *api.RemoveNetworkRe } if v, ok := n.Spec.Annotations.Labels[networkallocator.PredefinedLabel]; ok && v == "true" { - return nil, grpc.Errorf(codes.FailedPrecondition, "network %s (%s) is a swarm predefined network and cannot be removed", + return nil, status.Errorf(codes.FailedPrecondition, "network %s (%s) is a swarm predefined network and cannot be removed", request.NetworkID, n.Spec.Annotations.Name) } if err := rm(n.ID); err != nil { if err == store.ErrNotExist { - return nil, grpc.Errorf(codes.NotFound, "network %s not found", request.NetworkID) + return nil, status.Errorf(codes.NotFound, "network %s not found", request.NetworkID) } return nil, err } @@ -196,21 +196,21 @@ func (s *Server) removeNetwork(id string) error { return s.store.Update(func(tx store.Tx) error { services, err := store.FindServices(tx, store.ByReferencedNetworkID(id)) if err != nil { - return grpc.Errorf(codes.Internal, "could not find services using network %s: %v", id, err) + return status.Errorf(codes.Internal, "could not find services using network %s: %v", id, err) } if len(services) != 0 { - return grpc.Errorf(codes.FailedPrecondition, "network %s is in use by service %s", id, services[0].ID) + return status.Errorf(codes.FailedPrecondition, "network %s is in use by service %s", id, services[0].ID) } tasks, err := store.FindTasks(tx, store.ByReferencedNetworkID(id)) if err != nil { - return grpc.Errorf(codes.Internal, "could not find tasks using network %s: %v", id, err) + return status.Errorf(codes.Internal, "could not find tasks using network %s: %v", id, err) } for _, t := range tasks { if t.DesiredState <= api.TaskStateRunning && t.Status.State <= api.TaskStateRunning { - return grpc.Errorf(codes.FailedPrecondition, "network %s is in use by task %s", id, t.ID) + return status.Errorf(codes.FailedPrecondition, "network %s is in use by task %s", id, t.ID) } } @@ -222,11 +222,11 @@ func (s *Server) removeIngressNetwork(id string) error { return s.store.Update(func(tx store.Tx) error { services, err := store.FindServices(tx, store.All) if err != nil { - return grpc.Errorf(codes.Internal, "could not find services using network %s: %v", id, err) + return status.Errorf(codes.Internal, "could not find services using network %s: %v", id, err) } for _, srv := range services { if allocator.IsIngressNetworkNeeded(srv) { - return grpc.Errorf(codes.FailedPrecondition, "ingress network cannot be removed because service %s depends on it", srv.ID) + return status.Errorf(codes.FailedPrecondition, "ingress network cannot be removed because service %s depends on it", srv.ID) } } return store.DeleteNetwork(tx, id) diff --git a/manager/controlapi/node.go b/manager/controlapi/node.go index 3ec9094edf..e1fe3dec1d 100644 --- a/manager/controlapi/node.go +++ b/manager/controlapi/node.go @@ -9,13 +9,13 @@ import ( "github.com/docker/swarmkit/manager/state/store" gogotypes "github.com/gogo/protobuf/types" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) func validateNodeSpec(spec *api.NodeSpec) error { if spec == nil { - return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } return nil } @@ -25,7 +25,7 @@ func validateNodeSpec(spec *api.NodeSpec) error { // - Returns `NotFound` if the Node is not found. func (s *Server) GetNode(ctx context.Context, request *api.GetNodeRequest) (*api.GetNodeResponse, error) { if request.NodeID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var node *api.Node @@ -33,7 +33,7 @@ func (s *Server) GetNode(ctx context.Context, request *api.GetNodeRequest) (*api node = store.GetNode(tx, request.NodeID) }) if node == nil { - return nil, grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID) + return nil, status.Errorf(codes.NotFound, "node %s not found", request.NodeID) } if s.raft != nil { @@ -196,7 +196,7 @@ func (s *Server) ListNodes(ctx context.Context, request *api.ListNodesRequest) ( // - Returns an error if the update fails. func (s *Server) UpdateNode(ctx context.Context, request *api.UpdateNodeRequest) (*api.UpdateNodeResponse, error) { if request.NodeID == "" || request.NodeVersion == nil { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if err := validateNodeSpec(request.Spec); err != nil { return nil, err @@ -210,7 +210,7 @@ func (s *Server) UpdateNode(ctx context.Context, request *api.UpdateNodeRequest) err := s.store.Update(func(tx store.Tx) error { node = store.GetNode(tx, request.NodeID) if node == nil { - return grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID) + return status.Errorf(codes.NotFound, "node %s not found", request.NodeID) } // Demotion sanity checks. @@ -218,20 +218,20 @@ func (s *Server) UpdateNode(ctx context.Context, request *api.UpdateNodeRequest) // Check for manager entries in Store. managers, err := store.FindNodes(tx, store.ByRole(api.NodeRoleManager)) if err != nil { - return grpc.Errorf(codes.Internal, "internal store error: %v", err) + return status.Errorf(codes.Internal, "internal store error: %v", err) } if len(managers) == 1 && managers[0].ID == node.ID { - return grpc.Errorf(codes.FailedPrecondition, "attempting to demote the last manager of the swarm") + return status.Errorf(codes.FailedPrecondition, "attempting to demote the last manager of the swarm") } // Check for node in memberlist if member = s.raft.GetMemberByNodeID(request.NodeID); member == nil { - return grpc.Errorf(codes.NotFound, "can't find manager in raft memberlist") + return status.Errorf(codes.NotFound, "can't find manager in raft memberlist") } // Quorum safeguard if !s.raft.CanRemoveMember(member.RaftID) { - return grpc.Errorf(codes.FailedPrecondition, "can't remove member from the raft: this would result in a loss of quorum") + return status.Errorf(codes.FailedPrecondition, "can't remove member from the raft: this would result in a loss of quorum") } } @@ -278,24 +278,24 @@ func removeNodeAttachments(tx store.Tx, nodeID string) error { // - Returns an error if the delete fails. func (s *Server) RemoveNode(ctx context.Context, request *api.RemoveNodeRequest) (*api.RemoveNodeResponse, error) { if request.NodeID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } err := s.store.Update(func(tx store.Tx) error { node := store.GetNode(tx, request.NodeID) if node == nil { - return grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID) + return status.Errorf(codes.NotFound, "node %s not found", request.NodeID) } if node.Spec.DesiredRole == api.NodeRoleManager { if s.raft == nil { - return grpc.Errorf(codes.FailedPrecondition, "node %s is a manager but cannot access node information from the raft memberlist", request.NodeID) + return status.Errorf(codes.FailedPrecondition, "node %s is a manager but cannot access node information from the raft memberlist", request.NodeID) } if member := s.raft.GetMemberByNodeID(request.NodeID); member != nil { - return grpc.Errorf(codes.FailedPrecondition, "node %s is a cluster manager and is a member of the raft cluster. It must be demoted to worker before removal", request.NodeID) + return status.Errorf(codes.FailedPrecondition, "node %s is a cluster manager and is a member of the raft cluster. It must be demoted to worker before removal", request.NodeID) } } if !request.Force && node.Status.State == api.NodeStatus_READY { - return grpc.Errorf(codes.FailedPrecondition, "node %s is not down and can't be removed", request.NodeID) + return status.Errorf(codes.FailedPrecondition, "node %s is not down and can't be removed", request.NodeID) } // lookup the cluster @@ -304,7 +304,7 @@ func (s *Server) RemoveNode(ctx context.Context, request *api.RemoveNodeRequest) return err } if len(clusters) != 1 { - return grpc.Errorf(codes.Internal, "could not fetch cluster object") + return status.Errorf(codes.Internal, "could not fetch cluster object") } cluster := clusters[0] diff --git a/manager/controlapi/secret.go b/manager/controlapi/secret.go index bac4c102ef..fdcd2c412c 100644 --- a/manager/controlapi/secret.go +++ b/manager/controlapi/secret.go @@ -11,8 +11,8 @@ import ( "github.com/docker/swarmkit/manager/state/store" "github.com/sirupsen/logrus" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // assumes spec is not nil @@ -30,7 +30,7 @@ func secretFromSecretSpec(spec *api.SecretSpec) *api.Secret { // - Returns an error if getting fails. func (s *Server) GetSecret(ctx context.Context, request *api.GetSecretRequest) (*api.GetSecretResponse, error) { if request.SecretID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, "secret ID must be provided") + return nil, status.Errorf(codes.InvalidArgument, "secret ID must be provided") } var secret *api.Secret @@ -39,7 +39,7 @@ func (s *Server) GetSecret(ctx context.Context, request *api.GetSecretRequest) ( }) if secret == nil { - return nil, grpc.Errorf(codes.NotFound, "secret %s not found", request.SecretID) + return nil, status.Errorf(codes.NotFound, "secret %s not found", request.SecretID) } secret.Spec.Data = nil // clean the actual secret data so it's never returned @@ -52,20 +52,20 @@ func (s *Server) GetSecret(ctx context.Context, request *api.GetSecretRequest) ( // - Returns an error if the update fails. func (s *Server) UpdateSecret(ctx context.Context, request *api.UpdateSecretRequest) (*api.UpdateSecretResponse, error) { if request.SecretID == "" || request.SecretVersion == nil { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var secret *api.Secret err := s.store.Update(func(tx store.Tx) error { secret = store.GetSecret(tx, request.SecretID) if secret == nil { - return grpc.Errorf(codes.NotFound, "secret %s not found", request.SecretID) + return status.Errorf(codes.NotFound, "secret %s not found", request.SecretID) } // Check if the Name is different than the current name, or the secret is non-nil and different // than the current secret if secret.Spec.Annotations.Name != request.Spec.Annotations.Name || (request.Spec.Data != nil && subtle.ConstantTimeCompare(request.Spec.Data, secret.Spec.Data) == 0) { - return grpc.Errorf(codes.InvalidArgument, "only updates to Labels are allowed") + return status.Errorf(codes.InvalidArgument, "only updates to Labels are allowed") } // We only allow updating Labels @@ -171,7 +171,7 @@ func (s *Server) CreateSecret(ctx context.Context, request *api.CreateSecretRequ switch err { case store.ErrNameConflict: - return nil, grpc.Errorf(codes.AlreadyExists, "secret %s already exists", request.Spec.Annotations.Name) + return nil, status.Errorf(codes.AlreadyExists, "secret %s already exists", request.Spec.Annotations.Name) case nil: secret.Spec.Data = nil // clean the actual secret data so it's never returned log.G(ctx).WithFields(logrus.Fields{ @@ -192,20 +192,20 @@ func (s *Server) CreateSecret(ctx context.Context, request *api.CreateSecretRequ // - Returns an error if the deletion fails. func (s *Server) RemoveSecret(ctx context.Context, request *api.RemoveSecretRequest) (*api.RemoveSecretResponse, error) { if request.SecretID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, "secret ID must be provided") + return nil, status.Errorf(codes.InvalidArgument, "secret ID must be provided") } err := s.store.Update(func(tx store.Tx) error { // Check if the secret exists secret := store.GetSecret(tx, request.SecretID) if secret == nil { - return grpc.Errorf(codes.NotFound, "could not find secret %s", request.SecretID) + return status.Errorf(codes.NotFound, "could not find secret %s", request.SecretID) } // Check if any services currently reference this secret, return error if so services, err := store.FindServices(tx, store.ByReferencedSecretID(request.SecretID)) if err != nil { - return grpc.Errorf(codes.Internal, "could not find services using secret %s: %v", request.SecretID, err) + return status.Errorf(codes.Internal, "could not find services using secret %s: %v", request.SecretID, err) } if len(services) != 0 { @@ -221,14 +221,14 @@ func (s *Server) RemoveSecret(ctx context.Context, request *api.RemoveSecretRequ serviceStr = "service" } - return grpc.Errorf(codes.InvalidArgument, "secret '%s' is in use by the following %s: %v", secretName, serviceStr, serviceNameStr) + return status.Errorf(codes.InvalidArgument, "secret '%s' is in use by the following %s: %v", secretName, serviceStr, serviceNameStr) } return store.DeleteSecret(tx, request.SecretID) }) switch err { case store.ErrNotExist: - return nil, grpc.Errorf(codes.NotFound, "secret %s not found", request.SecretID) + return nil, status.Errorf(codes.NotFound, "secret %s not found", request.SecretID) case nil: log.G(ctx).WithFields(logrus.Fields{ "secret.ID": request.SecretID, @@ -243,7 +243,7 @@ func (s *Server) RemoveSecret(ctx context.Context, request *api.RemoveSecretRequ func validateSecretSpec(spec *api.SecretSpec) error { if spec == nil { - return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if err := validateConfigOrSecretAnnotations(spec.Annotations); err != nil { return err @@ -252,12 +252,12 @@ func validateSecretSpec(spec *api.SecretSpec) error { if spec.Driver != nil { // Ensure secret driver has a name if spec.Driver.Name == "" { - return grpc.Errorf(codes.InvalidArgument, "secret driver must have a name") + return status.Errorf(codes.InvalidArgument, "secret driver must have a name") } return nil } if err := validation.ValidateSecretPayload(spec.Data); err != nil { - return grpc.Errorf(codes.InvalidArgument, "%s", err.Error()) + return status.Errorf(codes.InvalidArgument, "%s", err.Error()) } return nil } diff --git a/manager/controlapi/service.go b/manager/controlapi/service.go index 951c27b01e..e4c27df977 100644 --- a/manager/controlapi/service.go +++ b/manager/controlapi/service.go @@ -19,8 +19,8 @@ import ( "github.com/docker/swarmkit/template" gogotypes "github.com/gogo/protobuf/types" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) var ( @@ -37,11 +37,11 @@ func validateResources(r *api.Resources) error { } if r.NanoCPUs != 0 && r.NanoCPUs < 1e6 { - return grpc.Errorf(codes.InvalidArgument, "invalid cpu value %g: Must be at least %g", float64(r.NanoCPUs)/1e9, 1e6/1e9) + return status.Errorf(codes.InvalidArgument, "invalid cpu value %g: Must be at least %g", float64(r.NanoCPUs)/1e9, 1e6/1e9) } if r.MemoryBytes != 0 && r.MemoryBytes < 4*1024*1024 { - return grpc.Errorf(codes.InvalidArgument, "invalid memory value %d: Must be at least 4MiB", r.MemoryBytes) + return status.Errorf(codes.InvalidArgument, "invalid memory value %d: Must be at least 4MiB", r.MemoryBytes) } if err := genericresource.ValidateTask(r); err != nil { return nil @@ -70,7 +70,7 @@ func validateRestartPolicy(rp *api.RestartPolicy) error { return err } if delay < 0 { - return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-delay cannot be negative") + return status.Errorf(codes.InvalidArgument, "TaskSpec: restart-delay cannot be negative") } } @@ -80,7 +80,7 @@ func validateRestartPolicy(rp *api.RestartPolicy) error { return err } if win < 0 { - return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-window cannot be negative") + return status.Errorf(codes.InvalidArgument, "TaskSpec: restart-window cannot be negative") } } @@ -101,7 +101,7 @@ func validateUpdate(uc *api.UpdateConfig) error { } if uc.Delay < 0 { - return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-delay cannot be negative") + return status.Errorf(codes.InvalidArgument, "TaskSpec: update-delay cannot be negative") } if uc.Monitor != nil { @@ -110,12 +110,12 @@ func validateUpdate(uc *api.UpdateConfig) error { return err } if monitor < 0 { - return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-monitor cannot be negative") + return status.Errorf(codes.InvalidArgument, "TaskSpec: update-monitor cannot be negative") } } if uc.MaxFailureRatio < 0 || uc.MaxFailureRatio > 1 { - return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-maxfailureratio cannot be less than 0 or bigger than 1") + return status.Errorf(codes.InvalidArgument, "TaskSpec: update-maxfailureratio cannot be less than 0 or bigger than 1") } return nil @@ -147,7 +147,7 @@ func validateContainerSpec(taskSpec api.TaskSpec) error { LogDriver: taskSpec.LogDriver, }) if err != nil { - return grpc.Errorf(codes.InvalidArgument, err.Error()) + return status.Errorf(codes.InvalidArgument, err.Error()) } if err := validateImage(container.Image); err != nil { @@ -164,11 +164,11 @@ func validateContainerSpec(taskSpec api.TaskSpec) error { // validateImage validates image name in containerSpec func validateImage(image string) error { if image == "" { - return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: image reference must be provided") + return status.Errorf(codes.InvalidArgument, "ContainerSpec: image reference must be provided") } if _, err := reference.ParseNormalizedNamed(image); err != nil { - return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: %q is not a valid repository/tag", image) + return status.Errorf(codes.InvalidArgument, "ContainerSpec: %q is not a valid repository/tag", image) } return nil } @@ -178,7 +178,7 @@ func validateMounts(mounts []api.Mount) error { mountMap := make(map[string]bool) for _, mount := range mounts { if _, exists := mountMap[mount.Target]; exists { - return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: duplicate mount point: %s", mount.Target) + return status.Errorf(codes.InvalidArgument, "ContainerSpec: duplicate mount point: %s", mount.Target) } mountMap[mount.Target] = true } @@ -198,7 +198,7 @@ func validateHealthCheck(hc *api.HealthConfig) error { return err } if interval != 0 && interval < time.Duration(minimumDuration) { - return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Interval in HealthConfig cannot be less than %s", minimumDuration) + return status.Errorf(codes.InvalidArgument, "ContainerSpec: Interval in HealthConfig cannot be less than %s", minimumDuration) } } @@ -208,7 +208,7 @@ func validateHealthCheck(hc *api.HealthConfig) error { return err } if timeout != 0 && timeout < time.Duration(minimumDuration) { - return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Timeout in HealthConfig cannot be less than %s", minimumDuration) + return status.Errorf(codes.InvalidArgument, "ContainerSpec: Timeout in HealthConfig cannot be less than %s", minimumDuration) } } @@ -218,12 +218,12 @@ func validateHealthCheck(hc *api.HealthConfig) error { return err } if sp != 0 && sp < time.Duration(minimumDuration) { - return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: StartPeriod in HealthConfig cannot be less than %s", minimumDuration) + return status.Errorf(codes.InvalidArgument, "ContainerSpec: StartPeriod in HealthConfig cannot be less than %s", minimumDuration) } } if hc.Retries < 0 { - return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Retries in HealthConfig cannot be negative") + return status.Errorf(codes.InvalidArgument, "ContainerSpec: Retries in HealthConfig cannot be negative") } return nil @@ -233,28 +233,28 @@ func validateGenericRuntimeSpec(taskSpec api.TaskSpec) error { generic := taskSpec.GetGeneric() if len(generic.Kind) < 3 { - return grpc.Errorf(codes.InvalidArgument, "Generic runtime: Invalid name %q", generic.Kind) + return status.Errorf(codes.InvalidArgument, "Generic runtime: Invalid name %q", generic.Kind) } reservedNames := []string{"container", "attachment"} for _, n := range reservedNames { if strings.ToLower(generic.Kind) == n { - return grpc.Errorf(codes.InvalidArgument, "Generic runtime: %q is a reserved name", generic.Kind) + return status.Errorf(codes.InvalidArgument, "Generic runtime: %q is a reserved name", generic.Kind) } } payload := generic.Payload if payload == nil { - return grpc.Errorf(codes.InvalidArgument, "Generic runtime is missing payload") + return status.Errorf(codes.InvalidArgument, "Generic runtime is missing payload") } if payload.TypeUrl == "" { - return grpc.Errorf(codes.InvalidArgument, "Generic runtime is missing payload type") + return status.Errorf(codes.InvalidArgument, "Generic runtime is missing payload type") } if len(payload.Value) == 0 { - return grpc.Errorf(codes.InvalidArgument, "Generic runtime has an empty payload") + return status.Errorf(codes.InvalidArgument, "Generic runtime has an empty payload") } return nil @@ -284,7 +284,7 @@ func validateTaskSpec(taskSpec api.TaskSpec) error { } if taskSpec.GetRuntime() == nil { - return grpc.Errorf(codes.InvalidArgument, "TaskSpec: missing runtime") + return status.Errorf(codes.InvalidArgument, "TaskSpec: missing runtime") } switch taskSpec.GetRuntime().(type) { @@ -297,7 +297,7 @@ func validateTaskSpec(taskSpec api.TaskSpec) error { return err } default: - return grpc.Errorf(codes.Unimplemented, "RuntimeSpec: unimplemented runtime in service spec") + return status.Errorf(codes.Unimplemented, "RuntimeSpec: unimplemented runtime in service spec") } return nil @@ -324,7 +324,7 @@ func validateEndpointSpec(epSpec *api.EndpointSpec) error { // for the backend network and hence we accept that configuration. if epSpec.Mode == api.ResolutionModeDNSRoundRobin && port.PublishMode == api.PublishModeIngress { - return grpc.Errorf(codes.InvalidArgument, "EndpointSpec: port published with ingress mode can't be used with dnsrr mode") + return status.Errorf(codes.InvalidArgument, "EndpointSpec: port published with ingress mode can't be used with dnsrr mode") } // If published port is not specified, it does not conflict @@ -335,7 +335,7 @@ func validateEndpointSpec(epSpec *api.EndpointSpec) error { portSpec := portSpec{publishedPort: port.PublishedPort, protocol: port.Protocol} if _, ok := portSet[portSpec]; ok { - return grpc.Errorf(codes.InvalidArgument, "EndpointSpec: duplicate published ports provided") + return status.Errorf(codes.InvalidArgument, "EndpointSpec: duplicate published ports provided") } portSet[portSpec] = struct{}{} @@ -358,23 +358,23 @@ func validateSecretRefsSpec(spec api.TaskSpec) error { for _, secretRef := range container.Secrets { // SecretID and SecretName are mandatory, we have invalid references without them if secretRef.SecretID == "" || secretRef.SecretName == "" { - return grpc.Errorf(codes.InvalidArgument, "malformed secret reference") + return status.Errorf(codes.InvalidArgument, "malformed secret reference") } // Every secret reference requires a Target if secretRef.GetTarget() == nil { - return grpc.Errorf(codes.InvalidArgument, "malformed secret reference, no target provided") + return status.Errorf(codes.InvalidArgument, "malformed secret reference, no target provided") } // If this is a file target, we will ensure filename uniqueness if secretRef.GetFile() != nil { fileName := secretRef.GetFile().Name if fileName == "" { - return grpc.Errorf(codes.InvalidArgument, "malformed file secret reference, invalid target file name provided") + return status.Errorf(codes.InvalidArgument, "malformed file secret reference, invalid target file name provided") } // If this target is already in use, we have conflicting targets if prevSecretName, ok := existingTargets[fileName]; ok { - return grpc.Errorf(codes.InvalidArgument, "secret references '%s' and '%s' have a conflicting target: '%s'", prevSecretName, secretRef.SecretName, fileName) + return status.Errorf(codes.InvalidArgument, "secret references '%s' and '%s' have a conflicting target: '%s'", prevSecretName, secretRef.SecretName, fileName) } existingTargets[fileName] = secretRef.SecretName @@ -398,12 +398,12 @@ func validateConfigRefsSpec(spec api.TaskSpec) error { for _, configRef := range container.Configs { // ConfigID and ConfigName are mandatory, we have invalid references without them if configRef.ConfigID == "" || configRef.ConfigName == "" { - return grpc.Errorf(codes.InvalidArgument, "malformed config reference") + return status.Errorf(codes.InvalidArgument, "malformed config reference") } // Every config reference requires a Target if configRef.GetTarget() == nil { - return grpc.Errorf(codes.InvalidArgument, "malformed config reference, no target provided") + return status.Errorf(codes.InvalidArgument, "malformed config reference, no target provided") } // If this is a file target, we will ensure filename uniqueness @@ -411,12 +411,12 @@ func validateConfigRefsSpec(spec api.TaskSpec) error { fileName := configRef.GetFile().Name // Validate the file name if fileName == "" { - return grpc.Errorf(codes.InvalidArgument, "malformed file config reference, invalid target file name provided") + return status.Errorf(codes.InvalidArgument, "malformed file config reference, invalid target file name provided") } // If this target is already in use, we have conflicting targets if prevConfigName, ok := existingTargets[fileName]; ok { - return grpc.Errorf(codes.InvalidArgument, "config references '%s' and '%s' have a conflicting target: '%s'", prevConfigName, configRef.ConfigName, fileName) + return status.Errorf(codes.InvalidArgument, "config references '%s' and '%s' have a conflicting target: '%s'", prevConfigName, configRef.ConfigName, fileName) } existingTargets[fileName] = configRef.ConfigName @@ -436,7 +436,7 @@ func (s *Server) validateNetworks(networks []*api.NetworkAttachmentConfig) error continue } if allocator.IsIngressNetwork(network) { - return grpc.Errorf(codes.InvalidArgument, + return status.Errorf(codes.InvalidArgument, "Service cannot be explicitly attached to the ingress network %q", network.Spec.Annotations.Name) } } @@ -448,11 +448,11 @@ func validateMode(s *api.ServiceSpec) error { switch m.(type) { case *api.ServiceSpec_Replicated: if int64(m.(*api.ServiceSpec_Replicated).Replicated.Replicas) < 0 { - return grpc.Errorf(codes.InvalidArgument, "Number of replicas must be non-negative") + return status.Errorf(codes.InvalidArgument, "Number of replicas must be non-negative") } case *api.ServiceSpec_Global: default: - return grpc.Errorf(codes.InvalidArgument, "Unrecognized service mode") + return status.Errorf(codes.InvalidArgument, "Unrecognized service mode") } return nil @@ -460,7 +460,7 @@ func validateMode(s *api.ServiceSpec) error { func validateServiceSpec(spec *api.ServiceSpec) error { if spec == nil { - return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if err := validateAnnotations(spec.Annotations); err != nil { return err @@ -536,7 +536,7 @@ func (s *Server) checkPortConflicts(spec *api.ServiceSpec, serviceID string) err switch pc.PublishMode { case api.PublishModeHost: if _, ok := ingressPorts[pcToStruct(pc)]; ok { - return grpc.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s) as a host-published port", pc.PublishedPort, service.Spec.Annotations.Name, service.ID) + return status.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s) as a host-published port", pc.PublishedPort, service.Spec.Annotations.Name, service.ID) } // Multiple services with same port in host publish mode can @@ -546,7 +546,7 @@ func (s *Server) checkPortConflicts(spec *api.ServiceSpec, serviceID string) err _, ingressConflict := ingressPorts[pcToStruct(pc)] _, hostModeConflict := hostModePorts[pcToStruct(pc)] if ingressConflict || hostModeConflict { - return grpc.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s) as an ingress port", pc.PublishedPort, service.Spec.Annotations.Name, service.ID) + return status.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s) as an ingress port", pc.PublishedPort, service.Spec.Annotations.Name, service.ID) } } @@ -598,7 +598,7 @@ func (s *Server) checkSecretExistence(tx store.Tx, spec *api.ServiceSpec) error secretStr = "secret" } - return grpc.Errorf(codes.InvalidArgument, "%s not found: %v", secretStr, strings.Join(failedSecrets, ", ")) + return status.Errorf(codes.InvalidArgument, "%s not found: %v", secretStr, strings.Join(failedSecrets, ", ")) } @@ -627,7 +627,7 @@ func (s *Server) checkConfigExistence(tx store.Tx, spec *api.ServiceSpec) error configStr = "config" } - return grpc.Errorf(codes.InvalidArgument, "%s not found: %v", configStr, strings.Join(failedConfigs, ", ")) + return status.Errorf(codes.InvalidArgument, "%s not found: %v", configStr, strings.Join(failedConfigs, ", ")) } @@ -662,7 +662,7 @@ func (s *Server) CreateService(ctx context.Context, request *api.CreateServiceRe if allocator.IsIngressNetworkNeeded(service) { if _, err := allocator.GetIngressNetwork(s.store); err == allocator.ErrNoIngress { - return nil, grpc.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present") + return nil, status.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present") } } @@ -694,7 +694,7 @@ func (s *Server) CreateService(ctx context.Context, request *api.CreateServiceRe // - Returns `NotFound` if the Service is not found. func (s *Server) GetService(ctx context.Context, request *api.GetServiceRequest) (*api.GetServiceResponse, error) { if request.ServiceID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var service *api.Service @@ -702,7 +702,7 @@ func (s *Server) GetService(ctx context.Context, request *api.GetServiceRequest) service = store.GetService(tx, request.ServiceID) }) if service == nil { - return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID) + return nil, status.Errorf(codes.NotFound, "service %s not found", request.ServiceID) } if request.InsertDefaults { @@ -721,7 +721,7 @@ func (s *Server) GetService(ctx context.Context, request *api.GetServiceRequest) // - Returns an error if the update fails. func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRequest) (*api.UpdateServiceResponse, error) { if request.ServiceID == "" || request.ServiceVersion == nil { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if err := validateServiceSpec(request.Spec); err != nil { return nil, err @@ -732,7 +732,7 @@ func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRe service = store.GetService(tx, request.ServiceID) }) if service == nil { - return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID) + return nil, status.Errorf(codes.NotFound, "service %s not found", request.ServiceID) } if request.Spec.Endpoint != nil && !reflect.DeepEqual(request.Spec.Endpoint, service.Spec.Endpoint) { @@ -744,7 +744,7 @@ func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRe err := s.store.Update(func(tx store.Tx) error { service = store.GetService(tx, request.ServiceID) if service == nil { - return grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID) + return status.Errorf(codes.NotFound, "service %s not found", request.ServiceID) } // It's not okay to update Service.Spec.Networks on its own. @@ -754,7 +754,7 @@ func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRe if (len(request.Spec.Networks) != 0 || len(service.Spec.Networks) != 0) && !reflect.DeepEqual(request.Spec.Networks, service.Spec.Networks) && reflect.DeepEqual(request.Spec.Task.Networks, service.Spec.Task.Networks) { - return grpc.Errorf(codes.Unimplemented, errNetworkUpdateNotSupported.Error()) + return status.Errorf(codes.Unimplemented, errNetworkUpdateNotSupported.Error()) } // Check to see if all the secrets being added exist as objects @@ -773,18 +773,18 @@ func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRe // with service mode change (comparing current config with previous config). // proper way to change service mode is to delete and re-add. if reflect.TypeOf(service.Spec.Mode) != reflect.TypeOf(request.Spec.Mode) { - return grpc.Errorf(codes.Unimplemented, errModeChangeNotAllowed.Error()) + return status.Errorf(codes.Unimplemented, errModeChangeNotAllowed.Error()) } if service.Spec.Annotations.Name != request.Spec.Annotations.Name { - return grpc.Errorf(codes.Unimplemented, errRenameNotSupported.Error()) + return status.Errorf(codes.Unimplemented, errRenameNotSupported.Error()) } service.Meta.Version = *request.ServiceVersion if request.Rollback == api.UpdateServiceRequest_PREVIOUS { if service.PreviousSpec == nil { - return grpc.Errorf(codes.FailedPrecondition, "service %s does not have a previous spec", request.ServiceID) + return status.Errorf(codes.FailedPrecondition, "service %s does not have a previous spec", request.ServiceID) } curSpec := service.Spec.Copy() @@ -815,7 +815,7 @@ func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRe if allocator.IsIngressNetworkNeeded(service) { if _, err := allocator.GetIngressNetwork(s.store); err == allocator.ErrNoIngress { - return grpc.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present") + return status.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present") } } @@ -836,7 +836,7 @@ func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRe // - Returns an error if the deletion fails. func (s *Server) RemoveService(ctx context.Context, request *api.RemoveServiceRequest) (*api.RemoveServiceResponse, error) { if request.ServiceID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } err := s.store.Update(func(tx store.Tx) error { @@ -844,7 +844,7 @@ func (s *Server) RemoveService(ctx context.Context, request *api.RemoveServiceRe }) if err != nil { if err == store.ErrNotExist { - return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID) + return nil, status.Errorf(codes.NotFound, "service %s not found", request.ServiceID) } return nil, err } diff --git a/manager/controlapi/task.go b/manager/controlapi/task.go index d2ae21522f..51b7bf82d8 100644 --- a/manager/controlapi/task.go +++ b/manager/controlapi/task.go @@ -6,8 +6,8 @@ import ( "github.com/docker/swarmkit/manager/orchestrator" "github.com/docker/swarmkit/manager/state/store" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // GetTask returns a Task given a TaskID. @@ -15,7 +15,7 @@ import ( // - Returns `NotFound` if the Task is not found. func (s *Server) GetTask(ctx context.Context, request *api.GetTaskRequest) (*api.GetTaskResponse, error) { if request.TaskID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var task *api.Task @@ -23,7 +23,7 @@ func (s *Server) GetTask(ctx context.Context, request *api.GetTaskRequest) (*api task = store.GetTask(tx, request.TaskID) }) if task == nil { - return nil, grpc.Errorf(codes.NotFound, "task %s not found", request.TaskID) + return nil, status.Errorf(codes.NotFound, "task %s not found", request.TaskID) } return &api.GetTaskResponse{ Task: task, @@ -36,7 +36,7 @@ func (s *Server) GetTask(ctx context.Context, request *api.GetTaskRequest) (*api // - Returns an error if the deletion fails. func (s *Server) RemoveTask(ctx context.Context, request *api.RemoveTaskRequest) (*api.RemoveTaskResponse, error) { if request.TaskID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } err := s.store.Update(func(tx store.Tx) error { @@ -44,7 +44,7 @@ func (s *Server) RemoveTask(ctx context.Context, request *api.RemoveTaskRequest) }) if err != nil { if err == store.ErrNotExist { - return nil, grpc.Errorf(codes.NotFound, "task %s not found", request.TaskID) + return nil, status.Errorf(codes.NotFound, "task %s not found", request.TaskID) } return nil, err } diff --git a/manager/dispatcher/dispatcher.go b/manager/dispatcher/dispatcher.go index 4de6a30c4d..1f4cfc1f88 100644 --- a/manager/dispatcher/dispatcher.go +++ b/manager/dispatcher/dispatcher.go @@ -7,10 +7,6 @@ import ( "sync" "time" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/transport" - "github.com/docker/go-events" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/api/equality" @@ -25,6 +21,9 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/net/context" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/grpc/transport" ) const ( @@ -322,7 +321,7 @@ func (d *Dispatcher) isRunningLocked() (context.Context, error) { d.mu.Lock() if !d.isRunning() { d.mu.Unlock() - return nil, grpc.Errorf(codes.Aborted, "dispatcher is stopped") + return nil, status.Errorf(codes.Aborted, "dispatcher is stopped") } ctx := d.ctx d.mu.Unlock() @@ -556,7 +555,7 @@ func (d *Dispatcher) UpdateTaskStatus(ctx context.Context, r *api.UpdateTaskStat } if t.NodeID != nodeID { - err := grpc.Errorf(codes.PermissionDenied, "cannot update a task not assigned this node") + err := status.Errorf(codes.PermissionDenied, "cannot update a task not assigned this node") log.WithField("task.id", u.TaskID).Error(err) return nil, err } @@ -1189,7 +1188,7 @@ func (d *Dispatcher) Session(r *api.SessionRequest, stream api.Dispatcher_Sessio log.WithError(err).Error("failed to remove node") } // still return an abort if the transport closure was ineffective. - return grpc.Errorf(codes.Aborted, "node must disconnect") + return status.Errorf(codes.Aborted, "node must disconnect") } for { diff --git a/manager/dispatcher/nodes.go b/manager/dispatcher/nodes.go index 8a0de558d6..cf35bb869a 100644 --- a/manager/dispatcher/nodes.go +++ b/manager/dispatcher/nodes.go @@ -4,12 +4,11 @@ import ( "sync" "time" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/identity" "github.com/docker/swarmkit/manager/dispatcher/heartbeat" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) const rateLimitCount = 3 @@ -36,7 +35,7 @@ func (rn *registeredNode) checkSessionID(sessionID string) error { // changed. If it has, we will the stream and make the node // re-register. if sessionID == "" || rn.SessionID != sessionID { - return grpc.Errorf(codes.InvalidArgument, ErrSessionInvalid.Error()) + return status.Errorf(codes.InvalidArgument, ErrSessionInvalid.Error()) } return nil @@ -97,7 +96,7 @@ func (s *nodeStore) CheckRateLimit(id string) error { } existRn.Attempts++ if existRn.Attempts > rateLimitCount { - return grpc.Errorf(codes.Unavailable, "node %s exceeded rate limit count of registrations", id) + return status.Errorf(codes.Unavailable, "node %s exceeded rate limit count of registrations", id) } existRn.Registered = time.Now() } @@ -136,7 +135,7 @@ func (s *nodeStore) Get(id string) (*registeredNode, error) { rn, ok := s.nodes[id] s.mu.RUnlock() if !ok { - return nil, grpc.Errorf(codes.NotFound, ErrNodeNotRegistered.Error()) + return nil, status.Errorf(codes.NotFound, ErrNodeNotRegistered.Error()) } return rn, nil } @@ -146,7 +145,7 @@ func (s *nodeStore) GetWithSession(id, sid string) (*registeredNode, error) { rn, ok := s.nodes[id] s.mu.RUnlock() if !ok { - return nil, grpc.Errorf(codes.NotFound, ErrNodeNotRegistered.Error()) + return nil, status.Errorf(codes.NotFound, ErrNodeNotRegistered.Error()) } return rn, rn.checkSessionID(sid) } diff --git a/manager/health/health.go b/manager/health/health.go index bf220bdc18..ef6658b09d 100644 --- a/manager/health/health.go +++ b/manager/health/health.go @@ -12,8 +12,8 @@ import ( "github.com/docker/swarmkit/api" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // Server represents a Health Check server to check @@ -46,7 +46,7 @@ func (s *Server) Check(ctx context.Context, in *api.HealthCheckRequest) (*api.He Status: status, }, nil } - return nil, grpc.Errorf(codes.NotFound, "unknown service") + return nil, status.Errorf(codes.NotFound, "unknown service") } // SetServingStatus is called when need to reset the serving status of a service diff --git a/manager/logbroker/broker.go b/manager/logbroker/broker.go index 860b55c30e..de2b93633f 100644 --- a/manager/logbroker/broker.go +++ b/manager/logbroker/broker.go @@ -6,9 +6,6 @@ import ( "io" "sync" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "github.com/docker/go-events" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/ca" @@ -18,6 +15,8 @@ import ( "github.com/docker/swarmkit/watch" "github.com/sirupsen/logrus" "golang.org/x/net/context" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) var ( @@ -93,11 +92,11 @@ func (lb *LogBroker) Stop() error { func validateSelector(selector *api.LogSelector) error { if selector == nil { - return grpc.Errorf(codes.InvalidArgument, "log selector must be provided") + return status.Errorf(codes.InvalidArgument, "log selector must be provided") } if len(selector.ServiceIDs) == 0 && len(selector.TaskIDs) == 0 && len(selector.NodeIDs) == 0 { - return grpc.Errorf(codes.InvalidArgument, "log selector must not be empty") + return status.Errorf(codes.InvalidArgument, "log selector must not be empty") } return nil @@ -401,17 +400,17 @@ func (lb *LogBroker) PublishLogs(stream api.LogBroker_PublishLogsServer) (err er } if logMsg.SubscriptionID == "" { - return grpc.Errorf(codes.InvalidArgument, "missing subscription ID") + return status.Errorf(codes.InvalidArgument, "missing subscription ID") } if currentSubscription == nil { currentSubscription = lb.getSubscription(logMsg.SubscriptionID) if currentSubscription == nil { - return grpc.Errorf(codes.NotFound, "unknown subscription ID") + return status.Errorf(codes.NotFound, "unknown subscription ID") } } else { if logMsg.SubscriptionID != currentSubscription.message.ID { - return grpc.Errorf(codes.InvalidArgument, "different subscription IDs in the same session") + return status.Errorf(codes.InvalidArgument, "different subscription IDs in the same session") } } @@ -427,7 +426,7 @@ func (lb *LogBroker) PublishLogs(stream api.LogBroker_PublishLogsServer) (err er // Make sure logs are emitted using the right Node ID to avoid impersonation. for _, msg := range logMsg.Messages { if msg.Context.NodeID != remote.NodeID { - return grpc.Errorf(codes.PermissionDenied, "invalid NodeID: expected=%s;received=%s", remote.NodeID, msg.Context.NodeID) + return status.Errorf(codes.PermissionDenied, "invalid NodeID: expected=%s;received=%s", remote.NodeID, msg.Context.NodeID) } } diff --git a/manager/resourceapi/allocator.go b/manager/resourceapi/allocator.go index 87b01ebd3b..ec19fba850 100644 --- a/manager/resourceapi/allocator.go +++ b/manager/resourceapi/allocator.go @@ -10,8 +10,8 @@ import ( "github.com/docker/swarmkit/manager/state/store" "github.com/docker/swarmkit/protobuf/ptypes" "golang.org/x/net/context" - "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) var ( @@ -50,11 +50,11 @@ func (ra *ResourceAllocator) AttachNetwork(ctx context.Context, request *api.Att } }) if network == nil { - return nil, grpc.Errorf(codes.NotFound, "network %s not found", request.Config.Target) + return nil, status.Errorf(codes.NotFound, "network %s not found", request.Config.Target) } if !network.Spec.Attachable { - return nil, grpc.Errorf(codes.PermissionDenied, "network %s not manually attachable", request.Config.Target) + return nil, status.Errorf(codes.PermissionDenied, "network %s not manually attachable", request.Config.Target) } t := &api.Task{ @@ -98,7 +98,7 @@ func (ra *ResourceAllocator) AttachNetwork(ctx context.Context, request *api.Att // - Returns an error if the deletion fails. func (ra *ResourceAllocator) DetachNetwork(ctx context.Context, request *api.DetachNetworkRequest) (*api.DetachNetworkResponse, error) { if request.AttachmentID == "" { - return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) + return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } nodeInfo, err := ca.RemoteNode(ctx) @@ -109,10 +109,10 @@ func (ra *ResourceAllocator) DetachNetwork(ctx context.Context, request *api.Det if err := ra.store.Update(func(tx store.Tx) error { t := store.GetTask(tx, request.AttachmentID) if t == nil { - return grpc.Errorf(codes.NotFound, "attachment %s not found", request.AttachmentID) + return status.Errorf(codes.NotFound, "attachment %s not found", request.AttachmentID) } if t.NodeID != nodeInfo.NodeID { - return grpc.Errorf(codes.PermissionDenied, "attachment %s doesn't belong to this node", request.AttachmentID) + return status.Errorf(codes.PermissionDenied, "attachment %s doesn't belong to this node", request.AttachmentID) } return store.DeleteTask(tx, request.AttachmentID) diff --git a/manager/state/raft/raft.go b/manager/state/raft/raft.go index b7cfe341de..3450d7df02 100644 --- a/manager/state/raft/raft.go +++ b/manager/state/raft/raft.go @@ -34,6 +34,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/peer" + "google.golang.org/grpc/status" ) var ( @@ -929,11 +930,11 @@ func (n *Node) Join(ctx context.Context, req *api.JoinRequest) (*api.JoinRespons defer n.membershipLock.Unlock() if !n.IsMember() { - return nil, grpc.Errorf(codes.FailedPrecondition, "%s", ErrNoRaftMember.Error()) + return nil, status.Errorf(codes.FailedPrecondition, "%s", ErrNoRaftMember.Error()) } if !n.isLeader() { - return nil, grpc.Errorf(codes.FailedPrecondition, "%s", ErrLostLeadership.Error()) + return nil, status.Errorf(codes.FailedPrecondition, "%s", ErrLostLeadership.Error()) } remoteAddr := req.Addr @@ -944,7 +945,7 @@ func (n *Node) Join(ctx context.Context, req *api.JoinRequest) (*api.JoinRespons requestHost, requestPort, err := net.SplitHostPort(remoteAddr) if err != nil { - return nil, grpc.Errorf(codes.InvalidArgument, "invalid address %s in raft join request", remoteAddr) + return nil, status.Errorf(codes.InvalidArgument, "invalid address %s in raft join request", remoteAddr) } requestIP := net.ParseIP(requestHost) @@ -1118,7 +1119,7 @@ func (n *Node) UpdateNode(id uint64, addr string) { // membership to an active member of the raft func (n *Node) Leave(ctx context.Context, req *api.LeaveRequest) (*api.LeaveResponse, error) { if req.Node == nil { - return nil, grpc.Errorf(codes.InvalidArgument, "no node information provided") + return nil, status.Errorf(codes.InvalidArgument, "no node information provided") } nodeInfo, err := ca.RemoteNode(ctx) @@ -1315,7 +1316,7 @@ func (n *Node) ProcessRaftMessage(ctx context.Context, msg *api.ProcessRaftMessa // a node in the remove set if n.cluster.IsIDRemoved(msg.Message.From) { n.processRaftMessageLogger(ctx, msg).Debug("received message from removed member") - return nil, grpc.Errorf(codes.NotFound, "%s", membership.ErrMemberRemoved.Error()) + return nil, status.Errorf(codes.NotFound, "%s", membership.ErrMemberRemoved.Error()) } ctx, cancel := n.WithContext(ctx) @@ -1393,7 +1394,7 @@ func (n *Node) ResolveAddress(ctx context.Context, msg *api.ResolveAddressReques member := n.cluster.GetMember(msg.RaftID) if member == nil { - return nil, grpc.Errorf(codes.NotFound, "member %x not found", msg.RaftID) + return nil, status.Errorf(codes.NotFound, "member %x not found", msg.RaftID) } return &api.ResolveAddressResponse{Addr: member.Addr}, nil } diff --git a/manager/state/raft/transport/mock_raft_test.go b/manager/state/raft/transport/mock_raft_test.go index 703570fb84..3b7a68e7bd 100644 --- a/manager/state/raft/transport/mock_raft_test.go +++ b/manager/state/raft/transport/mock_raft_test.go @@ -4,16 +4,15 @@ import ( "net" "time" - "golang.org/x/net/context" - "github.com/coreos/etcd/raft" "github.com/coreos/etcd/raft/raftpb" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/manager/health" "github.com/docker/swarmkit/manager/state/raft/membership" - + "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) type snapshotReport struct { @@ -89,7 +88,7 @@ func (r *mockRaft) RemovePeer(id uint64) error { func (r *mockRaft) ProcessRaftMessage(ctx context.Context, req *api.ProcessRaftMessageRequest) (*api.ProcessRaftMessageResponse, error) { if r.removed[req.Message.From] { - return nil, grpc.Errorf(codes.NotFound, "%s", membership.ErrMemberRemoved.Error()) + return nil, status.Errorf(codes.NotFound, "%s", membership.ErrMemberRemoved.Error()) } r.processedMessages <- req.Message return &api.ProcessRaftMessageResponse{}, nil diff --git a/manager/watchapi/watch.go b/manager/watchapi/watch.go index 53bed49f1c..223dcb55d6 100644 --- a/manager/watchapi/watch.go +++ b/manager/watchapi/watch.go @@ -1,12 +1,11 @@ package watchapi import ( - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/manager/state" "github.com/docker/swarmkit/manager/state/store" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // Watch starts a stream that returns any changes to objects that match @@ -26,7 +25,7 @@ func (s *Server) Watch(request *api.WatchRequest, stream api.Watch_WatchServer) watchArgs, err := api.ConvertWatchArgs(request.Entries) if err != nil { - return grpc.Errorf(codes.InvalidArgument, "%s", err.Error()) + return status.Errorf(codes.InvalidArgument, "%s", err.Error()) } watchArgs = append(watchArgs, state.EventCommit{}) diff --git a/protobuf/plugin/raftproxy/raftproxy.go b/protobuf/plugin/raftproxy/raftproxy.go index 14cf00ee0e..b29f566eb5 100644 --- a/protobuf/plugin/raftproxy/raftproxy.go +++ b/protobuf/plugin/raftproxy/raftproxy.go @@ -36,12 +36,12 @@ func (g *raftProxyGen) genProxyConstructor(s *descriptor.ServiceDescriptorProto) g.gen.P(`redirectChecker := func(ctx context.Context)(context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) @@ -376,6 +376,7 @@ func (g *raftProxyGen) GenerateImports(file *generator.FileDescriptor) { } g.gen.P("import raftselector \"github.com/docker/swarmkit/manager/raftselector\"") g.gen.P("import codes \"google.golang.org/grpc/codes\"") + g.gen.P("import status \"google.golang.org/grpc/status\"") g.gen.P("import metadata \"google.golang.org/grpc/metadata\"") g.gen.P("import transport \"google.golang.org/grpc/transport\"") // don't conflict with import added by ptypes diff --git a/protobuf/plugin/raftproxy/test/service.pb.go b/protobuf/plugin/raftproxy/test/service.pb.go index a48121e829..7cdd61f1dd 100644 --- a/protobuf/plugin/raftproxy/test/service.pb.go +++ b/protobuf/plugin/raftproxy/test/service.pb.go @@ -32,6 +32,7 @@ import ( import raftselector "github.com/docker/swarmkit/manager/raftselector" import codes "google.golang.org/grpc/codes" +import status "google.golang.org/grpc/status" import metadata "google.golang.org/grpc/metadata" import transport "google.golang.org/grpc/transport" import rafttime "time" @@ -973,12 +974,12 @@ func NewRaftProxyRouteGuideServer(local RouteGuideServer, connSelector raftselec redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) @@ -1256,12 +1257,12 @@ func NewRaftProxyHealthServer(local HealthServer, connSelector raftselector.Conn redirectChecker := func(ctx context.Context) (context.Context, error) { s, ok := transport.StreamFromContext(ctx) if !ok { - return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context") + return ctx, status.Errorf(codes.InvalidArgument, "remote addr is not found in context") } addr := s.ServerTransport().RemoteAddr().String() md, ok := metadata.FromContext(ctx) if ok && len(md["redirect"]) != 0 { - return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) + return ctx, status.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"]) } if !ok { md = metadata.New(map[string]string{}) diff --git a/protobuf/plugin/storeobject/storeobject.go b/protobuf/plugin/storeobject/storeobject.go index 225802afb0..51f7f9a4e6 100644 --- a/protobuf/plugin/storeobject/storeobject.go +++ b/protobuf/plugin/storeobject/storeobject.go @@ -552,7 +552,7 @@ func (d *storeObjectGen) genMsgStoreObject(m *generator.Descriptor, storeObject /* switch v := filter.By.(type) { default: - return nil, grpc.Errorf(codes.InvalidArgument, "selector type %T is unsupported for tasks", filter.By) + return nil, status.Errorf(codes.InvalidArgument, "selector type %T is unsupported for tasks", filter.By) } */