示例#1
0
// UpdateCluster updates a Cluster referenced by ClusterID with the given ClusterSpec.
// - Returns `NotFound` if the Cluster is not found.
// - Returns `InvalidArgument` if the ClusterSpec is malformed.
// - Returns `Unimplemented` if the ClusterSpec references unimplemented features.
// - 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())
	}
	if err := validateClusterSpec(request.Spec); err != nil {
		return nil, err
	}

	var cluster *api.Cluster
	err := s.store.Update(func(tx store.Tx) error {
		cluster = store.GetCluster(tx, request.ClusterID)
		if cluster == nil {
			return nil
		}
		cluster.Meta.Version = *request.ClusterVersion
		cluster.Spec = *request.Spec.Copy()
		return store.UpdateCluster(tx, cluster)
	})
	if err != nil {
		return nil, err
	}
	if cluster == nil {
		return nil, grpc.Errorf(codes.NotFound, "cluster %s not found", request.ClusterID)
	}

	redactedClusters := redactClusters([]*api.Cluster{cluster})

	// WARN: we should never return cluster here. We need to redact the private fields first.
	return &api.UpdateClusterResponse{
		Cluster: redactedClusters[0],
	}, nil
}
示例#2
0
func TestAdminClientGetChildren(t *testing.T) {
	connectAdminApiClient()
	tests := []struct {
		gcr *apipb.GetChildrenFromProfileRequest
		err error
	}{
		{
			gcr: &apipb.GetChildrenFromProfileRequest{
				ProfileId: clientsub,
			},
			err: grpc.Errorf(2, "Invalid ID"),
		},
		{
			gcr: &apipb.GetChildrenFromProfileRequest{},
			err: grpc.Errorf(2, "Invalid ID"),
		},
	}

	for i, tt := range tests {
		_, err := apiClient.GetChildren(context.Background(), tt.gcr)
		if err != tt.err {
			t.Fatalf("case %d, expected %v, got %v", i, tt.err, err)
		}
	}
}
示例#3
0
func NewRaftProxyHealthServer(local HealthServer, connSelector raftpicker.Interface, cluster raftpicker.RaftCluster, ctxMod func(context.Context) (context.Context, error)) HealthServer {
	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")
		}
		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"])
		}
		if !ok {
			md = metadata.New(map[string]string{})
		}
		md["redirect"] = append(md["redirect"], addr)
		return metadata.NewContext(ctx, md), nil
	}
	mods := []func(context.Context) (context.Context, error){redirectChecker}
	mods = append(mods, ctxMod)

	return &raftProxyHealthServer{
		local:        local,
		cluster:      cluster,
		connSelector: connSelector,
		ctxMods:      mods,
	}
}
func request_FlowCombination_RpcPathNestedStream_2(ctx context.Context, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathNestedStreamClient, error) {
	var protoReq NestedProto

	if err := json.NewDecoder(req.Body).Decode(&protoReq.C); err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "%v", err)
	}

	var (
		val string
		ok  bool
		err error
		_   = err
	)

	val, ok = pathParams["a.str"]
	if !ok {
		return nil, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str")
	}

	err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val)

	if err != nil {
		return nil, err
	}

	if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathNestedStream_2); err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "%v", err)
	}

	return client.RpcPathNestedStream(ctx, &protoReq)
}
示例#5
0
func request_API_CreateRepo_0(ctx context.Context, client APIClient, req *http.Request, pathParams map[string]string) (proto.Message, error) {
	var protoReq CreateRepoRequest

	var (
		val string
		ok  bool
		err error
		_   = err
	)

	val, ok = pathParams["repo.name"]
	if !ok {
		return nil, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "repo.name")
	}

	err = runtime.PopulateFieldFromPath(&protoReq, "repo.name", val)

	if err != nil {
		return nil, err
	}

	if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_API_CreateRepo_0); err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "%v", err)
	}

	return client.CreateRepo(ctx, &protoReq)
}
示例#6
0
// GetNode returns a Node given a NodeID.
// - Returns `InvalidArgument` if NodeID is not provided.
// - 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())
	}

	var node *api.Node
	s.store.View(func(tx store.ReadTx) {
		node = store.GetNode(tx, request.NodeID)
	})
	if node == nil {
		return nil, grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID)
	}

	if s.raft != nil {
		memberlist := s.raft.GetMemberlist()
		for _, member := range memberlist {
			if member.NodeID == node.ID {
				node.ManagerStatus = &api.ManagerStatus{
					RaftID:       member.RaftID,
					Addr:         member.Addr,
					Leader:       member.Status.Leader,
					Reachability: member.Status.Reachability,
				}
				break
			}
		}
	}

	return &api.GetNodeResponse{
		Node: node,
	}, nil
}
func request_FlowCombination_RpcPathSingleNestedRpc_0(ctx context.Context, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, error) {
	var protoReq SingleNestedProto

	var (
		val string
		ok  bool
		err error
		_   = err
	)

	val, ok = pathParams["a.str"]
	if !ok {
		return nil, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str")
	}

	err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val)

	if err != nil {
		return nil, err
	}

	if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathSingleNestedRpc_0); err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "%v", err)
	}

	return client.RpcPathSingleNestedRpc(ctx, &protoReq)
}
示例#8
0
func TestRegistryAdminClientListGames(t *testing.T) {
	connectRegistryAdminClient()
	tests := []struct {
		p   *apipb.GetGameReleaseRequest
		err error
	}{
		{
			p: &apipb.GetGameReleaseRequest{
				GameId:  "76b30f8c0c96db0001aa911f",
				Version: "2.2.2",
				State:   1,
			},
			err: grpc.Errorf(2, "No data found"),
		},
		{
			p:   &apipb.GetGameReleaseRequest{},
			err: grpc.Errorf(2, "invalid id"),
		},
	}

	for i, tt := range tests {
		_, err := registryClient.GetRelease(context.Background(), tt.p)
		if err != tt.err {
			t.Fatalf("case %d, expected %v, got %v", i, tt.err, err)
		}
	}
}
func request_ABitOfEverythingService_Update_0(ctx context.Context, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, error) {
	var protoReq ABitOfEverything

	if err := json.NewDecoder(req.Body).Decode(&protoReq); err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "%v", err)
	}

	var (
		val string
		ok  bool
		err error
		_   = err
	)

	val, ok = pathParams["uuid"]
	if !ok {
		return nil, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid")
	}

	protoReq.Uuid, err = runtime.String(val)

	if err != nil {
		return nil, err
	}

	return client.Update(ctx, &protoReq)
}
示例#10
0
//admin-client
func TestRegistryAdminClientGet(t *testing.T) {
	connectRegistryAdminClient()
	tests := []struct {
		p   *apipb.GetGameRequest
		err error
	}{
		{
			p: &apipb.GetGameRequest{
				UniqueName: "sample-otsimo-game-1",
			},
		},
		{
			p: &apipb.GetGameRequest{
				UniqueName: "myGameYeah1",
			},
			err: grpc.Errorf(2, "No data found"),
		},
		{
			p:   &apipb.GetGameRequest{},
			err: grpc.Errorf(2, "No data found"),
		},
	}

	for i, tt := range tests {
		_, err := registryClient.Get(context.Background(), tt.p)
		if err != tt.err {
			t.Fatalf("case %d, expected %v, got %v", i, tt.err, err)
		}
	}
}
示例#11
0
func TestRegistryAdminClientChangeReleaseState(t *testing.T) {
	connectRegistryAdminClient()
	tests := []struct {
		p   *apipb.ValidateRequest
		err error
	}{
		{
			p: &apipb.ValidateRequest{
				GameId:      "56b30f8c0c96db0001aa911f",
				GameVersion: "0.0.1",
				NewState:    3,
			},
			err: grpc.Errorf(2, "No data found"),
		},
		{
			p:   &apipb.ValidateRequest{},
			err: grpc.Errorf(2, "invalid id"),
		},
	}

	for i, tt := range tests {
		_, err := registryClient.ChangeReleaseState(context.Background(), tt.p)
		if err != tt.err {
			t.Fatalf("case %d, expected %v, got %v", i, tt.err, err)
		}
	}
}
示例#12
0
文件: status.go 项目: knz/cockroach
// handleNodeStatus handles GET requests for a single node's status.
func (s *statusServer) Node(
	ctx context.Context, req *serverpb.NodeRequest,
) (*status.NodeStatus, error) {
	ctx = s.AnnotateCtx(ctx)
	nodeID, _, err := s.parseNodeID(req.NodeId)
	if err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument, err.Error())
	}

	key := keys.NodeStatusKey(nodeID)
	b := &client.Batch{}
	b.Get(key)
	if err := s.db.Run(ctx, b); err != nil {
		log.Error(ctx, err)
		return nil, grpc.Errorf(codes.Internal, err.Error())
	}

	var nodeStatus status.NodeStatus
	if err := b.Results[0].Rows[0].ValueProto(&nodeStatus); err != nil {
		err = errors.Errorf("could not unmarshal NodeStatus from %s: %s", key, err)
		log.Error(ctx, err)
		return nil, grpc.Errorf(codes.Internal, err.Error())
	}
	return &nodeStatus, nil
}
示例#13
0
文件: status.go 项目: knz/cockroach
// Nodes returns all node statuses.
func (s *statusServer) Nodes(
	ctx context.Context, req *serverpb.NodesRequest,
) (*serverpb.NodesResponse, error) {
	ctx = s.AnnotateCtx(ctx)
	startKey := keys.StatusNodePrefix
	endKey := startKey.PrefixEnd()

	b := &client.Batch{}
	b.Scan(startKey, endKey)
	if err := s.db.Run(ctx, b); err != nil {
		log.Error(ctx, err)
		return nil, grpc.Errorf(codes.Internal, err.Error())
	}
	rows := b.Results[0].Rows

	resp := serverpb.NodesResponse{
		Nodes: make([]status.NodeStatus, len(rows)),
	}
	for i, row := range rows {
		if err := row.ValueProto(&resp.Nodes[i]); err != nil {
			log.Error(ctx, err)
			return nil, grpc.Errorf(codes.Internal, err.Error())
		}
	}
	return &resp, nil
}
示例#14
0
func (r *RegistryServer) AllReleases(ctx context.Context, in *apipb.GetGameRequest) (*apipb.AllGameReleases, error) {
	log.Infof("grpc:AllReleases(): %+v", in)

	repo := r.server.DB.GetGameReleaseRepo()
	gameID := in.GameId
	if len(gameID) == 0 {
		g, err := r.server.DB.GetGameRepo().GetGameWithUniqueId(in.UniqueName)
		if err != nil {
			return nil, grpc.Errorf(codes.NotFound, "game not found")
		}
		gameID = g.Id
	}
	list, err := repo.All(gameID)
	if err != nil {
		return nil, grpc.Errorf(codes.Internal, "failed to get releases, %v", err)
	}
	res := &apipb.AllGameReleases{
		GameId:   gameID,
		Releases: make([]*apipb.AllGameReleases_MiniRelease, len(list)),
	}
	for i, r := range list {
		res.Releases[i] = &apipb.AllGameReleases_MiniRelease{
			Version:      r.Version,
			ReleasedAt:   r.ReleasedAt,
			ReleaseState: r.ReleaseState,
		}
	}
	return res, nil
}
示例#15
0
func request_ChannelList_Update_0(ctx context.Context, marshaler runtime.Marshaler, client ChannelListClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
	var protoReq UpdateChannelListRequest
	var metadata runtime.ServerMetadata

	if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil {
		return nil, metadata, grpc.Errorf(codes.InvalidArgument, "%v", err)
	}

	var (
		val string
		ok  bool
		err error
		_   = err
	)

	val, ok = pathParams["id"]
	if !ok {
		return nil, metadata, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "id")
	}

	protoReq.Id, err = runtime.Int64(val)

	if err != nil {
		return nil, metadata, err
	}

	msg, err := client.Update(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
	return msg, metadata, err

}
示例#16
0
func (as *authServer) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
	user, err := getUser(db, request.Username)
	if err != nil {
		return nil, err
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.Password))
	if err != nil {
		return nil, grpc.Errorf(codes.PermissionDenied, "")
	}

	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	token.Claims["admin"] = user.IsAdmin
	token.Claims["iss"] = "auth.service"
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["email"] = user.Email
	token.Claims["sub"] = user.Username

	tokenString, err := token.SignedString(as.jwtPrivatekey)
	if err != nil {
		return nil, grpc.Errorf(codes.Internal, err.Error())
	}

	return &pb.LoginResponse{tokenString}, nil
}
示例#17
0
// Query is an endpoint that returns data for one or more metrics over a
// specific time span.
func (s *Server) Query(ctx context.Context, request *tspb.TimeSeriesQueryRequest) (*tspb.TimeSeriesQueryResponse, error) {
	if len(request.Queries) == 0 {
		return nil, grpc.Errorf(codes.InvalidArgument, "Queries cannot be empty")
	}

	response := tspb.TimeSeriesQueryResponse{
		Results: make([]tspb.TimeSeriesQueryResponse_Result, 0, len(request.Queries)),
	}
	for _, q := range request.Queries {
		datapoints, sources, err := s.db.Query(q, Resolution10s, request.StartNanos, request.EndNanos)
		if err != nil {
			return nil, grpc.Errorf(codes.Internal, err.Error())
		}
		result := tspb.TimeSeriesQueryResponse_Result{
			Query:      q,
			Datapoints: datapoints,
		}
		// TODO(tamird): Remove this (and all other) explicit setting of defaults.
		// It is currently required because the client side doesn't know about
		// proto defaults.
		result.SourceAggregator = q.GetSourceAggregator().Enum()
		result.Downsampler = q.GetDownsampler().Enum()
		result.Derivative = q.GetDerivative().Enum()

		result.Sources = sources
		response.Results = append(response.Results, result)
	}

	return &response, nil
}
示例#18
0
//Sign signs a message and returns the signature using a private key associate with the KeyID from the SignatureRequest
func (s *SignerServer) Sign(ctx context.Context, sr *pb.SignatureRequest) (*pb.Signature, error) {
	tufKey, service, err := FindKeyByID(s.CryptoServices, sr.KeyID)

	logger := ctxu.GetLogger(ctx)

	if err != nil {
		logger.Errorf("Sign: key %s not found", sr.KeyID.ID)
		return nil, grpc.Errorf(codes.NotFound, "key %s not found", sr.KeyID.ID)
	}

	privKey, _, err := service.GetPrivateKey(tufKey.ID())
	if err != nil {
		logger.Errorf("Sign: key %s not found", sr.KeyID.ID)
		return nil, grpc.Errorf(codes.NotFound, "key %s not found", sr.KeyID.ID)
	}
	sig, err := privKey.Sign(rand.Reader, sr.Content, nil)
	if err != nil {
		logger.Errorf("Sign: signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content)
		return nil, grpc.Errorf(codes.Internal, "Signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content)
	}

	logger.Info("Sign: Signed ", string(sr.Content), " with KeyID ", sr.KeyID.ID)

	signature := &pb.Signature{
		KeyInfo: &pb.KeyInfo{
			KeyID:     &pb.KeyID{ID: tufKey.ID()},
			Algorithm: &pb.Algorithm{Algorithm: tufKey.Algorithm()},
		},
		Algorithm: &pb.Algorithm{Algorithm: privKey.SignatureAlgorithm().String()},
		Content:   sig,
	}

	return signature, nil
}
示例#19
0
// RemoveNode removes a Node referenced by NodeID with the given NodeSpec.
// - Returns NotFound if the Node is not found.
// - Returns FailedPrecondition if the Node has manager role (and is part of the memberlist) or is not shut down.
// - Returns InvalidArgument if NodeID or NodeVersion is not valid.
// - 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())
	}

	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)
		}
		if node.Spec.Role == 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)
			}
			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)
			}
		}
		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 store.DeleteNode(tx, request.NodeID)
	})
	if err != nil {
		return nil, err
	}
	return &api.RemoveNodeResponse{}, nil
}
示例#20
0
func validateRestartPolicy(rp *api.RestartPolicy) error {
	if rp == nil {
		return nil
	}

	if rp.Delay != nil {
		delay, err := ptypes.Duration(rp.Delay)
		if err != nil {
			return err
		}
		if delay < 0 {
			return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-delay cannot be negative")
		}
	}

	if rp.Window != nil {
		win, err := ptypes.Duration(rp.Window)
		if err != nil {
			return err
		}
		if win < 0 {
			return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-window cannot be negative")
		}
	}

	return nil
}
func request_FlowCombination_RpcBodyStream_6(ctx context.Context, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, error) {
	var protoReq NonEmptyProto

	var (
		val string
		ok  bool
		err error
		_   = err
	)

	val, ok = pathParams["a"]
	if !ok {
		return nil, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "a")
	}

	protoReq.A, err = runtime.String(val)

	if err != nil {
		return nil, err
	}

	if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyStream_6); err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "%v", err)
	}

	return client.RpcBodyStream(ctx, &protoReq)
}
示例#22
0
func request_API_GetDistance_0(ctx context.Context, client APIClient, req *http.Request, pathParams map[string]string) (proto.Message, error) {
	var protoReq GetDistanceRequest

	var (
		val string
		ok  bool
		err error
		_   = err
	)

	val, ok = pathParams["source_airport_id"]
	if !ok {
		return nil, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "source_airport_id")
	}

	protoReq.SourceAirportId, err = runtime.String(val)

	if err != nil {
		return nil, err
	}

	val, ok = pathParams["destination_airport_id"]
	if !ok {
		return nil, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "destination_airport_id")
	}

	protoReq.DestinationAirportId, err = runtime.String(val)

	if err != nil {
		return nil, err
	}

	return client.GetDistance(ctx, &protoReq)
}
示例#23
0
func request_ApplicationManager_SetApplication_0(ctx context.Context, marshaler runtime.Marshaler, client ApplicationManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
	var protoReq Application
	var metadata runtime.ServerMetadata

	if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil {
		return nil, metadata, grpc.Errorf(codes.InvalidArgument, "%v", err)
	}

	var (
		val string
		ok  bool
		err error
		_   = err
	)

	val, ok = pathParams["app_id"]
	if !ok {
		return nil, metadata, grpc.Errorf(codes.InvalidArgument, "missing parameter %s", "app_id")
	}

	protoReq.AppId, err = runtime.String(val)

	if err != nil {
		return nil, metadata, err
	}

	msg, err := client.SetApplication(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
	return msg, metadata, err

}
示例#24
0
// RemoveNode updates a Node referenced by NodeID with the given NodeSpec.
// - Returns NotFound if the Node is not found.
// - Returns FailedPrecondition if the Node has manager role or not shut down.
// - Returns InvalidArgument if NodeID or NodeVersion is not valid.
// - 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())
	}
	if s.raft != nil {
		memberlist := s.raft.GetMemberlist()

		for _, member := range memberlist {
			if member.NodeID == request.NodeID {
				return nil, grpc.Errorf(codes.FailedPrecondition, "node %s is a cluster manager and is part of the quorum. It must be demoted to worker before removal", request.NodeID)
			}
		}
	}

	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)
		}
		if node.Spec.Role == api.NodeRoleManager {
			return grpc.Errorf(codes.FailedPrecondition, "node %s role is set to manager. It should be demoted to worker for safe removal", request.NodeID)
		}
		if node.Status.State == api.NodeStatus_READY {
			return grpc.Errorf(codes.FailedPrecondition, "node %s is not down and can't be removed", request.NodeID)
		}
		return store.DeleteNode(tx, request.NodeID)
	})
	if err != nil {
		return nil, err
	}
	return &api.RemoveNodeResponse{}, nil
}
示例#25
0
文件: auth.go 项目: yongtang/swarmkit
// AuthorizeForwardedRoleAndOrg checks for proper roles and organization of caller. The RPC may have
// been proxied by a manager, in which case the manager is authenticated and
// so is the certificate information that it forwarded. It returns the node ID
// of the original client.
func AuthorizeForwardedRoleAndOrg(ctx context.Context, authorizedRoles, forwarderRoles []string, org string, blacklistedCerts map[string]*api.BlacklistedCertificate) (string, error) {
	if isForwardedRequest(ctx) {
		_, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, forwarderRoles...)
		if err != nil {
			return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarder role: %v", err)
		}

		// This was a forwarded request. Authorize the forwarder, and
		// check if the forwarded role matches one of the authorized
		// roles.
		_, forwardedID, forwardedOrg, forwardedOUs := forwardedTLSInfoFromContext(ctx)

		if len(forwardedOUs) == 0 || forwardedID == "" || forwardedOrg == "" {
			return "", grpc.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)
		}

		if forwardedOrg != org {
			return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: organization mismatch, expecting: %s", org)
		}

		return forwardedID, nil
	}

	// There wasn't any node being forwarded, check if this is a direct call by the expected role
	nodeID, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, authorizedRoles...)
	if err == nil {
		return nodeID, nil
	}

	return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: unauthorized peer role: %v", err)
}
示例#26
0
文件: raft.go 项目: maxim28/docker
// ProcessRaftMessage calls 'Step' which advances the
// raft state machine with the provided message on the
// receiving node
func (n *Node) ProcessRaftMessage(ctx context.Context, msg *api.ProcessRaftMessageRequest) (*api.ProcessRaftMessageResponse, error) {
	if msg == nil || msg.Message == nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "no message provided")
	}

	// Don't process the message if this comes from
	// a node in the remove set
	if n.cluster.IsIDRemoved(msg.Message.From) {
		return nil, ErrMemberRemoved
	}

	if msg.Message.Type == raftpb.MsgProp {
		// We don't accepted forwarded proposals. Our
		// current architecture depends on only the leader
		// making proposals, so in-flight proposals can be
		// guaranteed not to conflict.
		return nil, grpc.Errorf(codes.InvalidArgument, "proposals not accepted")
	}

	// can't stop the raft node while an async RPC is in progress
	n.stopMu.RLock()
	defer n.stopMu.RUnlock()

	if !n.IsMember() {
		return nil, ErrNoRaftMember
	}

	if err := n.Step(n.Ctx, *msg.Message); err != nil {
		return nil, err
	}

	return &api.ProcessRaftMessageResponse{}, nil
}
示例#27
0
//update game entry
func TestUpdateGameEntry(t *testing.T) {
	connectApipb()
	tests := []struct {
		gcr *apipb.GameEntryRequest
		err error
	}{
		{
			gcr: &apipb.GameEntryRequest{
				ChildId: "000000000000000000000001",
				GameId:  "000000000000000000000001",
			},
		},
		{
			gcr: &apipb.GameEntryRequest{
				ChildId: "000000000000000000000099",
				GameId:  "000000000000000000000011",
			},
			err: grpc.Errorf(2, "Not found"),
		},

		{
			gcr: &apipb.GameEntryRequest{},
			err: grpc.Errorf(2, "Invalid ID"),
		},
	}

	for i, tt := range tests {
		_, err := apiClient.UpdateGameEntry(context.Background(), tt.gcr)
		if err != tt.err {
			t.Fatalf("case %d, expected %v, got %v", i, tt.err, err)
		}
	}
}
示例#28
0
func (s *walletServer) ImportPrivateKey(ctx context.Context, req *pb.ImportPrivateKeyRequest) (
	*pb.ImportPrivateKeyResponse, error) {

	defer zero.Bytes(req.Passphrase)

	wif, err := btcutil.DecodeWIF(req.PrivateKeyWif)
	if err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument,
			"Invalid WIF-encoded private key: %v", err)
	}

	lock := make(chan time.Time, 1)
	defer func() {
		lock <- time.Time{} // send matters, not the value
	}()
	err = s.wallet.Unlock(req.Passphrase, lock)
	if err != nil {
		return nil, translateError(err)
	}

	// At the moment, only the special-cased import account can be used to
	// import keys.
	if req.Account != waddrmgr.ImportedAddrAccount {
		return nil, grpc.Errorf(codes.InvalidArgument,
			"Only the imported account accepts private key imports")
	}

	_, err = s.wallet.ImportPrivateKey(wif, nil, req.Rescan)
	if err != nil {
		return nil, translateError(err)
	}

	return &pb.ImportPrivateKeyResponse{}, nil
}
示例#29
0
func (h *handlerManager) validateTTNAuthAppContext(ctx context.Context, appID string) (context.Context, *claims.Claims, error) {
	md, err := api.MetadataFromContext(ctx)
	if err != nil {
		return ctx, nil, err
	}
	// If token is empty, try to get the access key and convert it into a token
	token, err := api.TokenFromMetadata(md)
	if err != nil || token == "" {
		key, err := api.KeyFromMetadata(md)
		if err != nil {
			return ctx, nil, errors.NewErrInvalidArgument("Metadata", "neither token nor key present")
		}
		token, err := h.handler.Component.ExchangeAppKeyForToken(appID, key)
		if err != nil {
			return ctx, nil, err
		}
		md = metadata.Join(md, metadata.Pairs("token", token))
		ctx = metadata.NewContext(ctx, md)
	}
	claims, err := h.handler.Component.ValidateTTNAuthContext(ctx)
	if err != nil {
		return ctx, nil, err
	}
	if h.clientRate.Limit(claims.Subject) {
		return ctx, claims, grpc.Errorf(codes.ResourceExhausted, "Rate limit for client reached")
	}
	if h.applicationRate.Limit(appID) {
		return ctx, claims, grpc.Errorf(codes.ResourceExhausted, "Rate limit for application reached")
	}
	return ctx, claims, nil
}
示例#30
0
func validateClusterSpec(spec *api.ClusterSpec) error {
	if spec == nil {
		return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
	}

	// Validate that duration being provided is valid, and over our minimum
	if spec.CAConfig.NodeCertExpiry != nil {
		expiry, err := ptypes.Duration(spec.CAConfig.NodeCertExpiry)
		if err != nil {
			return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
		}
		if expiry < ca.MinNodeCertExpiration {
			return grpc.Errorf(codes.InvalidArgument, "minimum certificate expiry time is: %s", ca.MinNodeCertExpiration)
		}
	}

	// Validate that AcceptancePolicies only include Secrets that are bcrypted
	// TODO(diogo): Add a global list of acceptace algorithms. We only support bcrypt for now.
	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 nil
}