diff --git a/api/fabric/permit/v1/permit.pb.go b/api/fabric/permit/v1/permit.pb.go new file mode 100644 index 000000000..0baae0727 --- /dev/null +++ b/api/fabric/permit/v1/permit.pb.go @@ -0,0 +1,335 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The node-to-gateway probe permit contract. It is internal to galactic: +// only a cell's node identities may call it. A node asks the cell's gateway +// for a permit before it runs a probe an operator sent it directly, so every +// probe in the cell draws from the same aggregate packet budgets. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc (unknown) +// source: fabric/permit/v1/permit.proto + +package permitv1 + +import ( + v1 "go.datum.net/galactic/api/fabric/v1" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type RequestPermitRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // node is the calling node; it must be the node the caller's identity + // belongs to. + Node string `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` + // operator is the operator identity name the probe runs for; its packet + // budget is charged. + Operator string `protobuf:"bytes,2,opt,name=operator,proto3" json:"operator,omitempty"` + // request_id is the operator's request ID. + RequestId string `protobuf:"bytes,3,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + // query is the probe, in canonical form. + Query *v1.Query `protobuf:"bytes,4,opt,name=query,proto3" json:"query,omitempty"` + // expires_at is the request's absolute expiration; the permit's deadline + // is never later. + ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RequestPermitRequest) Reset() { + *x = RequestPermitRequest{} + mi := &file_fabric_permit_v1_permit_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RequestPermitRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RequestPermitRequest) ProtoMessage() {} + +func (x *RequestPermitRequest) ProtoReflect() protoreflect.Message { + mi := &file_fabric_permit_v1_permit_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RequestPermitRequest.ProtoReflect.Descriptor instead. +func (*RequestPermitRequest) Descriptor() ([]byte, []int) { + return file_fabric_permit_v1_permit_proto_rawDescGZIP(), []int{0} +} + +func (x *RequestPermitRequest) GetNode() string { + if x != nil { + return x.Node + } + return "" +} + +func (x *RequestPermitRequest) GetOperator() string { + if x != nil { + return x.Operator + } + return "" +} + +func (x *RequestPermitRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +func (x *RequestPermitRequest) GetQuery() *v1.Query { + if x != nil { + return x.Query + } + return nil +} + +func (x *RequestPermitRequest) GetExpiresAt() *timestamppb.Timestamp { + if x != nil { + return x.ExpiresAt + } + return nil +} + +type RequestPermitResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Permit *v1.ProbePermit `protobuf:"bytes,1,opt,name=permit,proto3" json:"permit,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RequestPermitResponse) Reset() { + *x = RequestPermitResponse{} + mi := &file_fabric_permit_v1_permit_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RequestPermitResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RequestPermitResponse) ProtoMessage() {} + +func (x *RequestPermitResponse) ProtoReflect() protoreflect.Message { + mi := &file_fabric_permit_v1_permit_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RequestPermitResponse.ProtoReflect.Descriptor instead. +func (*RequestPermitResponse) Descriptor() ([]byte, []int) { + return file_fabric_permit_v1_permit_proto_rawDescGZIP(), []int{1} +} + +func (x *RequestPermitResponse) GetPermit() *v1.ProbePermit { + if x != nil { + return x.Permit + } + return nil +} + +type ReleasePermitRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // node is the calling node. + Node string `protobuf:"bytes,1,opt,name=node,proto3" json:"node,omitempty"` + // id is the finished permit's ID. + Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ReleasePermitRequest) Reset() { + *x = ReleasePermitRequest{} + mi := &file_fabric_permit_v1_permit_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ReleasePermitRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReleasePermitRequest) ProtoMessage() {} + +func (x *ReleasePermitRequest) ProtoReflect() protoreflect.Message { + mi := &file_fabric_permit_v1_permit_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReleasePermitRequest.ProtoReflect.Descriptor instead. +func (*ReleasePermitRequest) Descriptor() ([]byte, []int) { + return file_fabric_permit_v1_permit_proto_rawDescGZIP(), []int{2} +} + +func (x *ReleasePermitRequest) GetNode() string { + if x != nil { + return x.Node + } + return "" +} + +func (x *ReleasePermitRequest) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +type ReleasePermitResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ReleasePermitResponse) Reset() { + *x = ReleasePermitResponse{} + mi := &file_fabric_permit_v1_permit_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ReleasePermitResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReleasePermitResponse) ProtoMessage() {} + +func (x *ReleasePermitResponse) ProtoReflect() protoreflect.Message { + mi := &file_fabric_permit_v1_permit_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ReleasePermitResponse.ProtoReflect.Descriptor instead. +func (*ReleasePermitResponse) Descriptor() ([]byte, []int) { + return file_fabric_permit_v1_permit_proto_rawDescGZIP(), []int{3} +} + +var File_fabric_permit_v1_permit_proto protoreflect.FileDescriptor + +const file_fabric_permit_v1_permit_proto_rawDesc = "" + + "\n" + + "\x1dfabric/permit/v1/permit.proto\x12\x10fabric.permit.v1\x1a\x16fabric/v1/fabric.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\xc8\x01\n" + + "\x14RequestPermitRequest\x12\x12\n" + + "\x04node\x18\x01 \x01(\tR\x04node\x12\x1a\n" + + "\boperator\x18\x02 \x01(\tR\boperator\x12\x1d\n" + + "\n" + + "request_id\x18\x03 \x01(\tR\trequestId\x12&\n" + + "\x05query\x18\x04 \x01(\v2\x10.fabric.v1.QueryR\x05query\x129\n" + + "\n" + + "expires_at\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\"G\n" + + "\x15RequestPermitResponse\x12.\n" + + "\x06permit\x18\x01 \x01(\v2\x16.fabric.v1.ProbePermitR\x06permit\":\n" + + "\x14ReleasePermitRequest\x12\x12\n" + + "\x04node\x18\x01 \x01(\tR\x04node\x12\x0e\n" + + "\x02id\x18\x02 \x01(\tR\x02id\"\x17\n" + + "\x15ReleasePermitResponse2\xd3\x01\n" + + "\rPermitService\x12`\n" + + "\rRequestPermit\x12&.fabric.permit.v1.RequestPermitRequest\x1a'.fabric.permit.v1.RequestPermitResponse\x12`\n" + + "\rReleasePermit\x12&.fabric.permit.v1.ReleasePermitRequest\x1a'.fabric.permit.v1.ReleasePermitResponseB5Z3go.datum.net/galactic/api/fabric/permit/v1;permitv1b\x06proto3" + +var ( + file_fabric_permit_v1_permit_proto_rawDescOnce sync.Once + file_fabric_permit_v1_permit_proto_rawDescData []byte +) + +func file_fabric_permit_v1_permit_proto_rawDescGZIP() []byte { + file_fabric_permit_v1_permit_proto_rawDescOnce.Do(func() { + file_fabric_permit_v1_permit_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_fabric_permit_v1_permit_proto_rawDesc), len(file_fabric_permit_v1_permit_proto_rawDesc))) + }) + return file_fabric_permit_v1_permit_proto_rawDescData +} + +var file_fabric_permit_v1_permit_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_fabric_permit_v1_permit_proto_goTypes = []any{ + (*RequestPermitRequest)(nil), // 0: fabric.permit.v1.RequestPermitRequest + (*RequestPermitResponse)(nil), // 1: fabric.permit.v1.RequestPermitResponse + (*ReleasePermitRequest)(nil), // 2: fabric.permit.v1.ReleasePermitRequest + (*ReleasePermitResponse)(nil), // 3: fabric.permit.v1.ReleasePermitResponse + (*v1.Query)(nil), // 4: fabric.v1.Query + (*timestamppb.Timestamp)(nil), // 5: google.protobuf.Timestamp + (*v1.ProbePermit)(nil), // 6: fabric.v1.ProbePermit +} +var file_fabric_permit_v1_permit_proto_depIdxs = []int32{ + 4, // 0: fabric.permit.v1.RequestPermitRequest.query:type_name -> fabric.v1.Query + 5, // 1: fabric.permit.v1.RequestPermitRequest.expires_at:type_name -> google.protobuf.Timestamp + 6, // 2: fabric.permit.v1.RequestPermitResponse.permit:type_name -> fabric.v1.ProbePermit + 0, // 3: fabric.permit.v1.PermitService.RequestPermit:input_type -> fabric.permit.v1.RequestPermitRequest + 2, // 4: fabric.permit.v1.PermitService.ReleasePermit:input_type -> fabric.permit.v1.ReleasePermitRequest + 1, // 5: fabric.permit.v1.PermitService.RequestPermit:output_type -> fabric.permit.v1.RequestPermitResponse + 3, // 6: fabric.permit.v1.PermitService.ReleasePermit:output_type -> fabric.permit.v1.ReleasePermitResponse + 5, // [5:7] is the sub-list for method output_type + 3, // [3:5] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_fabric_permit_v1_permit_proto_init() } +func file_fabric_permit_v1_permit_proto_init() { + if File_fabric_permit_v1_permit_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_fabric_permit_v1_permit_proto_rawDesc), len(file_fabric_permit_v1_permit_proto_rawDesc)), + NumEnums: 0, + NumMessages: 4, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_fabric_permit_v1_permit_proto_goTypes, + DependencyIndexes: file_fabric_permit_v1_permit_proto_depIdxs, + MessageInfos: file_fabric_permit_v1_permit_proto_msgTypes, + }.Build() + File_fabric_permit_v1_permit_proto = out.File + file_fabric_permit_v1_permit_proto_goTypes = nil + file_fabric_permit_v1_permit_proto_depIdxs = nil +} diff --git a/api/fabric/permit/v1/permit.proto b/api/fabric/permit/v1/permit.proto new file mode 100644 index 000000000..cab8e40ff --- /dev/null +++ b/api/fabric/permit/v1/permit.proto @@ -0,0 +1,57 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The node-to-gateway probe permit contract. It is internal to galactic: +// only a cell's node identities may call it. A node asks the cell's gateway +// for a permit before it runs a probe an operator sent it directly, so every +// probe in the cell draws from the same aggregate packet budgets. + +syntax = "proto3"; + +package fabric.permit.v1; + +import "fabric/v1/fabric.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "go.datum.net/galactic/api/fabric/permit/v1;permitv1"; + +// PermitService runs on each cell's fabric-api gateway. A follower forwards +// a call once to the leader, which alone issues permits. +service PermitService { + // RequestPermit reserves a cell execution slot and the probe's worst-case + // packets, and returns a permit for one attempt on the calling node. + rpc RequestPermit(RequestPermitRequest) returns (RequestPermitResponse); + // ReleasePermit reports that the node finished a permit's probe, freeing + // its execution slot before the permit expires. + rpc ReleasePermit(ReleasePermitRequest) returns (ReleasePermitResponse); +} + +message RequestPermitRequest { + // node is the calling node; it must be the node the caller's identity + // belongs to. + string node = 1; + // operator is the operator identity name the probe runs for; its packet + // budget is charged. + string operator = 2; + // request_id is the operator's request ID. + string request_id = 3; + // query is the probe, in canonical form. + fabric.v1.Query query = 4; + // expires_at is the request's absolute expiration; the permit's deadline + // is never later. + google.protobuf.Timestamp expires_at = 5; +} + +message RequestPermitResponse { + fabric.v1.ProbePermit permit = 1; +} + +message ReleasePermitRequest { + // node is the calling node. + string node = 1; + // id is the finished permit's ID. + string id = 2; +} + +message ReleasePermitResponse {} diff --git a/api/fabric/permit/v1/permit_grpc.pb.go b/api/fabric/permit/v1/permit_grpc.pb.go new file mode 100644 index 000000000..f9a350592 --- /dev/null +++ b/api/fabric/permit/v1/permit_grpc.pb.go @@ -0,0 +1,182 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The node-to-gateway probe permit contract. It is internal to galactic: +// only a cell's node identities may call it. A node asks the cell's gateway +// for a permit before it runs a probe an operator sent it directly, so every +// probe in the cell draws from the same aggregate packet budgets. + +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.2 +// - protoc (unknown) +// source: fabric/permit/v1/permit.proto + +package permitv1 + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + PermitService_RequestPermit_FullMethodName = "/fabric.permit.v1.PermitService/RequestPermit" + PermitService_ReleasePermit_FullMethodName = "/fabric.permit.v1.PermitService/ReleasePermit" +) + +// PermitServiceClient is the client API for PermitService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// PermitService runs on each cell's fabric-api gateway. A follower forwards +// a call once to the leader, which alone issues permits. +type PermitServiceClient interface { + // RequestPermit reserves a cell execution slot and the probe's worst-case + // packets, and returns a permit for one attempt on the calling node. + RequestPermit(ctx context.Context, in *RequestPermitRequest, opts ...grpc.CallOption) (*RequestPermitResponse, error) + // ReleasePermit reports that the node finished a permit's probe, freeing + // its execution slot before the permit expires. + ReleasePermit(ctx context.Context, in *ReleasePermitRequest, opts ...grpc.CallOption) (*ReleasePermitResponse, error) +} + +type permitServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewPermitServiceClient(cc grpc.ClientConnInterface) PermitServiceClient { + return &permitServiceClient{cc} +} + +func (c *permitServiceClient) RequestPermit(ctx context.Context, in *RequestPermitRequest, opts ...grpc.CallOption) (*RequestPermitResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(RequestPermitResponse) + err := c.cc.Invoke(ctx, PermitService_RequestPermit_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *permitServiceClient) ReleasePermit(ctx context.Context, in *ReleasePermitRequest, opts ...grpc.CallOption) (*ReleasePermitResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ReleasePermitResponse) + err := c.cc.Invoke(ctx, PermitService_ReleasePermit_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// PermitServiceServer is the server API for PermitService service. +// All implementations must embed UnimplementedPermitServiceServer +// for forward compatibility. +// +// PermitService runs on each cell's fabric-api gateway. A follower forwards +// a call once to the leader, which alone issues permits. +type PermitServiceServer interface { + // RequestPermit reserves a cell execution slot and the probe's worst-case + // packets, and returns a permit for one attempt on the calling node. + RequestPermit(context.Context, *RequestPermitRequest) (*RequestPermitResponse, error) + // ReleasePermit reports that the node finished a permit's probe, freeing + // its execution slot before the permit expires. + ReleasePermit(context.Context, *ReleasePermitRequest) (*ReleasePermitResponse, error) + mustEmbedUnimplementedPermitServiceServer() +} + +// UnimplementedPermitServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedPermitServiceServer struct{} + +func (UnimplementedPermitServiceServer) RequestPermit(context.Context, *RequestPermitRequest) (*RequestPermitResponse, error) { + return nil, status.Error(codes.Unimplemented, "method RequestPermit not implemented") +} +func (UnimplementedPermitServiceServer) ReleasePermit(context.Context, *ReleasePermitRequest) (*ReleasePermitResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ReleasePermit not implemented") +} +func (UnimplementedPermitServiceServer) mustEmbedUnimplementedPermitServiceServer() {} +func (UnimplementedPermitServiceServer) testEmbeddedByValue() {} + +// UnsafePermitServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to PermitServiceServer will +// result in compilation errors. +type UnsafePermitServiceServer interface { + mustEmbedUnimplementedPermitServiceServer() +} + +func RegisterPermitServiceServer(s grpc.ServiceRegistrar, srv PermitServiceServer) { + // If the following call panics, it indicates UnimplementedPermitServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&PermitService_ServiceDesc, srv) +} + +func _PermitService_RequestPermit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestPermitRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(PermitServiceServer).RequestPermit(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: PermitService_RequestPermit_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(PermitServiceServer).RequestPermit(ctx, req.(*RequestPermitRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _PermitService_ReleasePermit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ReleasePermitRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(PermitServiceServer).ReleasePermit(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: PermitService_ReleasePermit_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(PermitServiceServer).ReleasePermit(ctx, req.(*ReleasePermitRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// PermitService_ServiceDesc is the grpc.ServiceDesc for PermitService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var PermitService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "fabric.permit.v1.PermitService", + HandlerType: (*PermitServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "RequestPermit", + Handler: _PermitService_RequestPermit_Handler, + }, + { + MethodName: "ReleasePermit", + Handler: _PermitService_ReleasePermit_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "fabric/permit/v1/permit.proto", +} diff --git a/api/fabric/service/v1/fixtures_test.go b/api/fabric/service/v1/fixtures_test.go index 64ef73802..6b5b6df38 100644 --- a/api/fabric/service/v1/fixtures_test.go +++ b/api/fabric/service/v1/fixtures_test.go @@ -58,7 +58,8 @@ func TestCapabilitiesFixture(t *testing.T) { var caps servicev1.GetCapabilitiesResponse decode(t, fixture(t, "capabilities.json"), &caps) if len(caps.GetOperations()) != 4 || caps.GetLimits().GetMaxSelectedRouters() != 32 || - caps.GetLimits().GetMaxRequestLifetime().AsDuration().Seconds() != 120 { + caps.GetLimits().GetMaxRequestLifetime().AsDuration().Seconds() != 120 || + caps.GetLimits().GetAdmission().GetPacketDestinationPrefix().GetPerSecond() != 40 { t.Errorf("capabilities = %v", &caps) } } diff --git a/api/fabric/service/v1/service.pb.go b/api/fabric/service/v1/service.pb.go index bf79aa019..e6e106554 100644 --- a/api/fabric/service/v1/service.pb.go +++ b/api/fabric/service/v1/service.pb.go @@ -277,7 +277,10 @@ type Limits struct { // larger inventory fails with InventoryTooLarge. MaxInventoryRouters uint32 `protobuf:"varint,4,opt,name=max_inventory_routers,json=maxInventoryRouters,proto3" json:"max_inventory_routers,omitempty"` // max_budgets holds the largest value each request budget may take. - MaxBudgets *v1.Budgets `protobuf:"bytes,5,opt,name=max_budgets,json=maxBudgets,proto3" json:"max_budgets,omitempty"` + MaxBudgets *v1.Budgets `protobuf:"bytes,5,opt,name=max_budgets,json=maxBudgets,proto3" json:"max_budgets,omitempty"` + // admission holds the cell's aggregate admission and probe budgets. It is + // set when the aggregate-probe-budgets feature is served. + Admission *AdmissionLimits `protobuf:"bytes,6,opt,name=admission,proto3" json:"admission,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -347,6 +350,236 @@ func (x *Limits) GetMaxBudgets() *v1.Budgets { return nil } +func (x *Limits) GetAdmission() *AdmissionLimits { + if x != nil { + return x.Admission + } + return nil +} + +// TokenRate is a token bucket's sustained rate, in tokens per second, and +// its burst. +type TokenRate struct { + state protoimpl.MessageState `protogen:"open.v1"` + PerSecond float64 `protobuf:"fixed64,1,opt,name=per_second,json=perSecond,proto3" json:"per_second,omitempty"` + Burst float64 `protobuf:"fixed64,2,opt,name=burst,proto3" json:"burst,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *TokenRate) Reset() { + *x = TokenRate{} + mi := &file_fabric_service_v1_service_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *TokenRate) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TokenRate) ProtoMessage() {} + +func (x *TokenRate) ProtoReflect() protoreflect.Message { + mi := &file_fabric_service_v1_service_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TokenRate.ProtoReflect.Descriptor instead. +func (*TokenRate) Descriptor() ([]byte, []int) { + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{4} +} + +func (x *TokenRate) GetPerSecond() float64 { + if x != nil { + return x.PerSecond + } + return 0 +} + +func (x *TokenRate) GetBurst() float64 { + if x != nil { + return x.Burst + } + return 0 +} + +// AdmissionLimits are a cell's aggregate limits. Request buckets charge one +// token per RunDiagnostic; packet buckets charge each probe's worst case, +// ping_packets or traceroute_packets, when its router job is dispatched. +// Packet budgets are shared with the cell's operator and FabricQuery probes. +type AdmissionLimits struct { + state protoimpl.MessageState `protogen:"open.v1"` + RequestCell *TokenRate `protobuf:"bytes,1,opt,name=request_cell,json=requestCell,proto3" json:"request_cell,omitempty"` + RequestProject *TokenRate `protobuf:"bytes,2,opt,name=request_project,json=requestProject,proto3" json:"request_project,omitempty"` + PacketCell *TokenRate `protobuf:"bytes,3,opt,name=packet_cell,json=packetCell,proto3" json:"packet_cell,omitempty"` + PacketProject *TokenRate `protobuf:"bytes,4,opt,name=packet_project,json=packetProject,proto3" json:"packet_project,omitempty"` + // packet_destination_host charges the destination's /32 or /128, and + // packet_destination_prefix its /24 or /64, whatever the project. + PacketDestinationHost *TokenRate `protobuf:"bytes,5,opt,name=packet_destination_host,json=packetDestinationHost,proto3" json:"packet_destination_host,omitempty"` + PacketDestinationPrefix *TokenRate `protobuf:"bytes,6,opt,name=packet_destination_prefix,json=packetDestinationPrefix,proto3" json:"packet_destination_prefix,omitempty"` + // active_jobs and project_active_jobs bound router jobs executing at once + // in the cell and per project. + ActiveJobs uint32 `protobuf:"varint,7,opt,name=active_jobs,json=activeJobs,proto3" json:"active_jobs,omitempty"` + ProjectActiveJobs uint32 `protobuf:"varint,8,opt,name=project_active_jobs,json=projectActiveJobs,proto3" json:"project_active_jobs,omitempty"` + // queued_jobs and project_queued_jobs bound router jobs waiting for a + // slot. A request's selected routers are admitted together or refused + // with QueueFull. + QueuedJobs uint32 `protobuf:"varint,9,opt,name=queued_jobs,json=queuedJobs,proto3" json:"queued_jobs,omitempty"` + ProjectQueuedJobs uint32 `protobuf:"varint,10,opt,name=project_queued_jobs,json=projectQueuedJobs,proto3" json:"project_queued_jobs,omitempty"` + // streams and project_streams bound live RunDiagnostic streams. + Streams uint32 `protobuf:"varint,11,opt,name=streams,proto3" json:"streams,omitempty"` + ProjectStreams uint32 `protobuf:"varint,12,opt,name=project_streams,json=projectStreams,proto3" json:"project_streams,omitempty"` + // queue_wait bounds a router job's wait for a slot (QueueTimeout). + QueueWait *durationpb.Duration `protobuf:"bytes,13,opt,name=queue_wait,json=queueWait,proto3" json:"queue_wait,omitempty"` + PingPackets uint32 `protobuf:"varint,14,opt,name=ping_packets,json=pingPackets,proto3" json:"ping_packets,omitempty"` + TraceroutePackets uint32 `protobuf:"varint,15,opt,name=traceroute_packets,json=traceroutePackets,proto3" json:"traceroute_packets,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AdmissionLimits) Reset() { + *x = AdmissionLimits{} + mi := &file_fabric_service_v1_service_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AdmissionLimits) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AdmissionLimits) ProtoMessage() {} + +func (x *AdmissionLimits) ProtoReflect() protoreflect.Message { + mi := &file_fabric_service_v1_service_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AdmissionLimits.ProtoReflect.Descriptor instead. +func (*AdmissionLimits) Descriptor() ([]byte, []int) { + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{5} +} + +func (x *AdmissionLimits) GetRequestCell() *TokenRate { + if x != nil { + return x.RequestCell + } + return nil +} + +func (x *AdmissionLimits) GetRequestProject() *TokenRate { + if x != nil { + return x.RequestProject + } + return nil +} + +func (x *AdmissionLimits) GetPacketCell() *TokenRate { + if x != nil { + return x.PacketCell + } + return nil +} + +func (x *AdmissionLimits) GetPacketProject() *TokenRate { + if x != nil { + return x.PacketProject + } + return nil +} + +func (x *AdmissionLimits) GetPacketDestinationHost() *TokenRate { + if x != nil { + return x.PacketDestinationHost + } + return nil +} + +func (x *AdmissionLimits) GetPacketDestinationPrefix() *TokenRate { + if x != nil { + return x.PacketDestinationPrefix + } + return nil +} + +func (x *AdmissionLimits) GetActiveJobs() uint32 { + if x != nil { + return x.ActiveJobs + } + return 0 +} + +func (x *AdmissionLimits) GetProjectActiveJobs() uint32 { + if x != nil { + return x.ProjectActiveJobs + } + return 0 +} + +func (x *AdmissionLimits) GetQueuedJobs() uint32 { + if x != nil { + return x.QueuedJobs + } + return 0 +} + +func (x *AdmissionLimits) GetProjectQueuedJobs() uint32 { + if x != nil { + return x.ProjectQueuedJobs + } + return 0 +} + +func (x *AdmissionLimits) GetStreams() uint32 { + if x != nil { + return x.Streams + } + return 0 +} + +func (x *AdmissionLimits) GetProjectStreams() uint32 { + if x != nil { + return x.ProjectStreams + } + return 0 +} + +func (x *AdmissionLimits) GetQueueWait() *durationpb.Duration { + if x != nil { + return x.QueueWait + } + return nil +} + +func (x *AdmissionLimits) GetPingPackets() uint32 { + if x != nil { + return x.PingPackets + } + return 0 +} + +func (x *AdmissionLimits) GetTraceroutePackets() uint32 { + if x != nil { + return x.TraceroutePackets + } + return 0 +} + type RunDiagnosticRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // api_major must be 1. @@ -376,7 +609,7 @@ type RunDiagnosticRequest struct { func (x *RunDiagnosticRequest) Reset() { *x = RunDiagnosticRequest{} - mi := &file_fabric_service_v1_service_proto_msgTypes[4] + mi := &file_fabric_service_v1_service_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -388,7 +621,7 @@ func (x *RunDiagnosticRequest) String() string { func (*RunDiagnosticRequest) ProtoMessage() {} func (x *RunDiagnosticRequest) ProtoReflect() protoreflect.Message { - mi := &file_fabric_service_v1_service_proto_msgTypes[4] + mi := &file_fabric_service_v1_service_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -401,7 +634,7 @@ func (x *RunDiagnosticRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RunDiagnosticRequest.ProtoReflect.Descriptor instead. func (*RunDiagnosticRequest) Descriptor() ([]byte, []int) { - return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{4} + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{6} } func (x *RunDiagnosticRequest) GetApiMajor() uint32 { @@ -488,7 +721,7 @@ type DiagnosticEvent struct { func (x *DiagnosticEvent) Reset() { *x = DiagnosticEvent{} - mi := &file_fabric_service_v1_service_proto_msgTypes[5] + mi := &file_fabric_service_v1_service_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -500,7 +733,7 @@ func (x *DiagnosticEvent) String() string { func (*DiagnosticEvent) ProtoMessage() {} func (x *DiagnosticEvent) ProtoReflect() protoreflect.Message { - mi := &file_fabric_service_v1_service_proto_msgTypes[5] + mi := &file_fabric_service_v1_service_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -513,7 +746,7 @@ func (x *DiagnosticEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use DiagnosticEvent.ProtoReflect.Descriptor instead. func (*DiagnosticEvent) Descriptor() ([]byte, []int) { - return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{5} + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{7} } func (x *DiagnosticEvent) GetRequestId() string { @@ -605,7 +838,7 @@ type Snapshot struct { func (x *Snapshot) Reset() { *x = Snapshot{} - mi := &file_fabric_service_v1_service_proto_msgTypes[6] + mi := &file_fabric_service_v1_service_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -617,7 +850,7 @@ func (x *Snapshot) String() string { func (*Snapshot) ProtoMessage() {} func (x *Snapshot) ProtoReflect() protoreflect.Message { - mi := &file_fabric_service_v1_service_proto_msgTypes[6] + mi := &file_fabric_service_v1_service_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -630,7 +863,7 @@ func (x *Snapshot) ProtoReflect() protoreflect.Message { // Deprecated: Use Snapshot.ProtoReflect.Descriptor instead. func (*Snapshot) Descriptor() ([]byte, []int) { - return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{6} + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{8} } func (x *Snapshot) GetSnapshotId() string { @@ -685,7 +918,7 @@ type SnapshotRouter struct { func (x *SnapshotRouter) Reset() { *x = SnapshotRouter{} - mi := &file_fabric_service_v1_service_proto_msgTypes[7] + mi := &file_fabric_service_v1_service_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -697,7 +930,7 @@ func (x *SnapshotRouter) String() string { func (*SnapshotRouter) ProtoMessage() {} func (x *SnapshotRouter) ProtoReflect() protoreflect.Message { - mi := &file_fabric_service_v1_service_proto_msgTypes[7] + mi := &file_fabric_service_v1_service_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -710,7 +943,7 @@ func (x *SnapshotRouter) ProtoReflect() protoreflect.Message { // Deprecated: Use SnapshotRouter.ProtoReflect.Descriptor instead. func (*SnapshotRouter) Descriptor() ([]byte, []int) { - return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{7} + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{9} } func (x *SnapshotRouter) GetNode() string { @@ -760,7 +993,7 @@ type RouterOutcome struct { func (x *RouterOutcome) Reset() { *x = RouterOutcome{} - mi := &file_fabric_service_v1_service_proto_msgTypes[8] + mi := &file_fabric_service_v1_service_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -772,7 +1005,7 @@ func (x *RouterOutcome) String() string { func (*RouterOutcome) ProtoMessage() {} func (x *RouterOutcome) ProtoReflect() protoreflect.Message { - mi := &file_fabric_service_v1_service_proto_msgTypes[8] + mi := &file_fabric_service_v1_service_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -785,7 +1018,7 @@ func (x *RouterOutcome) ProtoReflect() protoreflect.Message { // Deprecated: Use RouterOutcome.ProtoReflect.Descriptor instead. func (*RouterOutcome) Descriptor() ([]byte, []int) { - return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{8} + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{10} } func (x *RouterOutcome) GetNode() string { @@ -857,14 +1090,20 @@ type Failure struct { // reason is a fabric-api error code, e.g. NodeUnreachable or Timeout. Reason string `protobuf:"bytes,1,opt,name=reason,proto3" json:"reason,omitempty"` // message is a sanitized description of at most 256 bytes. - Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` + Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` + // scope is the limit that refused a Throttled, QueueFull or + // LimiterUnavailable router: cell, project, destination or queue. + Scope string `protobuf:"bytes,3,opt,name=scope,proto3" json:"scope,omitempty"` + // retry_delay is the advised delay before a new attempt, for a refusal + // that carries one. It is guidance, not a reservation. + RetryDelay *durationpb.Duration `protobuf:"bytes,4,opt,name=retry_delay,json=retryDelay,proto3" json:"retry_delay,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *Failure) Reset() { *x = Failure{} - mi := &file_fabric_service_v1_service_proto_msgTypes[9] + mi := &file_fabric_service_v1_service_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -876,7 +1115,7 @@ func (x *Failure) String() string { func (*Failure) ProtoMessage() {} func (x *Failure) ProtoReflect() protoreflect.Message { - mi := &file_fabric_service_v1_service_proto_msgTypes[9] + mi := &file_fabric_service_v1_service_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -889,7 +1128,7 @@ func (x *Failure) ProtoReflect() protoreflect.Message { // Deprecated: Use Failure.ProtoReflect.Descriptor instead. func (*Failure) Descriptor() ([]byte, []int) { - return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{9} + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{11} } func (x *Failure) GetReason() string { @@ -906,6 +1145,20 @@ func (x *Failure) GetMessage() string { return "" } +func (x *Failure) GetScope() string { + if x != nil { + return x.Scope + } + return "" +} + +func (x *Failure) GetRetryDelay() *durationpb.Duration { + if x != nil { + return x.RetryDelay + } + return nil +} + // Complete is a stream's terminal coverage. expected equals successful + // failed + omitted, and successful + failed is the number of selected // routers in the snapshot. @@ -929,7 +1182,7 @@ type Complete struct { func (x *Complete) Reset() { *x = Complete{} - mi := &file_fabric_service_v1_service_proto_msgTypes[10] + mi := &file_fabric_service_v1_service_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -941,7 +1194,7 @@ func (x *Complete) String() string { func (*Complete) ProtoMessage() {} func (x *Complete) ProtoReflect() protoreflect.Message { - mi := &file_fabric_service_v1_service_proto_msgTypes[10] + mi := &file_fabric_service_v1_service_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -954,7 +1207,7 @@ func (x *Complete) ProtoReflect() protoreflect.Message { // Deprecated: Use Complete.ProtoReflect.Descriptor instead. func (*Complete) Descriptor() ([]byte, []int) { - return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{10} + return file_fabric_service_v1_service_proto_rawDescGZIP(), []int{12} } func (x *Complete) GetSnapshotId() string { @@ -1035,14 +1288,40 @@ const file_fabric_service_v1_service_proto_rawDesc = "" + "\fgenerated_at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\vgeneratedAt\"z\n" + "\tOperation\x12(\n" + "\x04type\x18\x01 \x01(\x0e2\x14.fabric.v1.QueryTypeR\x04type\x12C\n" + - "\x10address_families\x18\x02 \x03(\x0e2\x18.fabric.v1.AddressFamilyR\x0faddressFamilies\"\xb9\x02\n" + + "\x10address_families\x18\x02 \x03(\x0e2\x18.fabric.v1.AddressFamilyR\x0faddressFamilies\"\xfb\x02\n" + "\x06Limits\x12K\n" + "\x14max_request_lifetime\x18\x01 \x01(\v2\x19.google.protobuf.DurationR\x12maxRequestLifetime\x12G\n" + "\x12max_node_execution\x18\x02 \x01(\v2\x19.google.protobuf.DurationR\x10maxNodeExecution\x120\n" + "\x14max_selected_routers\x18\x03 \x01(\rR\x12maxSelectedRouters\x122\n" + "\x15max_inventory_routers\x18\x04 \x01(\rR\x13maxInventoryRouters\x123\n" + "\vmax_budgets\x18\x05 \x01(\v2\x12.fabric.v1.BudgetsR\n" + - "maxBudgets\"\xd9\x02\n" + + "maxBudgets\x12@\n" + + "\tadmission\x18\x06 \x01(\v2\".fabric.service.v1.AdmissionLimitsR\tadmission\"@\n" + + "\tTokenRate\x12\x1d\n" + + "\n" + + "per_second\x18\x01 \x01(\x01R\tperSecond\x12\x14\n" + + "\x05burst\x18\x02 \x01(\x01R\x05burst\"\xbe\x06\n" + + "\x0fAdmissionLimits\x12?\n" + + "\frequest_cell\x18\x01 \x01(\v2\x1c.fabric.service.v1.TokenRateR\vrequestCell\x12E\n" + + "\x0frequest_project\x18\x02 \x01(\v2\x1c.fabric.service.v1.TokenRateR\x0erequestProject\x12=\n" + + "\vpacket_cell\x18\x03 \x01(\v2\x1c.fabric.service.v1.TokenRateR\n" + + "packetCell\x12C\n" + + "\x0epacket_project\x18\x04 \x01(\v2\x1c.fabric.service.v1.TokenRateR\rpacketProject\x12T\n" + + "\x17packet_destination_host\x18\x05 \x01(\v2\x1c.fabric.service.v1.TokenRateR\x15packetDestinationHost\x12X\n" + + "\x19packet_destination_prefix\x18\x06 \x01(\v2\x1c.fabric.service.v1.TokenRateR\x17packetDestinationPrefix\x12\x1f\n" + + "\vactive_jobs\x18\a \x01(\rR\n" + + "activeJobs\x12.\n" + + "\x13project_active_jobs\x18\b \x01(\rR\x11projectActiveJobs\x12\x1f\n" + + "\vqueued_jobs\x18\t \x01(\rR\n" + + "queuedJobs\x12.\n" + + "\x13project_queued_jobs\x18\n" + + " \x01(\rR\x11projectQueuedJobs\x12\x18\n" + + "\astreams\x18\v \x01(\rR\astreams\x12'\n" + + "\x0fproject_streams\x18\f \x01(\rR\x0eprojectStreams\x128\n" + + "\n" + + "queue_wait\x18\r \x01(\v2\x19.google.protobuf.DurationR\tqueueWait\x12!\n" + + "\fping_packets\x18\x0e \x01(\rR\vpingPackets\x12-\n" + + "\x12traceroute_packets\x18\x0f \x01(\rR\x11traceroutePackets\"\xd9\x02\n" + "\x14RunDiagnosticRequest\x12\x1b\n" + "\tapi_major\x18\x01 \x01(\rR\bapiMajor\x12\x12\n" + "\x04cell\x18\x02 \x01(\tR\x04cell\x12\x1d\n" + @@ -1083,10 +1362,13 @@ const file_fabric_service_v1_service_proto_rawDesc = "" + "\fcompleted_at\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\vcompletedAt\x12:\n" + "\vobservation\x18\x04 \x01(\v2\x16.fabric.v1.ObservationH\x00R\vobservation\x126\n" + "\afailure\x18\x05 \x01(\v2\x1a.fabric.service.v1.FailureH\x00R\afailureB\b\n" + - "\x06result\";\n" + + "\x06result\"\x8d\x01\n" + "\aFailure\x12\x16\n" + "\x06reason\x18\x01 \x01(\tR\x06reason\x12\x18\n" + - "\amessage\x18\x02 \x01(\tR\amessage\"\x9b\x02\n" + + "\amessage\x18\x02 \x01(\tR\amessage\x12\x14\n" + + "\x05scope\x18\x03 \x01(\tR\x05scope\x12:\n" + + "\vretry_delay\x18\x04 \x01(\v2\x19.google.protobuf.DurationR\n" + + "retryDelay\"\x9b\x02\n" + "\bComplete\x12\x1f\n" + "\vsnapshot_id\x18\x01 \x01(\tR\n" + "snapshotId\x12;\n" + @@ -1116,57 +1398,68 @@ func file_fabric_service_v1_service_proto_rawDescGZIP() []byte { return file_fabric_service_v1_service_proto_rawDescData } -var file_fabric_service_v1_service_proto_msgTypes = make([]protoimpl.MessageInfo, 11) +var file_fabric_service_v1_service_proto_msgTypes = make([]protoimpl.MessageInfo, 13) var file_fabric_service_v1_service_proto_goTypes = []any{ (*GetCapabilitiesRequest)(nil), // 0: fabric.service.v1.GetCapabilitiesRequest (*GetCapabilitiesResponse)(nil), // 1: fabric.service.v1.GetCapabilitiesResponse (*Operation)(nil), // 2: fabric.service.v1.Operation (*Limits)(nil), // 3: fabric.service.v1.Limits - (*RunDiagnosticRequest)(nil), // 4: fabric.service.v1.RunDiagnosticRequest - (*DiagnosticEvent)(nil), // 5: fabric.service.v1.DiagnosticEvent - (*Snapshot)(nil), // 6: fabric.service.v1.Snapshot - (*SnapshotRouter)(nil), // 7: fabric.service.v1.SnapshotRouter - (*RouterOutcome)(nil), // 8: fabric.service.v1.RouterOutcome - (*Failure)(nil), // 9: fabric.service.v1.Failure - (*Complete)(nil), // 10: fabric.service.v1.Complete - (*timestamppb.Timestamp)(nil), // 11: google.protobuf.Timestamp - (v1.QueryType)(0), // 12: fabric.v1.QueryType - (v1.AddressFamily)(0), // 13: fabric.v1.AddressFamily - (*durationpb.Duration)(nil), // 14: google.protobuf.Duration - (*v1.Budgets)(nil), // 15: fabric.v1.Budgets - (*v1.Query)(nil), // 16: fabric.v1.Query - (*v1.Observation)(nil), // 17: fabric.v1.Observation + (*TokenRate)(nil), // 4: fabric.service.v1.TokenRate + (*AdmissionLimits)(nil), // 5: fabric.service.v1.AdmissionLimits + (*RunDiagnosticRequest)(nil), // 6: fabric.service.v1.RunDiagnosticRequest + (*DiagnosticEvent)(nil), // 7: fabric.service.v1.DiagnosticEvent + (*Snapshot)(nil), // 8: fabric.service.v1.Snapshot + (*SnapshotRouter)(nil), // 9: fabric.service.v1.SnapshotRouter + (*RouterOutcome)(nil), // 10: fabric.service.v1.RouterOutcome + (*Failure)(nil), // 11: fabric.service.v1.Failure + (*Complete)(nil), // 12: fabric.service.v1.Complete + (*timestamppb.Timestamp)(nil), // 13: google.protobuf.Timestamp + (v1.QueryType)(0), // 14: fabric.v1.QueryType + (v1.AddressFamily)(0), // 15: fabric.v1.AddressFamily + (*durationpb.Duration)(nil), // 16: google.protobuf.Duration + (*v1.Budgets)(nil), // 17: fabric.v1.Budgets + (*v1.Query)(nil), // 18: fabric.v1.Query + (*v1.Observation)(nil), // 19: fabric.v1.Observation } var file_fabric_service_v1_service_proto_depIdxs = []int32{ 2, // 0: fabric.service.v1.GetCapabilitiesResponse.operations:type_name -> fabric.service.v1.Operation 3, // 1: fabric.service.v1.GetCapabilitiesResponse.limits:type_name -> fabric.service.v1.Limits - 11, // 2: fabric.service.v1.GetCapabilitiesResponse.generated_at:type_name -> google.protobuf.Timestamp - 12, // 3: fabric.service.v1.Operation.type:type_name -> fabric.v1.QueryType - 13, // 4: fabric.service.v1.Operation.address_families:type_name -> fabric.v1.AddressFamily - 14, // 5: fabric.service.v1.Limits.max_request_lifetime:type_name -> google.protobuf.Duration - 14, // 6: fabric.service.v1.Limits.max_node_execution:type_name -> google.protobuf.Duration - 15, // 7: fabric.service.v1.Limits.max_budgets:type_name -> fabric.v1.Budgets - 11, // 8: fabric.service.v1.RunDiagnosticRequest.expires_at:type_name -> google.protobuf.Timestamp - 16, // 9: fabric.service.v1.RunDiagnosticRequest.query:type_name -> fabric.v1.Query - 15, // 10: fabric.service.v1.RunDiagnosticRequest.budgets:type_name -> fabric.v1.Budgets - 6, // 11: fabric.service.v1.DiagnosticEvent.snapshot:type_name -> fabric.service.v1.Snapshot - 8, // 12: fabric.service.v1.DiagnosticEvent.outcome:type_name -> fabric.service.v1.RouterOutcome - 10, // 13: fabric.service.v1.DiagnosticEvent.complete:type_name -> fabric.service.v1.Complete - 11, // 14: fabric.service.v1.Snapshot.captured_at:type_name -> google.protobuf.Timestamp - 7, // 15: fabric.service.v1.Snapshot.routers:type_name -> fabric.service.v1.SnapshotRouter - 11, // 16: fabric.service.v1.RouterOutcome.completed_at:type_name -> google.protobuf.Timestamp - 17, // 17: fabric.service.v1.RouterOutcome.observation:type_name -> fabric.v1.Observation - 9, // 18: fabric.service.v1.RouterOutcome.failure:type_name -> fabric.service.v1.Failure - 11, // 19: fabric.service.v1.Complete.finished_at:type_name -> google.protobuf.Timestamp - 0, // 20: fabric.service.v1.LookingGlassService.GetCapabilities:input_type -> fabric.service.v1.GetCapabilitiesRequest - 4, // 21: fabric.service.v1.LookingGlassService.RunDiagnostic:input_type -> fabric.service.v1.RunDiagnosticRequest - 1, // 22: fabric.service.v1.LookingGlassService.GetCapabilities:output_type -> fabric.service.v1.GetCapabilitiesResponse - 5, // 23: fabric.service.v1.LookingGlassService.RunDiagnostic:output_type -> fabric.service.v1.DiagnosticEvent - 22, // [22:24] is the sub-list for method output_type - 20, // [20:22] is the sub-list for method input_type - 20, // [20:20] is the sub-list for extension type_name - 20, // [20:20] is the sub-list for extension extendee - 0, // [0:20] is the sub-list for field type_name + 13, // 2: fabric.service.v1.GetCapabilitiesResponse.generated_at:type_name -> google.protobuf.Timestamp + 14, // 3: fabric.service.v1.Operation.type:type_name -> fabric.v1.QueryType + 15, // 4: fabric.service.v1.Operation.address_families:type_name -> fabric.v1.AddressFamily + 16, // 5: fabric.service.v1.Limits.max_request_lifetime:type_name -> google.protobuf.Duration + 16, // 6: fabric.service.v1.Limits.max_node_execution:type_name -> google.protobuf.Duration + 17, // 7: fabric.service.v1.Limits.max_budgets:type_name -> fabric.v1.Budgets + 5, // 8: fabric.service.v1.Limits.admission:type_name -> fabric.service.v1.AdmissionLimits + 4, // 9: fabric.service.v1.AdmissionLimits.request_cell:type_name -> fabric.service.v1.TokenRate + 4, // 10: fabric.service.v1.AdmissionLimits.request_project:type_name -> fabric.service.v1.TokenRate + 4, // 11: fabric.service.v1.AdmissionLimits.packet_cell:type_name -> fabric.service.v1.TokenRate + 4, // 12: fabric.service.v1.AdmissionLimits.packet_project:type_name -> fabric.service.v1.TokenRate + 4, // 13: fabric.service.v1.AdmissionLimits.packet_destination_host:type_name -> fabric.service.v1.TokenRate + 4, // 14: fabric.service.v1.AdmissionLimits.packet_destination_prefix:type_name -> fabric.service.v1.TokenRate + 16, // 15: fabric.service.v1.AdmissionLimits.queue_wait:type_name -> google.protobuf.Duration + 13, // 16: fabric.service.v1.RunDiagnosticRequest.expires_at:type_name -> google.protobuf.Timestamp + 18, // 17: fabric.service.v1.RunDiagnosticRequest.query:type_name -> fabric.v1.Query + 17, // 18: fabric.service.v1.RunDiagnosticRequest.budgets:type_name -> fabric.v1.Budgets + 8, // 19: fabric.service.v1.DiagnosticEvent.snapshot:type_name -> fabric.service.v1.Snapshot + 10, // 20: fabric.service.v1.DiagnosticEvent.outcome:type_name -> fabric.service.v1.RouterOutcome + 12, // 21: fabric.service.v1.DiagnosticEvent.complete:type_name -> fabric.service.v1.Complete + 13, // 22: fabric.service.v1.Snapshot.captured_at:type_name -> google.protobuf.Timestamp + 9, // 23: fabric.service.v1.Snapshot.routers:type_name -> fabric.service.v1.SnapshotRouter + 13, // 24: fabric.service.v1.RouterOutcome.completed_at:type_name -> google.protobuf.Timestamp + 19, // 25: fabric.service.v1.RouterOutcome.observation:type_name -> fabric.v1.Observation + 11, // 26: fabric.service.v1.RouterOutcome.failure:type_name -> fabric.service.v1.Failure + 16, // 27: fabric.service.v1.Failure.retry_delay:type_name -> google.protobuf.Duration + 13, // 28: fabric.service.v1.Complete.finished_at:type_name -> google.protobuf.Timestamp + 0, // 29: fabric.service.v1.LookingGlassService.GetCapabilities:input_type -> fabric.service.v1.GetCapabilitiesRequest + 6, // 30: fabric.service.v1.LookingGlassService.RunDiagnostic:input_type -> fabric.service.v1.RunDiagnosticRequest + 1, // 31: fabric.service.v1.LookingGlassService.GetCapabilities:output_type -> fabric.service.v1.GetCapabilitiesResponse + 7, // 32: fabric.service.v1.LookingGlassService.RunDiagnostic:output_type -> fabric.service.v1.DiagnosticEvent + 31, // [31:33] is the sub-list for method output_type + 29, // [29:31] is the sub-list for method input_type + 29, // [29:29] is the sub-list for extension type_name + 29, // [29:29] is the sub-list for extension extendee + 0, // [0:29] is the sub-list for field type_name } func init() { file_fabric_service_v1_service_proto_init() } @@ -1174,12 +1467,12 @@ func file_fabric_service_v1_service_proto_init() { if File_fabric_service_v1_service_proto != nil { return } - file_fabric_service_v1_service_proto_msgTypes[5].OneofWrappers = []any{ + file_fabric_service_v1_service_proto_msgTypes[7].OneofWrappers = []any{ (*DiagnosticEvent_Snapshot)(nil), (*DiagnosticEvent_Outcome)(nil), (*DiagnosticEvent_Complete)(nil), } - file_fabric_service_v1_service_proto_msgTypes[8].OneofWrappers = []any{ + file_fabric_service_v1_service_proto_msgTypes[10].OneofWrappers = []any{ (*RouterOutcome_Observation)(nil), (*RouterOutcome_Failure)(nil), } @@ -1189,7 +1482,7 @@ func file_fabric_service_v1_service_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_fabric_service_v1_service_proto_rawDesc), len(file_fabric_service_v1_service_proto_rawDesc)), NumEnums: 0, - NumMessages: 11, + NumMessages: 13, NumExtensions: 0, NumServices: 1, }, diff --git a/api/fabric/service/v1/service.proto b/api/fabric/service/v1/service.proto index bc850f448..f7b328fa5 100644 --- a/api/fabric/service/v1/service.proto +++ b/api/fabric/service/v1/service.proto @@ -82,6 +82,47 @@ message Limits { uint32 max_inventory_routers = 4; // max_budgets holds the largest value each request budget may take. fabric.v1.Budgets max_budgets = 5; + // admission holds the cell's aggregate admission and probe budgets. It is + // set when the aggregate-probe-budgets feature is served. + AdmissionLimits admission = 6; +} + +// TokenRate is a token bucket's sustained rate, in tokens per second, and +// its burst. +message TokenRate { + double per_second = 1; + double burst = 2; +} + +// AdmissionLimits are a cell's aggregate limits. Request buckets charge one +// token per RunDiagnostic; packet buckets charge each probe's worst case, +// ping_packets or traceroute_packets, when its router job is dispatched. +// Packet budgets are shared with the cell's operator and FabricQuery probes. +message AdmissionLimits { + TokenRate request_cell = 1; + TokenRate request_project = 2; + TokenRate packet_cell = 3; + TokenRate packet_project = 4; + // packet_destination_host charges the destination's /32 or /128, and + // packet_destination_prefix its /24 or /64, whatever the project. + TokenRate packet_destination_host = 5; + TokenRate packet_destination_prefix = 6; + // active_jobs and project_active_jobs bound router jobs executing at once + // in the cell and per project. + uint32 active_jobs = 7; + uint32 project_active_jobs = 8; + // queued_jobs and project_queued_jobs bound router jobs waiting for a + // slot. A request's selected routers are admitted together or refused + // with QueueFull. + uint32 queued_jobs = 9; + uint32 project_queued_jobs = 10; + // streams and project_streams bound live RunDiagnostic streams. + uint32 streams = 11; + uint32 project_streams = 12; + // queue_wait bounds a router job's wait for a slot (QueueTimeout). + google.protobuf.Duration queue_wait = 13; + uint32 ping_packets = 14; + uint32 traceroute_packets = 15; } message RunDiagnosticRequest { @@ -169,6 +210,12 @@ message Failure { string reason = 1; // message is a sanitized description of at most 256 bytes. string message = 2; + // scope is the limit that refused a Throttled, QueueFull or + // LimiterUnavailable router: cell, project, destination or queue. + string scope = 3; + // retry_delay is the advised delay before a new attempt, for a refusal + // that carries one. It is guidance, not a reservation. + google.protobuf.Duration retry_delay = 4; } // Complete is a stream's terminal coverage. expected equals successful + diff --git a/api/fabric/service/v1/testdata/capabilities.json b/api/fabric/service/v1/testdata/capabilities.json index fbcda4645..e6a3a749a 100644 --- a/api/fabric/service/v1/testdata/capabilities.json +++ b/api/fabric/service/v1/testdata/capabilities.json @@ -10,13 +10,30 @@ {"type": "QUERY_TYPE_PING", "addressFamilies": ["ADDRESS_FAMILY_IPV4", "ADDRESS_FAMILY_IPV6"]}, {"type": "QUERY_TYPE_TRACEROUTE", "addressFamilies": ["ADDRESS_FAMILY_IPV4", "ADDRESS_FAMILY_IPV6"]} ], - "features": ["router-outcomes", "terminal-coverage"], + "features": ["router-outcomes", "terminal-coverage", "aggregate-probe-budgets"], "limits": { "maxRequestLifetime": "120s", "maxNodeExecution": "30s", "maxSelectedRouters": 32, "maxInventoryRouters": 256, - "maxBudgets": {"maxResponseBytes": 131072, "maxPrefixes": 100, "maxPathsPerPrefix": 8, "maxCommunitiesPerPath": 64} + "maxBudgets": {"maxResponseBytes": 131072, "maxPrefixes": 100, "maxPathsPerPrefix": 8, "maxCommunitiesPerPath": 64}, + "admission": { + "requestCell": {"perSecond": 2, "burst": 8}, + "requestProject": {"perSecond": 0.2, "burst": 2}, + "packetCell": {"perSecond": 100, "burst": 640}, + "packetProject": {"perSecond": 20, "burst": 640}, + "packetDestinationHost": {"perSecond": 20, "burst": 640}, + "packetDestinationPrefix": {"perSecond": 40, "burst": 640}, + "activeJobs": 8, + "projectActiveJobs": 2, + "queuedJobs": 256, + "projectQueuedJobs": 32, + "streams": 16, + "projectStreams": 2, + "queueWait": "10s", + "pingPackets": 3, + "traceroutePackets": 20 + } }, "generatedAt": "2026-10-24T12:00:00Z" } diff --git a/api/fabric/v1/fabric.pb.go b/api/fabric/v1/fabric.pb.go index 02a3eaf8f..f45989b95 100644 --- a/api/fabric/v1/fabric.pb.go +++ b/api/fabric/v1/fabric.pb.go @@ -348,8 +348,11 @@ type ExecuteRequest struct { Query *Query `protobuf:"bytes,3,opt,name=query,proto3" json:"query,omitempty"` // expires_at is the absolute request expiration. A node rejects an expired // request and clamps its own deadline to it. - ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` - Budgets *Budgets `protobuf:"bytes,5,opt,name=budgets,proto3" json:"budgets,omitempty"` + ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` + Budgets *Budgets `protobuf:"bytes,5,opt,name=budgets,proto3" json:"budgets,omitempty"` + // permit authorizes one probe against the cell's aggregate packet budgets. + // Only the cell's gateway sets it; a node consumes each permit once. + Permit *ProbePermit `protobuf:"bytes,6,opt,name=permit,proto3" json:"permit,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -419,6 +422,124 @@ func (x *ExecuteRequest) GetBudgets() *Budgets { return nil } +func (x *ExecuteRequest) GetPermit() *ProbePermit { + if x != nil { + return x.Permit + } + return nil +} + +// ProbePermit is the cell gateway's authorization of one probe on one node: +// one attempt, its destination, operation and packet allowance, bound to +// the gateway's election epoch. It is internal to galactic. +type ProbePermit struct { + state protoimpl.MessageState `protogen:"open.v1"` + // id is unique per permit; a node refuses an ID it already consumed. + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + // epoch is the election Lease's UID and holder identity when the permit + // was issued, as "/". + Epoch string `protobuf:"bytes,2,opt,name=epoch,proto3" json:"epoch,omitempty"` + // request_id is the attempt the permit was issued for. + RequestId string `protobuf:"bytes,3,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + // node is the node the probe may run on. + Node string `protobuf:"bytes,4,opt,name=node,proto3" json:"node,omitempty"` + // destination is the probe's canonical numeric destination. + Destination string `protobuf:"bytes,5,opt,name=destination,proto3" json:"destination,omitempty"` + Operation QueryType `protobuf:"varint,6,opt,name=operation,proto3,enum=fabric.v1.QueryType" json:"operation,omitempty"` + // packets is the most probe packets the node may send under the permit. + Packets uint32 `protobuf:"varint,7,opt,name=packets,proto3" json:"packets,omitempty"` + // deadline is when the permit expires; the node sends nothing after it. + Deadline *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=deadline,proto3" json:"deadline,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ProbePermit) Reset() { + *x = ProbePermit{} + mi := &file_fabric_v1_fabric_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ProbePermit) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProbePermit) ProtoMessage() {} + +func (x *ProbePermit) ProtoReflect() protoreflect.Message { + mi := &file_fabric_v1_fabric_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProbePermit.ProtoReflect.Descriptor instead. +func (*ProbePermit) Descriptor() ([]byte, []int) { + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{3} +} + +func (x *ProbePermit) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *ProbePermit) GetEpoch() string { + if x != nil { + return x.Epoch + } + return "" +} + +func (x *ProbePermit) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +func (x *ProbePermit) GetNode() string { + if x != nil { + return x.Node + } + return "" +} + +func (x *ProbePermit) GetDestination() string { + if x != nil { + return x.Destination + } + return "" +} + +func (x *ProbePermit) GetOperation() QueryType { + if x != nil { + return x.Operation + } + return QueryType_QUERY_TYPE_UNSPECIFIED +} + +func (x *ProbePermit) GetPackets() uint32 { + if x != nil { + return x.Packets + } + return 0 +} + +func (x *ProbePermit) GetDeadline() *timestamppb.Timestamp { + if x != nil { + return x.Deadline + } + return nil +} + type ExecuteResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Observation *Observation `protobuf:"bytes,1,opt,name=observation,proto3" json:"observation,omitempty"` @@ -428,7 +549,7 @@ type ExecuteResponse struct { func (x *ExecuteResponse) Reset() { *x = ExecuteResponse{} - mi := &file_fabric_v1_fabric_proto_msgTypes[3] + mi := &file_fabric_v1_fabric_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -440,7 +561,7 @@ func (x *ExecuteResponse) String() string { func (*ExecuteResponse) ProtoMessage() {} func (x *ExecuteResponse) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[3] + mi := &file_fabric_v1_fabric_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -453,7 +574,7 @@ func (x *ExecuteResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecuteResponse.ProtoReflect.Descriptor instead. func (*ExecuteResponse) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{3} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{4} } func (x *ExecuteResponse) GetObservation() *Observation { @@ -492,7 +613,7 @@ type Observation struct { func (x *Observation) Reset() { *x = Observation{} - mi := &file_fabric_v1_fabric_proto_msgTypes[4] + mi := &file_fabric_v1_fabric_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -504,7 +625,7 @@ func (x *Observation) String() string { func (*Observation) ProtoMessage() {} func (x *Observation) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[4] + mi := &file_fabric_v1_fabric_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -517,7 +638,7 @@ func (x *Observation) ProtoReflect() protoreflect.Message { // Deprecated: Use Observation.ProtoReflect.Descriptor instead. func (*Observation) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{4} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{5} } func (x *Observation) GetNode() string { @@ -667,7 +788,7 @@ type RouteResult struct { func (x *RouteResult) Reset() { *x = RouteResult{} - mi := &file_fabric_v1_fabric_proto_msgTypes[5] + mi := &file_fabric_v1_fabric_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -679,7 +800,7 @@ func (x *RouteResult) String() string { func (*RouteResult) ProtoMessage() {} func (x *RouteResult) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[5] + mi := &file_fabric_v1_fabric_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -692,7 +813,7 @@ func (x *RouteResult) ProtoReflect() protoreflect.Message { // Deprecated: Use RouteResult.ProtoReflect.Descriptor instead. func (*RouteResult) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{5} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{6} } func (x *RouteResult) GetLookupKind() LookupKind { @@ -734,7 +855,7 @@ type IndexState struct { func (x *IndexState) Reset() { *x = IndexState{} - mi := &file_fabric_v1_fabric_proto_msgTypes[6] + mi := &file_fabric_v1_fabric_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -746,7 +867,7 @@ func (x *IndexState) String() string { func (*IndexState) ProtoMessage() {} func (x *IndexState) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[6] + mi := &file_fabric_v1_fabric_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -759,7 +880,7 @@ func (x *IndexState) ProtoReflect() protoreflect.Message { // Deprecated: Use IndexState.ProtoReflect.Descriptor instead. func (*IndexState) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{6} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{7} } func (x *IndexState) GetSyncedAt() *timestamppb.Timestamp { @@ -807,7 +928,7 @@ type PrefixObservation struct { func (x *PrefixObservation) Reset() { *x = PrefixObservation{} - mi := &file_fabric_v1_fabric_proto_msgTypes[7] + mi := &file_fabric_v1_fabric_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -819,7 +940,7 @@ func (x *PrefixObservation) String() string { func (*PrefixObservation) ProtoMessage() {} func (x *PrefixObservation) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[7] + mi := &file_fabric_v1_fabric_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -832,7 +953,7 @@ func (x *PrefixObservation) ProtoReflect() protoreflect.Message { // Deprecated: Use PrefixObservation.ProtoReflect.Descriptor instead. func (*PrefixObservation) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{7} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{8} } func (x *PrefixObservation) GetPrefix() string { @@ -897,7 +1018,7 @@ type Path struct { func (x *Path) Reset() { *x = Path{} - mi := &file_fabric_v1_fabric_proto_msgTypes[8] + mi := &file_fabric_v1_fabric_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -909,7 +1030,7 @@ func (x *Path) String() string { func (*Path) ProtoMessage() {} func (x *Path) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[8] + mi := &file_fabric_v1_fabric_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -922,7 +1043,7 @@ func (x *Path) ProtoReflect() protoreflect.Message { // Deprecated: Use Path.ProtoReflect.Descriptor instead. func (*Path) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{8} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{9} } func (x *Path) GetBest() bool { @@ -1097,7 +1218,7 @@ type ASSegment struct { func (x *ASSegment) Reset() { *x = ASSegment{} - mi := &file_fabric_v1_fabric_proto_msgTypes[9] + mi := &file_fabric_v1_fabric_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1109,7 +1230,7 @@ func (x *ASSegment) String() string { func (*ASSegment) ProtoMessage() {} func (x *ASSegment) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[9] + mi := &file_fabric_v1_fabric_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1122,7 +1243,7 @@ func (x *ASSegment) ProtoReflect() protoreflect.Message { // Deprecated: Use ASSegment.ProtoReflect.Descriptor instead. func (*ASSegment) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{9} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{10} } func (x *ASSegment) GetType() string { @@ -1152,7 +1273,7 @@ type NextHop struct { func (x *NextHop) Reset() { *x = NextHop{} - mi := &file_fabric_v1_fabric_proto_msgTypes[10] + mi := &file_fabric_v1_fabric_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1164,7 +1285,7 @@ func (x *NextHop) String() string { func (*NextHop) ProtoMessage() {} func (x *NextHop) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[10] + mi := &file_fabric_v1_fabric_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1177,7 +1298,7 @@ func (x *NextHop) ProtoReflect() protoreflect.Message { // Deprecated: Use NextHop.ProtoReflect.Descriptor instead. func (*NextHop) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{10} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{11} } func (x *NextHop) GetAddress() string { @@ -1232,7 +1353,7 @@ type Installation struct { func (x *Installation) Reset() { *x = Installation{} - mi := &file_fabric_v1_fabric_proto_msgTypes[11] + mi := &file_fabric_v1_fabric_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1244,7 +1365,7 @@ func (x *Installation) String() string { func (*Installation) ProtoMessage() {} func (x *Installation) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[11] + mi := &file_fabric_v1_fabric_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1257,7 +1378,7 @@ func (x *Installation) ProtoReflect() protoreflect.Message { // Deprecated: Use Installation.ProtoReflect.Descriptor instead. func (*Installation) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{11} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{12} } func (x *Installation) GetSampleTime() *timestamppb.Timestamp { @@ -1309,7 +1430,7 @@ type ZebraRoute struct { func (x *ZebraRoute) Reset() { *x = ZebraRoute{} - mi := &file_fabric_v1_fabric_proto_msgTypes[12] + mi := &file_fabric_v1_fabric_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1321,7 +1442,7 @@ func (x *ZebraRoute) String() string { func (*ZebraRoute) ProtoMessage() {} func (x *ZebraRoute) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[12] + mi := &file_fabric_v1_fabric_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1334,7 +1455,7 @@ func (x *ZebraRoute) ProtoReflect() protoreflect.Message { // Deprecated: Use ZebraRoute.ProtoReflect.Descriptor instead. func (*ZebraRoute) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{12} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{13} } func (x *ZebraRoute) GetProtocol() string { @@ -1392,7 +1513,7 @@ type ZebraNextHop struct { func (x *ZebraNextHop) Reset() { *x = ZebraNextHop{} - mi := &file_fabric_v1_fabric_proto_msgTypes[13] + mi := &file_fabric_v1_fabric_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1404,7 +1525,7 @@ func (x *ZebraNextHop) String() string { func (*ZebraNextHop) ProtoMessage() {} func (x *ZebraNextHop) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[13] + mi := &file_fabric_v1_fabric_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1417,7 +1538,7 @@ func (x *ZebraNextHop) ProtoReflect() protoreflect.Message { // Deprecated: Use ZebraNextHop.ProtoReflect.Descriptor instead. func (*ZebraNextHop) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{13} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{14} } func (x *ZebraNextHop) GetAddress() string { @@ -1468,7 +1589,7 @@ type SummaryResult struct { func (x *SummaryResult) Reset() { *x = SummaryResult{} - mi := &file_fabric_v1_fabric_proto_msgTypes[14] + mi := &file_fabric_v1_fabric_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1480,7 +1601,7 @@ func (x *SummaryResult) String() string { func (*SummaryResult) ProtoMessage() {} func (x *SummaryResult) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[14] + mi := &file_fabric_v1_fabric_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1493,7 +1614,7 @@ func (x *SummaryResult) ProtoReflect() protoreflect.Message { // Deprecated: Use SummaryResult.ProtoReflect.Descriptor instead. func (*SummaryResult) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{14} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{15} } func (x *SummaryResult) GetRouterId() string { @@ -1554,7 +1675,7 @@ type Peer struct { func (x *Peer) Reset() { *x = Peer{} - mi := &file_fabric_v1_fabric_proto_msgTypes[15] + mi := &file_fabric_v1_fabric_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1566,7 +1687,7 @@ func (x *Peer) String() string { func (*Peer) ProtoMessage() {} func (x *Peer) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[15] + mi := &file_fabric_v1_fabric_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1579,7 +1700,7 @@ func (x *Peer) ProtoReflect() protoreflect.Message { // Deprecated: Use Peer.ProtoReflect.Descriptor instead. func (*Peer) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{15} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{16} } func (x *Peer) GetAddress() string { @@ -1696,7 +1817,7 @@ type PingResult struct { func (x *PingResult) Reset() { *x = PingResult{} - mi := &file_fabric_v1_fabric_proto_msgTypes[16] + mi := &file_fabric_v1_fabric_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1708,7 +1829,7 @@ func (x *PingResult) String() string { func (*PingResult) ProtoMessage() {} func (x *PingResult) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[16] + mi := &file_fabric_v1_fabric_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1721,7 +1842,7 @@ func (x *PingResult) ProtoReflect() protoreflect.Message { // Deprecated: Use PingResult.ProtoReflect.Descriptor instead. func (*PingResult) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{16} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{17} } func (x *PingResult) GetSource() string { @@ -1793,7 +1914,7 @@ type TracerouteResult struct { func (x *TracerouteResult) Reset() { *x = TracerouteResult{} - mi := &file_fabric_v1_fabric_proto_msgTypes[17] + mi := &file_fabric_v1_fabric_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1805,7 +1926,7 @@ func (x *TracerouteResult) String() string { func (*TracerouteResult) ProtoMessage() {} func (x *TracerouteResult) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[17] + mi := &file_fabric_v1_fabric_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1818,7 +1939,7 @@ func (x *TracerouteResult) ProtoReflect() protoreflect.Message { // Deprecated: Use TracerouteResult.ProtoReflect.Descriptor instead. func (*TracerouteResult) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{17} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{18} } func (x *TracerouteResult) GetSource() string { @@ -1859,7 +1980,7 @@ type Hop struct { func (x *Hop) Reset() { *x = Hop{} - mi := &file_fabric_v1_fabric_proto_msgTypes[18] + mi := &file_fabric_v1_fabric_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1871,7 +1992,7 @@ func (x *Hop) String() string { func (*Hop) ProtoMessage() {} func (x *Hop) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[18] + mi := &file_fabric_v1_fabric_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1884,7 +2005,7 @@ func (x *Hop) ProtoReflect() protoreflect.Message { // Deprecated: Use Hop.ProtoReflect.Descriptor instead. func (*Hop) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{18} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{19} } func (x *Hop) GetTtl() uint32 { @@ -1920,7 +2041,7 @@ type ProbeReply struct { func (x *ProbeReply) Reset() { *x = ProbeReply{} - mi := &file_fabric_v1_fabric_proto_msgTypes[19] + mi := &file_fabric_v1_fabric_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1932,7 +2053,7 @@ func (x *ProbeReply) String() string { func (*ProbeReply) ProtoMessage() {} func (x *ProbeReply) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[19] + mi := &file_fabric_v1_fabric_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1945,7 +2066,7 @@ func (x *ProbeReply) ProtoReflect() protoreflect.Message { // Deprecated: Use ProbeReply.ProtoReflect.Descriptor instead. func (*ProbeReply) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{19} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{20} } func (x *ProbeReply) GetSequence() uint32 { @@ -1998,7 +2119,7 @@ type InfoRequest struct { func (x *InfoRequest) Reset() { *x = InfoRequest{} - mi := &file_fabric_v1_fabric_proto_msgTypes[20] + mi := &file_fabric_v1_fabric_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2010,7 +2131,7 @@ func (x *InfoRequest) String() string { func (*InfoRequest) ProtoMessage() {} func (x *InfoRequest) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[20] + mi := &file_fabric_v1_fabric_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2023,7 +2144,7 @@ func (x *InfoRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use InfoRequest.ProtoReflect.Descriptor instead. func (*InfoRequest) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{20} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{21} } type InfoResponse struct { @@ -2040,14 +2161,18 @@ type InfoResponse struct { EnabledQueryTypes []QueryType `protobuf:"varint,8,rep,packed,name=enabled_query_types,json=enabledQueryTypes,proto3,enum=fabric.v1.QueryType" json:"enabled_query_types,omitempty"` // probe_sources lists the per-family probe source addresses that are // available. - ProbeSources []string `protobuf:"bytes,9,rep,name=probe_sources,json=probeSources,proto3" json:"probe_sources,omitempty"` + ProbeSources []string `protobuf:"bytes,9,rep,name=probe_sources,json=probeSources,proto3" json:"probe_sources,omitempty"` + // probe_permits is true when the node verifies and enforces each probe's + // ProbePermit. A gateway enforcing aggregate probe budgets sends probes + // only to such nodes. + ProbePermits bool `protobuf:"varint,10,opt,name=probe_permits,json=probePermits,proto3" json:"probe_permits,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InfoResponse) Reset() { *x = InfoResponse{} - mi := &file_fabric_v1_fabric_proto_msgTypes[21] + mi := &file_fabric_v1_fabric_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2059,7 +2184,7 @@ func (x *InfoResponse) String() string { func (*InfoResponse) ProtoMessage() {} func (x *InfoResponse) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[21] + mi := &file_fabric_v1_fabric_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2072,7 +2197,7 @@ func (x *InfoResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use InfoResponse.ProtoReflect.Descriptor instead. func (*InfoResponse) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{21} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{22} } func (x *InfoResponse) GetNode() string { @@ -2138,6 +2263,13 @@ func (x *InfoResponse) GetProbeSources() []string { return nil } +func (x *InfoResponse) GetProbePermits() bool { + if x != nil { + return x.ProbePermits + } + return false +} + type QueryRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Query *Query `protobuf:"bytes,1,opt,name=query,proto3" json:"query,omitempty"` @@ -2153,7 +2285,7 @@ type QueryRequest struct { func (x *QueryRequest) Reset() { *x = QueryRequest{} - mi := &file_fabric_v1_fabric_proto_msgTypes[22] + mi := &file_fabric_v1_fabric_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2165,7 +2297,7 @@ func (x *QueryRequest) String() string { func (*QueryRequest) ProtoMessage() {} func (x *QueryRequest) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[22] + mi := &file_fabric_v1_fabric_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2178,7 +2310,7 @@ func (x *QueryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use QueryRequest.ProtoReflect.Descriptor instead. func (*QueryRequest) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{22} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{23} } func (x *QueryRequest) GetQuery() *Query { @@ -2219,7 +2351,7 @@ type QueryResponse struct { func (x *QueryResponse) Reset() { *x = QueryResponse{} - mi := &file_fabric_v1_fabric_proto_msgTypes[23] + mi := &file_fabric_v1_fabric_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2231,7 +2363,7 @@ func (x *QueryResponse) String() string { func (*QueryResponse) ProtoMessage() {} func (x *QueryResponse) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[23] + mi := &file_fabric_v1_fabric_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2244,7 +2376,7 @@ func (x *QueryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use QueryResponse.ProtoReflect.Descriptor instead. func (*QueryResponse) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{23} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{24} } func (x *QueryResponse) GetRequestId() string { @@ -2273,7 +2405,7 @@ type NodeResult struct { func (x *NodeResult) Reset() { *x = NodeResult{} - mi := &file_fabric_v1_fabric_proto_msgTypes[24] + mi := &file_fabric_v1_fabric_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2285,7 +2417,7 @@ func (x *NodeResult) String() string { func (*NodeResult) ProtoMessage() {} func (x *NodeResult) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[24] + mi := &file_fabric_v1_fabric_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2298,7 +2430,7 @@ func (x *NodeResult) ProtoReflect() protoreflect.Message { // Deprecated: Use NodeResult.ProtoReflect.Descriptor instead. func (*NodeResult) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{24} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{25} } func (x *NodeResult) GetNode() string { @@ -2337,7 +2469,7 @@ type ListNodesRequest struct { func (x *ListNodesRequest) Reset() { *x = ListNodesRequest{} - mi := &file_fabric_v1_fabric_proto_msgTypes[25] + mi := &file_fabric_v1_fabric_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2349,7 +2481,7 @@ func (x *ListNodesRequest) String() string { func (*ListNodesRequest) ProtoMessage() {} func (x *ListNodesRequest) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[25] + mi := &file_fabric_v1_fabric_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2362,7 +2494,7 @@ func (x *ListNodesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListNodesRequest.ProtoReflect.Descriptor instead. func (*ListNodesRequest) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{25} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{26} } type ListNodesResponse struct { @@ -2374,7 +2506,7 @@ type ListNodesResponse struct { func (x *ListNodesResponse) Reset() { *x = ListNodesResponse{} - mi := &file_fabric_v1_fabric_proto_msgTypes[26] + mi := &file_fabric_v1_fabric_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2386,7 +2518,7 @@ func (x *ListNodesResponse) String() string { func (*ListNodesResponse) ProtoMessage() {} func (x *ListNodesResponse) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[26] + mi := &file_fabric_v1_fabric_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2399,7 +2531,7 @@ func (x *ListNodesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListNodesResponse.ProtoReflect.Descriptor instead. func (*ListNodesResponse) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{26} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{27} } func (x *ListNodesResponse) GetNodes() []*NodeEndpoint { @@ -2422,7 +2554,7 @@ type NodeEndpoint struct { func (x *NodeEndpoint) Reset() { *x = NodeEndpoint{} - mi := &file_fabric_v1_fabric_proto_msgTypes[27] + mi := &file_fabric_v1_fabric_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2434,7 +2566,7 @@ func (x *NodeEndpoint) String() string { func (*NodeEndpoint) ProtoMessage() {} func (x *NodeEndpoint) ProtoReflect() protoreflect.Message { - mi := &file_fabric_v1_fabric_proto_msgTypes[27] + mi := &file_fabric_v1_fabric_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2447,7 +2579,7 @@ func (x *NodeEndpoint) ProtoReflect() protoreflect.Message { // Deprecated: Use NodeEndpoint.ProtoReflect.Descriptor instead. func (*NodeEndpoint) Descriptor() ([]byte, []int) { - return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{27} + return file_fabric_v1_fabric_proto_rawDescGZIP(), []int{28} } func (x *NodeEndpoint) GetNode() string { @@ -2498,7 +2630,7 @@ const file_fabric_v1_fabric_proto_rawDesc = "" + "\x12max_response_bytes\x18\x01 \x01(\rR\x10maxResponseBytes\x12!\n" + "\fmax_prefixes\x18\x02 \x01(\rR\vmaxPrefixes\x12/\n" + "\x14max_paths_per_prefix\x18\x03 \x01(\rR\x11maxPathsPerPrefix\x127\n" + - "\x18max_communities_per_path\x18\x04 \x01(\rR\x15maxCommunitiesPerPath\"\xd4\x01\n" + + "\x18max_communities_per_path\x18\x04 \x01(\rR\x15maxCommunitiesPerPath\"\x84\x02\n" + "\x0eExecuteRequest\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\tR\trequestId\x12\x12\n" + @@ -2506,7 +2638,18 @@ const file_fabric_v1_fabric_proto_rawDesc = "" + "\x05query\x18\x03 \x01(\v2\x10.fabric.v1.QueryR\x05query\x129\n" + "\n" + "expires_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\x12,\n" + - "\abudgets\x18\x05 \x01(\v2\x12.fabric.v1.BudgetsR\abudgets\"K\n" + + "\abudgets\x18\x05 \x01(\v2\x12.fabric.v1.BudgetsR\abudgets\x12.\n" + + "\x06permit\x18\x06 \x01(\v2\x16.fabric.v1.ProbePermitR\x06permit\"\x8e\x02\n" + + "\vProbePermit\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x14\n" + + "\x05epoch\x18\x02 \x01(\tR\x05epoch\x12\x1d\n" + + "\n" + + "request_id\x18\x03 \x01(\tR\trequestId\x12\x12\n" + + "\x04node\x18\x04 \x01(\tR\x04node\x12 \n" + + "\vdestination\x18\x05 \x01(\tR\vdestination\x122\n" + + "\toperation\x18\x06 \x01(\x0e2\x14.fabric.v1.QueryTypeR\toperation\x12\x18\n" + + "\apackets\x18\a \x01(\rR\apackets\x126\n" + + "\bdeadline\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\bdeadline\"K\n" + "\x0fExecuteResponse\x128\n" + "\vobservation\x18\x01 \x01(\v2\x16.fabric.v1.ObservationR\vobservation\"\xb6\x04\n" + "\vObservation\x12\x12\n" + @@ -2663,7 +2806,7 @@ const file_fabric_v1_fabric_proto_rawDesc = "" + "\atimeout\x18\x04 \x01(\bR\atimeout\x12\x1b\n" + "\ticmp_type\x18\x05 \x01(\tR\bicmpType\x12\x1b\n" + "\ticmp_code\x18\x06 \x01(\rR\bicmpCode\"\r\n" + - "\vInfoRequest\"\xd5\x02\n" + + "\vInfoRequest\"\xfa\x02\n" + "\fInfoResponse\x12\x12\n" + "\x04node\x18\x01 \x01(\tR\x04node\x12\x12\n" + "\x04site\x18\x02 \x01(\tR\x04site\x12\x1b\n" + @@ -2674,7 +2817,9 @@ const file_fabric_v1_fabric_proto_rawDesc = "" + "\x15diagnostics_available\x18\x06 \x01(\bR\x14diagnosticsAvailable\x12-\n" + "\x12unavailable_reason\x18\a \x01(\tR\x11unavailableReason\x12D\n" + "\x13enabled_query_types\x18\b \x03(\x0e2\x14.fabric.v1.QueryTypeR\x11enabledQueryTypes\x12#\n" + - "\rprobe_sources\x18\t \x03(\tR\fprobeSources\"\xaf\x01\n" + + "\rprobe_sources\x18\t \x03(\tR\fprobeSources\x12#\n" + + "\rprobe_permits\x18\n" + + " \x01(\bR\fprobePermits\"\xaf\x01\n" + "\fQueryRequest\x12&\n" + "\x05query\x18\x01 \x01(\v2\x10.fabric.v1.QueryR\x05query\x12\x14\n" + "\x05nodes\x18\x02 \x03(\tR\x05nodes\x12,\n" + @@ -2739,7 +2884,7 @@ func file_fabric_v1_fabric_proto_rawDescGZIP() []byte { } var file_fabric_v1_fabric_proto_enumTypes = make([]protoimpl.EnumInfo, 3) -var file_fabric_v1_fabric_proto_msgTypes = make([]protoimpl.MessageInfo, 28) +var file_fabric_v1_fabric_proto_msgTypes = make([]protoimpl.MessageInfo, 29) var file_fabric_v1_fabric_proto_goTypes = []any{ (QueryType)(0), // 0: fabric.v1.QueryType (AddressFamily)(0), // 1: fabric.v1.AddressFamily @@ -2747,89 +2892,93 @@ var file_fabric_v1_fabric_proto_goTypes = []any{ (*Query)(nil), // 3: fabric.v1.Query (*Budgets)(nil), // 4: fabric.v1.Budgets (*ExecuteRequest)(nil), // 5: fabric.v1.ExecuteRequest - (*ExecuteResponse)(nil), // 6: fabric.v1.ExecuteResponse - (*Observation)(nil), // 7: fabric.v1.Observation - (*RouteResult)(nil), // 8: fabric.v1.RouteResult - (*IndexState)(nil), // 9: fabric.v1.IndexState - (*PrefixObservation)(nil), // 10: fabric.v1.PrefixObservation - (*Path)(nil), // 11: fabric.v1.Path - (*ASSegment)(nil), // 12: fabric.v1.ASSegment - (*NextHop)(nil), // 13: fabric.v1.NextHop - (*Installation)(nil), // 14: fabric.v1.Installation - (*ZebraRoute)(nil), // 15: fabric.v1.ZebraRoute - (*ZebraNextHop)(nil), // 16: fabric.v1.ZebraNextHop - (*SummaryResult)(nil), // 17: fabric.v1.SummaryResult - (*Peer)(nil), // 18: fabric.v1.Peer - (*PingResult)(nil), // 19: fabric.v1.PingResult - (*TracerouteResult)(nil), // 20: fabric.v1.TracerouteResult - (*Hop)(nil), // 21: fabric.v1.Hop - (*ProbeReply)(nil), // 22: fabric.v1.ProbeReply - (*InfoRequest)(nil), // 23: fabric.v1.InfoRequest - (*InfoResponse)(nil), // 24: fabric.v1.InfoResponse - (*QueryRequest)(nil), // 25: fabric.v1.QueryRequest - (*QueryResponse)(nil), // 26: fabric.v1.QueryResponse - (*NodeResult)(nil), // 27: fabric.v1.NodeResult - (*ListNodesRequest)(nil), // 28: fabric.v1.ListNodesRequest - (*ListNodesResponse)(nil), // 29: fabric.v1.ListNodesResponse - (*NodeEndpoint)(nil), // 30: fabric.v1.NodeEndpoint - (*timestamppb.Timestamp)(nil), // 31: google.protobuf.Timestamp - (*durationpb.Duration)(nil), // 32: google.protobuf.Duration + (*ProbePermit)(nil), // 6: fabric.v1.ProbePermit + (*ExecuteResponse)(nil), // 7: fabric.v1.ExecuteResponse + (*Observation)(nil), // 8: fabric.v1.Observation + (*RouteResult)(nil), // 9: fabric.v1.RouteResult + (*IndexState)(nil), // 10: fabric.v1.IndexState + (*PrefixObservation)(nil), // 11: fabric.v1.PrefixObservation + (*Path)(nil), // 12: fabric.v1.Path + (*ASSegment)(nil), // 13: fabric.v1.ASSegment + (*NextHop)(nil), // 14: fabric.v1.NextHop + (*Installation)(nil), // 15: fabric.v1.Installation + (*ZebraRoute)(nil), // 16: fabric.v1.ZebraRoute + (*ZebraNextHop)(nil), // 17: fabric.v1.ZebraNextHop + (*SummaryResult)(nil), // 18: fabric.v1.SummaryResult + (*Peer)(nil), // 19: fabric.v1.Peer + (*PingResult)(nil), // 20: fabric.v1.PingResult + (*TracerouteResult)(nil), // 21: fabric.v1.TracerouteResult + (*Hop)(nil), // 22: fabric.v1.Hop + (*ProbeReply)(nil), // 23: fabric.v1.ProbeReply + (*InfoRequest)(nil), // 24: fabric.v1.InfoRequest + (*InfoResponse)(nil), // 25: fabric.v1.InfoResponse + (*QueryRequest)(nil), // 26: fabric.v1.QueryRequest + (*QueryResponse)(nil), // 27: fabric.v1.QueryResponse + (*NodeResult)(nil), // 28: fabric.v1.NodeResult + (*ListNodesRequest)(nil), // 29: fabric.v1.ListNodesRequest + (*ListNodesResponse)(nil), // 30: fabric.v1.ListNodesResponse + (*NodeEndpoint)(nil), // 31: fabric.v1.NodeEndpoint + (*timestamppb.Timestamp)(nil), // 32: google.protobuf.Timestamp + (*durationpb.Duration)(nil), // 33: google.protobuf.Duration } var file_fabric_v1_fabric_proto_depIdxs = []int32{ 0, // 0: fabric.v1.Query.type:type_name -> fabric.v1.QueryType 1, // 1: fabric.v1.Query.address_family:type_name -> fabric.v1.AddressFamily 3, // 2: fabric.v1.ExecuteRequest.query:type_name -> fabric.v1.Query - 31, // 3: fabric.v1.ExecuteRequest.expires_at:type_name -> google.protobuf.Timestamp + 32, // 3: fabric.v1.ExecuteRequest.expires_at:type_name -> google.protobuf.Timestamp 4, // 4: fabric.v1.ExecuteRequest.budgets:type_name -> fabric.v1.Budgets - 7, // 5: fabric.v1.ExecuteResponse.observation:type_name -> fabric.v1.Observation - 31, // 6: fabric.v1.Observation.sample_time:type_name -> google.protobuf.Timestamp - 32, // 7: fabric.v1.Observation.duration:type_name -> google.protobuf.Duration - 8, // 8: fabric.v1.Observation.routes:type_name -> fabric.v1.RouteResult - 17, // 9: fabric.v1.Observation.summary:type_name -> fabric.v1.SummaryResult - 19, // 10: fabric.v1.Observation.ping:type_name -> fabric.v1.PingResult - 20, // 11: fabric.v1.Observation.traceroute:type_name -> fabric.v1.TracerouteResult - 2, // 12: fabric.v1.RouteResult.lookup_kind:type_name -> fabric.v1.LookupKind - 10, // 13: fabric.v1.RouteResult.prefixes:type_name -> fabric.v1.PrefixObservation - 9, // 14: fabric.v1.RouteResult.index:type_name -> fabric.v1.IndexState - 31, // 15: fabric.v1.IndexState.synced_at:type_name -> google.protobuf.Timestamp - 31, // 16: fabric.v1.IndexState.last_update:type_name -> google.protobuf.Timestamp - 11, // 17: fabric.v1.PrefixObservation.paths:type_name -> fabric.v1.Path - 14, // 18: fabric.v1.PrefixObservation.installation:type_name -> fabric.v1.Installation - 12, // 19: fabric.v1.Path.as_path_segments:type_name -> fabric.v1.ASSegment - 13, // 20: fabric.v1.Path.next_hops:type_name -> fabric.v1.NextHop - 31, // 21: fabric.v1.Path.last_update:type_name -> google.protobuf.Timestamp - 31, // 22: fabric.v1.Installation.sample_time:type_name -> google.protobuf.Timestamp - 15, // 23: fabric.v1.Installation.routes:type_name -> fabric.v1.ZebraRoute - 16, // 24: fabric.v1.ZebraRoute.next_hops:type_name -> fabric.v1.ZebraNextHop - 18, // 25: fabric.v1.SummaryResult.peers:type_name -> fabric.v1.Peer - 32, // 26: fabric.v1.Peer.uptime:type_name -> google.protobuf.Duration - 22, // 27: fabric.v1.PingResult.replies:type_name -> fabric.v1.ProbeReply - 32, // 28: fabric.v1.PingResult.rtt_min:type_name -> google.protobuf.Duration - 32, // 29: fabric.v1.PingResult.rtt_avg:type_name -> google.protobuf.Duration - 32, // 30: fabric.v1.PingResult.rtt_max:type_name -> google.protobuf.Duration - 21, // 31: fabric.v1.TracerouteResult.hops:type_name -> fabric.v1.Hop - 22, // 32: fabric.v1.Hop.probes:type_name -> fabric.v1.ProbeReply - 32, // 33: fabric.v1.ProbeReply.rtt:type_name -> google.protobuf.Duration - 0, // 34: fabric.v1.InfoResponse.enabled_query_types:type_name -> fabric.v1.QueryType - 3, // 35: fabric.v1.QueryRequest.query:type_name -> fabric.v1.Query - 4, // 36: fabric.v1.QueryRequest.budgets:type_name -> fabric.v1.Budgets - 32, // 37: fabric.v1.QueryRequest.timeout:type_name -> google.protobuf.Duration - 27, // 38: fabric.v1.QueryResponse.results:type_name -> fabric.v1.NodeResult - 7, // 39: fabric.v1.NodeResult.observation:type_name -> fabric.v1.Observation - 30, // 40: fabric.v1.ListNodesResponse.nodes:type_name -> fabric.v1.NodeEndpoint - 5, // 41: fabric.v1.FabricService.Execute:input_type -> fabric.v1.ExecuteRequest - 23, // 42: fabric.v1.FabricService.Info:input_type -> fabric.v1.InfoRequest - 25, // 43: fabric.v1.FabricGatewayService.Query:input_type -> fabric.v1.QueryRequest - 28, // 44: fabric.v1.FabricGatewayService.ListNodes:input_type -> fabric.v1.ListNodesRequest - 6, // 45: fabric.v1.FabricService.Execute:output_type -> fabric.v1.ExecuteResponse - 24, // 46: fabric.v1.FabricService.Info:output_type -> fabric.v1.InfoResponse - 26, // 47: fabric.v1.FabricGatewayService.Query:output_type -> fabric.v1.QueryResponse - 29, // 48: fabric.v1.FabricGatewayService.ListNodes:output_type -> fabric.v1.ListNodesResponse - 45, // [45:49] is the sub-list for method output_type - 41, // [41:45] is the sub-list for method input_type - 41, // [41:41] is the sub-list for extension type_name - 41, // [41:41] is the sub-list for extension extendee - 0, // [0:41] is the sub-list for field type_name + 6, // 5: fabric.v1.ExecuteRequest.permit:type_name -> fabric.v1.ProbePermit + 0, // 6: fabric.v1.ProbePermit.operation:type_name -> fabric.v1.QueryType + 32, // 7: fabric.v1.ProbePermit.deadline:type_name -> google.protobuf.Timestamp + 8, // 8: fabric.v1.ExecuteResponse.observation:type_name -> fabric.v1.Observation + 32, // 9: fabric.v1.Observation.sample_time:type_name -> google.protobuf.Timestamp + 33, // 10: fabric.v1.Observation.duration:type_name -> google.protobuf.Duration + 9, // 11: fabric.v1.Observation.routes:type_name -> fabric.v1.RouteResult + 18, // 12: fabric.v1.Observation.summary:type_name -> fabric.v1.SummaryResult + 20, // 13: fabric.v1.Observation.ping:type_name -> fabric.v1.PingResult + 21, // 14: fabric.v1.Observation.traceroute:type_name -> fabric.v1.TracerouteResult + 2, // 15: fabric.v1.RouteResult.lookup_kind:type_name -> fabric.v1.LookupKind + 11, // 16: fabric.v1.RouteResult.prefixes:type_name -> fabric.v1.PrefixObservation + 10, // 17: fabric.v1.RouteResult.index:type_name -> fabric.v1.IndexState + 32, // 18: fabric.v1.IndexState.synced_at:type_name -> google.protobuf.Timestamp + 32, // 19: fabric.v1.IndexState.last_update:type_name -> google.protobuf.Timestamp + 12, // 20: fabric.v1.PrefixObservation.paths:type_name -> fabric.v1.Path + 15, // 21: fabric.v1.PrefixObservation.installation:type_name -> fabric.v1.Installation + 13, // 22: fabric.v1.Path.as_path_segments:type_name -> fabric.v1.ASSegment + 14, // 23: fabric.v1.Path.next_hops:type_name -> fabric.v1.NextHop + 32, // 24: fabric.v1.Path.last_update:type_name -> google.protobuf.Timestamp + 32, // 25: fabric.v1.Installation.sample_time:type_name -> google.protobuf.Timestamp + 16, // 26: fabric.v1.Installation.routes:type_name -> fabric.v1.ZebraRoute + 17, // 27: fabric.v1.ZebraRoute.next_hops:type_name -> fabric.v1.ZebraNextHop + 19, // 28: fabric.v1.SummaryResult.peers:type_name -> fabric.v1.Peer + 33, // 29: fabric.v1.Peer.uptime:type_name -> google.protobuf.Duration + 23, // 30: fabric.v1.PingResult.replies:type_name -> fabric.v1.ProbeReply + 33, // 31: fabric.v1.PingResult.rtt_min:type_name -> google.protobuf.Duration + 33, // 32: fabric.v1.PingResult.rtt_avg:type_name -> google.protobuf.Duration + 33, // 33: fabric.v1.PingResult.rtt_max:type_name -> google.protobuf.Duration + 22, // 34: fabric.v1.TracerouteResult.hops:type_name -> fabric.v1.Hop + 23, // 35: fabric.v1.Hop.probes:type_name -> fabric.v1.ProbeReply + 33, // 36: fabric.v1.ProbeReply.rtt:type_name -> google.protobuf.Duration + 0, // 37: fabric.v1.InfoResponse.enabled_query_types:type_name -> fabric.v1.QueryType + 3, // 38: fabric.v1.QueryRequest.query:type_name -> fabric.v1.Query + 4, // 39: fabric.v1.QueryRequest.budgets:type_name -> fabric.v1.Budgets + 33, // 40: fabric.v1.QueryRequest.timeout:type_name -> google.protobuf.Duration + 28, // 41: fabric.v1.QueryResponse.results:type_name -> fabric.v1.NodeResult + 8, // 42: fabric.v1.NodeResult.observation:type_name -> fabric.v1.Observation + 31, // 43: fabric.v1.ListNodesResponse.nodes:type_name -> fabric.v1.NodeEndpoint + 5, // 44: fabric.v1.FabricService.Execute:input_type -> fabric.v1.ExecuteRequest + 24, // 45: fabric.v1.FabricService.Info:input_type -> fabric.v1.InfoRequest + 26, // 46: fabric.v1.FabricGatewayService.Query:input_type -> fabric.v1.QueryRequest + 29, // 47: fabric.v1.FabricGatewayService.ListNodes:input_type -> fabric.v1.ListNodesRequest + 7, // 48: fabric.v1.FabricService.Execute:output_type -> fabric.v1.ExecuteResponse + 25, // 49: fabric.v1.FabricService.Info:output_type -> fabric.v1.InfoResponse + 27, // 50: fabric.v1.FabricGatewayService.Query:output_type -> fabric.v1.QueryResponse + 30, // 51: fabric.v1.FabricGatewayService.ListNodes:output_type -> fabric.v1.ListNodesResponse + 48, // [48:52] is the sub-list for method output_type + 44, // [44:48] is the sub-list for method input_type + 44, // [44:44] is the sub-list for extension type_name + 44, // [44:44] is the sub-list for extension extendee + 0, // [0:44] is the sub-list for field type_name } func init() { file_fabric_v1_fabric_proto_init() } @@ -2837,20 +2986,20 @@ func file_fabric_v1_fabric_proto_init() { if File_fabric_v1_fabric_proto != nil { return } - file_fabric_v1_fabric_proto_msgTypes[4].OneofWrappers = []any{ + file_fabric_v1_fabric_proto_msgTypes[5].OneofWrappers = []any{ (*Observation_Routes)(nil), (*Observation_Summary)(nil), (*Observation_Ping)(nil), (*Observation_Traceroute)(nil), } - file_fabric_v1_fabric_proto_msgTypes[8].OneofWrappers = []any{} + file_fabric_v1_fabric_proto_msgTypes[9].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_fabric_v1_fabric_proto_rawDesc), len(file_fabric_v1_fabric_proto_rawDesc)), NumEnums: 3, - NumMessages: 28, + NumMessages: 29, NumExtensions: 0, NumServices: 2, }, diff --git a/api/fabric/v1/fabric.proto b/api/fabric/v1/fabric.proto index 69a230e3c..563fafa0b 100644 --- a/api/fabric/v1/fabric.proto +++ b/api/fabric/v1/fabric.proto @@ -84,6 +84,31 @@ message ExecuteRequest { // request and clamps its own deadline to it. google.protobuf.Timestamp expires_at = 4; Budgets budgets = 5; + // permit authorizes one probe against the cell's aggregate packet budgets. + // Only the cell's gateway sets it; a node consumes each permit once. + ProbePermit permit = 6; +} + +// ProbePermit is the cell gateway's authorization of one probe on one node: +// one attempt, its destination, operation and packet allowance, bound to +// the gateway's election epoch. It is internal to galactic. +message ProbePermit { + // id is unique per permit; a node refuses an ID it already consumed. + string id = 1; + // epoch is the election Lease's UID and holder identity when the permit + // was issued, as "/". + string epoch = 2; + // request_id is the attempt the permit was issued for. + string request_id = 3; + // node is the node the probe may run on. + string node = 4; + // destination is the probe's canonical numeric destination. + string destination = 5; + QueryType operation = 6; + // packets is the most probe packets the node may send under the permit. + uint32 packets = 7; + // deadline is when the permit expires; the node sends nothing after it. + google.protobuf.Timestamp deadline = 8; } message ExecuteResponse { @@ -309,6 +334,10 @@ message InfoResponse { // probe_sources lists the per-family probe source addresses that are // available. repeated string probe_sources = 9; + // probe_permits is true when the node verifies and enforces each probe's + // ProbePermit. A gateway enforcing aggregate probe budgets sends probes + // only to such nodes. + bool probe_permits = 10; } message QueryRequest { diff --git a/cmd/fabric-api/gateway.go b/cmd/fabric-api/gateway.go index ba3790c1a..ae2538495 100644 --- a/cmd/fabric-api/gateway.go +++ b/cmd/fabric-api/gateway.go @@ -20,7 +20,10 @@ import ( "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/uuid" + "k8s.io/client-go/kubernetes" clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/leaderelection/resourcelock" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" @@ -30,6 +33,7 @@ import ( fabricapi "go.datum.net/galactic/internal/fabric/api/v1alpha1" "go.datum.net/galactic/internal/fabric/gateway" + "go.datum.net/galactic/internal/fabric/gateway/limit" "go.datum.net/galactic/internal/fabric/identity" "go.datum.net/galactic/internal/fabric/query" "go.datum.net/galactic/internal/metadata" @@ -49,6 +53,7 @@ type gatewayOptions struct { maxInFlight int retention, cleanupGrace time.Duration serviceIdentities []string + aggregateBudgets bool } func newGatewayCommand() *cobra.Command { @@ -94,6 +99,10 @@ func newGatewayCommand() *cobra.Command { f.StringSliceVar(&o.serviceIdentities, "service-identities", nil, "Names of the Looking Glass service identities (spiffe://fabric-api.datumapis.com/cell//service/) "+ "allowed to call this cell's gateway; empty allows none") + f.BoolVar(&o.aggregateBudgets, "aggregate-budgets", false, + "Enforce the cell's aggregate admission and probe packet budgets on every caller, issue probe permits to "+ + "nodes, and bound each principal's share of --cell-slots and --cell-queue to the contract defaults; "+ + "every node must run with --probe-permits first") return cmd } @@ -130,14 +139,29 @@ func runGateway(parent context.Context, o *gatewayOptions) error { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(fabricapi.AddToScheme(scheme)) - mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ - Scheme: scheme, - Metrics: metricsserver.Options{BindAddress: o.metricsAddress}, - HealthProbeBindAddress: o.healthAddress, - LeaderElection: true, - LeaderElectionID: o.leaseName, - LeaderElectionNamespace: o.namespace, - LeaderElectionReleaseOnCancel: true, + restConfig := ctrl.GetConfigOrDie() + // The election identity is this process's own, "_", so the + // limiter can recognise the Lease as its own and no later process + // reuses it. + holder := o.podName + "_" + string(uuid.NewUUID()) + kc, err := kubernetes.NewForConfig(restConfig) + if err != nil { + return fmt.Errorf("kubernetes client: %w", err) + } + lock, err := resourcelock.New(resourcelock.LeasesResourceLock, o.namespace, o.leaseName, kc.CoreV1(), + kc.CoordinationV1(), resourcelock.ResourceLockConfig{Identity: holder}) + if err != nil { + return fmt.Errorf("election lock: %w", err) + } + mgr, err := ctrl.NewManager(restConfig, ctrl.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: o.metricsAddress}, + HealthProbeBindAddress: o.healthAddress, + LeaderElection: true, + LeaderElectionID: o.leaseName, + LeaderElectionNamespace: o.namespace, + LeaderElectionReleaseOnCancel: true, + LeaderElectionResourceLockInterface: lock, // Pods are cached only in the fabric-router namespace; FabricQuery // is cached cluster-wide since NSO writes it into each project's // mapped namespace. @@ -156,6 +180,22 @@ func runGateway(parent context.Context, o *gatewayOptions) error { } executor := gateway.NewExecutor(o.slots, o.expensiveSlots, o.queue) + var admission *gateway.Admission + if o.aggregateBudgets { + limits := limit.Defaults() + limits.Slots, limits.Queue = o.slots, o.queue + // A smaller cell lowers each principal's share with it. + limits.PrincipalSlots = min(limits.PrincipalSlots, o.slots) + limits.PrincipalQueue = min(limits.PrincipalQueue, o.queue) + admission, err = gateway.NewAdmission(limits, &limit.Authority{ + Reader: mgr.GetAPIReader(), Namespace: o.namespace, Name: o.leaseName, Identity: holder, + }) + if err != nil { + return fmt.Errorf("--aggregate-budgets: %w", err) + } + executor.PrincipalSlots, executor.PrincipalQueue = limits.PrincipalSlots, limits.PrincipalQueue + go admission.Authority.Watch(ctx, limit.WatchInterval) + } metrics := gateway.NewMetrics(ctrlmetrics.Registry, func() float64 { return float64(executor.Depth()) }) executor.ObserveWait = func(d time.Duration) { metrics.QueueWait(d.Seconds()) } creds := o.tls.credentials(identity.Gateway(o.cell)) @@ -191,7 +231,7 @@ func runGateway(parent context.Context, o *gatewayOptions) error { discoverer := &gateway.Discoverer{ Reader: mgr.GetClient(), Namespace: o.namespace, Selector: sel, CertsSelector: certsSel, } - runner := &gateway.Runner{Clients: pool, Executor: executor, Metrics: metrics} + runner := &gateway.Runner{Clients: pool, Executor: executor, Metrics: metrics, Admission: admission} rec := &gateway.Reconciler{ Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), @@ -241,10 +281,14 @@ func runGateway(parent context.Context, o *gatewayOptions) error { Discoverer: &gateway.Discoverer{ Reader: mgr.GetAPIReader(), Namespace: o.namespace, Selector: sel, CertsSelector: certsSel, }, - Runner: runner, - Revision: metadata.GitCommit, + Runner: runner, + Admission: admission, + Revision: metadata.GitCommit, + } + permits := &gateway.Permits{ + Admission: admission, Executor: executor, Discoverer: discoverer, Elected: debug.Elected, Leader: debug, } - gs := gateway.NewServer(creds, allowlist, debug, service, grpc.MaxRecvMsgSize(64<<10), serverStats()) + gs := gateway.NewServer(creds, allowlist, debug, service, permits, grpc.MaxRecvMsgSize(64<<10), serverStats()) debugAddr := fmt.Sprintf(":%d", o.debugPort) if o.podIP != "" { debugAddr = net.JoinHostPort(o.podIP, strconv.Itoa(o.debugPort)) diff --git a/cmd/fabric-api/node.go b/cmd/fabric-api/node.go index 4d7872531..6150e9cff 100644 --- a/cmd/fabric-api/node.go +++ b/cmd/fabric-api/node.go @@ -22,7 +22,10 @@ import ( grpchealth "google.golang.org/grpc/health" "google.golang.org/grpc/health/grpc_health_v1" "google.golang.org/grpc/keepalive" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + permitv1 "go.datum.net/galactic/api/fabric/permit/v1" fabricv1 "go.datum.net/galactic/api/fabric/v1" "go.datum.net/galactic/internal/fabric/frr" "go.datum.net/galactic/internal/fabric/identity" @@ -72,6 +75,8 @@ type nodeOptions struct { breakerCooldown time.Duration searchSource, bmpAddress string indexMaxRoutes int + probePermits, requirePermits bool + gatewayAddress, gatewayLease string } func newNodeCommand() *cobra.Command { @@ -121,6 +126,15 @@ func newNodeCommand() *cobra.Command { f.IntVar(&o.indexMaxRoutes, "search-index-max-routes", 4_000_000, "Prefixes the search index holds at most") f.DurationVar(&o.breakerCooldown, "expensive-breaker-cooldown", node.DefaultBreakerCooldown, "How long expensive searches stay suspended after one times out") + f.BoolVar(&o.probePermits, "probe-permits", false, + "Verify and enforce the cell gateway's probe permits, reading its election lease from the API (needs a "+ + "service account token that may get --gateway-lease-name in --namespace)") + f.BoolVar(&o.requirePermits, "require-probe-permits", false, + "With --probe-permits, refuse a probe without a permit; a direct operator's probe obtains one from "+ + "--gateway-address") + f.StringVar(&o.gatewayAddress, "gateway-address", "", + "host:port of the cell gateway's gRPC service, from which direct operator probes obtain permits") + f.StringVar(&o.gatewayLease, "gateway-lease-name", "fabric-api-gateway", "The cell gateway's election lease name") return cmd } @@ -185,6 +199,10 @@ func runNode(parent context.Context, o *nodeOptions) error { return fmt.Errorf("--search-source must be index or frr, not %q", o.searchSource) } + permits, err := nodePermits(o, creds) + if err != nil { + return err + } srv, err := node.NewServer(node.Config{ NodeName: o.nodeName, Site: o.site, @@ -200,6 +218,7 @@ func runNode(parent context.Context, o *nodeOptions) error { PacketRate: o.packetRate, BreakerCooldown: o.breakerCooldown, Index: ix, + Permits: permits, Credentials: creds, Metrics: metrics, }) @@ -253,6 +272,42 @@ func runNode(parent context.Context, o *nodeOptions) error { } } +// nodePermits returns the probe permit checker the flags select, or nil +// without --probe-permits. +func nodePermits(o *nodeOptions, creds *identity.Credentials) (*node.Permits, error) { + switch { + case !o.probePermits && (o.requirePermits || o.gatewayAddress != ""): + return nil, errors.New("--require-probe-permits and --gateway-address need --probe-permits") + case !o.probePermits: + return nil, nil + case o.requirePermits && o.gatewayAddress == "": + return nil, errors.New("--require-probe-permits needs --gateway-address for direct operator probes") + } + cfg, err := ctrl.GetConfig() + if err != nil { + return nil, fmt.Errorf("--probe-permits: %w", err) + } + reader, err := client.New(cfg, client.Options{}) + if err != nil { + return nil, fmt.Errorf("--probe-permits: %w", err) + } + p := &node.Permits{ + Reader: reader, Namespace: o.namespace, LeaseName: o.gatewayLease, Require: o.requirePermits, + Started: time.Now(), + } + if o.gatewayAddress != "" { + conn, err := grpc.NewClient(o.gatewayAddress, + grpc.WithTransportCredentials(credentials.NewTLS(creds.ClientConfig(identity.Gateway(o.cell)))), + // A permit request charges budgets; it is never replayed. + grpc.WithDisableRetry()) + if err != nil { + return nil, fmt.Errorf("--gateway-address: %w", err) + } + p.Gateway = permitv1.NewPermitServiceClient(conn) + } + return p, nil +} + // idleUnconfigured serves only metrics, reporting diagnostics unavailable, // until the process is signalled. func idleUnconfigured(parent context.Context, hostIP netip.Addr, o *nodeOptions) error { diff --git a/docs/agents/ARCHITECTURE-FABRIC-API.md b/docs/agents/ARCHITECTURE-FABRIC-API.md index 1eef4647e..9a08dafaa 100644 --- a/docs/agents/ARCHITECTURE-FABRIC-API.md +++ b/docs/agents/ARCHITECTURE-FABRIC-API.md @@ -108,6 +108,8 @@ api/fabric/service/v1/ service.proto LookingGlassService, the customer service's contract api/fabric/forward/v1/ forward.proto ForwardService, gateway-only follower-to-leader forwarding +api/fabric/permit/v1/ + permit.proto PermitService, node-only probe permits for direct operator probes internal/fabric/ api/v1alpha1/ FabricQuery types, deepcopy, CRD envtest @@ -118,7 +120,8 @@ internal/fabric/ identity/ URI SAN identities, reloading mTLS credentials, certificate sync errcode/ Typed error codes carried as gRPC ErrorInfo node/ FabricService implementation (the sidecar's logic) - gateway/ Reconciler, Runner, Executor, Pool, Discoverer, Debug, Service, Janitor + gateway/ Reconciler, Runner, Executor, Pool, Discoverer, Debug, Service, Admission, Permits, Janitor + gateway/limit/ Aggregate token buckets, attempt keys, election authority and limits testpki/ Throwaway CA for tests config/fabric-api/ @@ -209,7 +212,7 @@ federation, for diagnosing a cell directly: --gateway host:9346 │ any replica; a follower forwards Query to the │ leader named by the election lease's holder ▼ - Debug.Query ─► Runner (project key "operator/") + Debug.Query ─► Runner (project key "operator/"; FabricQuery "fabricquery//") │ nodes see the *gateway* identity, so the ▼ public destination policy applies node sidecars @@ -293,13 +296,19 @@ With a cell set, `runNode`: `Info.diagnostics_available` is true, and is wired to no pod probe. 6. Serves `/metrics` on `:9345` unless `--metrics-bind-address` is set. +With `--probe-permits`, step 3 also gives the server a `node.Permits`, which +reads the gateway's election Lease through an uncached client built from the +pod's service account, and with `--gateway-address` a `PermitService` client +for direct operator probes. + Shutdown is a graceful gRPC stop with a 10 s limit. ### `cmd/fabric-api/gateway.go` — `fabric-api gateway` The cell executor. It requires `--site`, `--cluster-name`, `--cell` and `--pod-name`. It builds a controller-runtime manager with leader election -(lease `fabric-api-gateway` in the pods' namespace, released on cancel), caches +(lease `fabric-api-gateway` in the pods' namespace, released on cancel, held +through its own resource lock under the identity `_`), caches `Pod`s only in the `fabric-router` namespace and `FabricQuery` cluster-wide, and registers: @@ -313,11 +322,16 @@ registers: (`gateway.Debug`), the Looking Glass service (`gateway.Service`) and the gateway-only forwarding service, authorized per role from `gateway.GatewayMethods` by a `node.Authorizer` that re-verifies the caller's - certificate on every unary and streaming call. The service takes each - request's router inventory with an uncached pod list and runs through the - shared `Runner` and executor, but its `Enabled` field is not set, so the - leader refuses valid requests with `ServiceDisabled`; no flag turns - execution on. + certificate on every unary and streaming call, and the node-only permit + service (`gateway.Permits`). The service takes each request's router + inventory with an uncached pod list and runs through the shared `Runner` and + executor, but its `Enabled` field is not set, so the leader refuses valid + requests with `ServiceDisabled`; no flag turns execution on. + +With `--aggregate-budgets` it also builds a `gateway.Admission` under a +`limit.Authority` for that holder identity, gives it to the runner, the +service and the permit service, bounds each principal's share of the executor, +and starts `Authority.Watch`, which reads the Lease every second. Metrics are registered on controller-runtime's registry and served on `:9347` along with its own; `/healthz` and `/readyz` are plain pings on `:8081`. @@ -391,7 +405,9 @@ The Component also adds the `fabric-api-certs` DaemonSet (see The Component sets `automountServiceAccountToken: false` on the pod and adds a projected token volume mounted only into `frr-init` and `config-agent`, the two containers that call the Kubernetes API. The `fabric-api` sidecar needs no API -access and gets no token. +access and gets no token, unless it runs with `--probe-permits`, which no +manifest sets yet (see +[Aggregate probe budgets](../fabric-api/configuration.md#aggregate-probe-budgets)). --- @@ -403,6 +419,7 @@ access and gets no token. | `api/fabric/v1` | `FabricService` and `FabricGatewayService` contract: `Execute`, `Info`, `Query`, `ListNodes`; observations, budgets | No | | `api/fabric/service/v1` | `LookingGlassService` contract: `GetCapabilities` (policy, features, limits), `RunDiagnostic` and its snapshot, outcome and complete events; `testdata/` holds the wire examples | No | | `api/fabric/forward/v1` | `ForwardService.ForwardDiagnostic`: the gateway-only envelope a follower forwards to the leader | No | +| `api/fabric/permit/v1` | `PermitService.RequestPermit`/`ReleasePermit`: a node obtains a probe permit for a direct operator's probe | No | | `internal/fabric/query` | `Canonicalize` (target rules, family inference, AS-path grammar, community forms), `DestinationPolicy`, `Budgets`/`Ceilings`, probe limits. Imports nothing from the rest of galactic | No | | `internal/fabric/frr` (`command.go`) | Closed command builder: `VersionCommand`, `SummaryCommand`, `LookupCommand`, `SearchCommand`, `RouteCommand`. `Command` fields are unexported, so there is no free-text path | No | | `internal/fabric/frr` (`vty.go`) | Unix-socket client: `cmd\0` out, read to `\0\0\0`, per-command connection, byte cap, deadline handling | No | @@ -416,10 +433,14 @@ access and gets no token. | `internal/fabric/node` (`server.go`) | `Execute` pipeline, `Info`, FRR identity refresh, expensive-query breaker, probe policy and budgets | Semaphores, limiter, breaker, last-read FRR state | | `internal/fabric/node` (`dedup.go`) | Duplicate-suppression cache keyed by `(requestID, node, operation)`, bounded in entries and bytes | In-memory cache | | `internal/fabric/node` (`shape.go`) | Per-node shaping: path and community caps, response fit | No | +| `internal/fabric/node` (`permit.go`) | `Permits`: verifies and consumes each probe permit once (node, request, destination, operation, deadline, Lease epoch), refuses all for 32 s after start, obtains and releases permits for direct operator probes | Consumed permit IDs (memory) | | `internal/fabric/node` (`auth.go`) | `Authorizer` (unary and stream) and `AuthInterceptor`: identity from the handshake, optional per-call re-verification capped at certificate expiry, per-role method table, call logging | No | | `internal/fabric/gateway` (`reconciler.go`) | `FabricQuery` lifecycle: validation, snapshot, start marker, terminal status, conditions, coverage, shrink to budget | In-flight executions (memory) | | `internal/fabric/gateway` (`runner.go`) | `Pool` (one mTLS connection per sidecar, pinned to its certs pod's identity), `Runner` fan-out, per-node deadline, cheap-read retry; `Runner.Stream` hands each outcome off as its node finishes, with no retry and a queue bound (`QueueTimeout`) | Connections | -| `internal/fabric/gateway` (`executor.go`) | Cell-wide slots with an expensive sub-budget and per-project round-robin queue | Queue state | +| `internal/fabric/gateway` (`executor.go`) | Cell-wide slots with an expensive sub-budget and per-principal round-robin queue; optional per-principal slot and queue caps; all-or-nothing `Reserve` of a request's jobs | Queue state | +| `internal/fabric/gateway` (`admission.go`) | `Admission`: request tokens, attempt keys, live stream caps and probe permits charged to the packet buckets, under the election `Authority`; slot hold after a lost node answer | Stream counts (memory) | +| `internal/fabric/gateway` (`permit.go`) | `Permits`: the node-only permit service; maps the node identity's certs pod to its node, holds the operator's slot until release or deadline plus 2 s, forwards once to the leader | Held permits (memory) | +| `internal/fabric/gateway/limit` | `Limits` and `Validate`; `Buckets` (request and packet token buckets, never negative, key families bounded without evicting debt); `Attempts` (duplicate attempt keys, fail closed); `Authority` (uncached Lease check, epoch, 125 s recovery hold, `Watch`) | Buckets, attempt keys, epoch (memory) | | `internal/fabric/gateway` (`discovery.go`) | Pod snapshot with omission reasons, one pod per node, node budget, node-to-certs-pod mapping (`NoCertificatePod`); `Inventory`, the service's one-router-per-node snapshot (newest usable pod, `NotRequested`, `NoSidecar`, unscheduled count, 256-router cap) | No | | `internal/fabric/gateway` (`debug.go`) | Operator debug service, leader forwarding through the election lease | Connection to the leader | | `internal/fabric/gateway` (`service.go`) | `NewServer`, service `Allowlist`, Looking Glass service authorization and attribution validation, one-hop typed forwarding to the leader, capabilities, and (when `Enabled`) streamed execution with terminal coverage | No | @@ -790,7 +811,9 @@ with the Component but its restart does not touch FRR. | Typed error codes and their gRPC mapping | `internal/fabric/errcode/errcode.go` | | FabricQuery lifecycle, conditions, coverage | `internal/fabric/gateway/reconciler.go:Reconcile`, `terminalStatus`, `persist` | | Fan-out, deadlines, retries | `internal/fabric/gateway/runner.go:Runner.Run`, `one` | -| Cell concurrency and fairness | `internal/fabric/gateway/executor.go:Executor.Acquire` | +| Cell concurrency and fairness | `internal/fabric/gateway/executor.go:Executor.Acquire`, `Reserve` | +| Aggregate admission and probe budgets | `internal/fabric/gateway/service.go:Service.execute`, `admission.go:Admission.permit`, `limit/` | +| Probe permits on the node | `internal/fabric/node/permit.go:Permits.consume`, `server.go:probeGrant` | | Node snapshot and omission reasons | `internal/fabric/gateway/discovery.go:Discoverer.Snapshot`, `omitReason` | | Operator debug service and leader forwarding | `internal/fabric/gateway/debug.go:Debug.Query`, `forward`, `leaderAddress` | | Cleanup | `internal/fabric/gateway/janitor.go:Janitor.Sweep`, `StaleCounter` | diff --git a/docs/fabric-api/api.md b/docs/fabric-api/api.md index 08674e2c8..2f46acfe7 100644 --- a/docs/fabric-api/api.md +++ b/docs/fabric-api/api.md @@ -374,26 +374,29 @@ Codes appear in `observations[].errorCode` and `installation.errorCode`, in `fabric-api.datumapis.com`. Over gRPC every failure is a status; success is an `Observation`. -| Code | gRPC status | Meaning | -| ------------------------ | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `FRRUnavailable` | `Unavailable` | The daemon's vty socket could not be reached | -| `FRRVersionUnsupported` | `FailedPrecondition` | The running FRR is not a release the parsers have fixtures for (only 10.7) | -| `CommandFailed` | `FailedPrecondition` | FRR rejected or failed the command, including a regular expression FRR cannot compile | -| `ResponseTooLarge` | `ResourceExhausted` | FRR's response exceeded 4 MiB, or the result did not fit the budget even when shaped | -| `MalformedResponse` | `Internal` | FRR's response was incomplete or not the expected JSON | -| `Timeout` | `DeadlineExceeded` | The deadline passed: waiting for a slot, reading FRR, or a node not answering in time | -| `ProbeSourceUnavailable` | `FailedPrecondition` | No probe source for the family, or the source address could not be bound | -| `ProbeFailed` | `Internal` | The probe socket failed while probing | -| `DestinationNotAllowed` | `InvalidArgument` | The probe destination is refused by the caller's destination policy | -| `InvalidQuery` | `InvalidArgument` | Any other validation failure; the specific validation code is in `ErrorInfo` metadata (`queryCode`) and at the start of the message | -| `QueryTypeUnavailable` | `FailedPrecondition` | The type is not enabled on the node (expensive types by default), the search index is not synced with bgpd, or (`--search-source=frr`) the expensive-query breaker is open | -| `NodeBusy` | `ResourceExhausted` | The node's expensive-search or probe budget is full, a node execution slot did not free in time, or the cell queue is full | -| `DuplicateConflict` | `AlreadyExists` | A request ID was reused with different arguments | -| `Expired` | `DeadlineExceeded` | The request's absolute expiration has passed | -| `WrongNode` | `FailedPrecondition` | The request named another node | -| `Unauthorized` | `PermissionDenied` | The caller's identity may not make this call | -| `NodeUnreachable` | `Unknown` (by reason) | The gateway could not reach the node, or no leader is elected for a forwarded debug call | -| `Internal` | `Internal` | An unexpected failure | +| Code | gRPC status | Meaning | +| ------------------------ | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `FRRUnavailable` | `Unavailable` | The daemon's vty socket could not be reached | +| `FRRVersionUnsupported` | `FailedPrecondition` | The running FRR is not a release the parsers have fixtures for (only 10.7) | +| `CommandFailed` | `FailedPrecondition` | FRR rejected or failed the command, including a regular expression FRR cannot compile | +| `ResponseTooLarge` | `ResourceExhausted` | FRR's response exceeded 4 MiB, or the result did not fit the budget even when shaped | +| `MalformedResponse` | `Internal` | FRR's response was incomplete or not the expected JSON | +| `Timeout` | `DeadlineExceeded` | The deadline passed: waiting for a slot, reading FRR, or a node not answering in time | +| `ProbeSourceUnavailable` | `FailedPrecondition` | No probe source for the family, or the source address could not be bound | +| `ProbeFailed` | `Internal` | The probe socket failed while probing | +| `DestinationNotAllowed` | `InvalidArgument` | The probe destination is refused by the caller's destination policy | +| `InvalidQuery` | `InvalidArgument` | Any other validation failure; the specific validation code is in `ErrorInfo` metadata (`queryCode`) and at the start of the message | +| `QueryTypeUnavailable` | `FailedPrecondition` | The type is not enabled on the node (expensive types by default), the search index is not synced with bgpd, (`--search-source=frr`) the expensive-query breaker is open, or a probe went to a node that does not enforce probe permits while the gateway enforces aggregate budgets | +| `NodeBusy` | `ResourceExhausted` | The node's expensive-search or probe budget is full, a node execution slot did not free in time, or the cell queue is full | +| `DuplicateConflict` | `AlreadyExists` | A request ID was reused with different arguments | +| `Expired` | `DeadlineExceeded` | The request's absolute expiration has passed | +| `WrongNode` | `FailedPrecondition` | The request named another node | +| `Unauthorized` | `PermissionDenied` | The caller's identity may not make this call | +| `NodeUnreachable` | `Unknown` (by reason) | The gateway could not reach the node, or no leader is elected for a forwarded debug call | +| `Internal` | `Internal` | An unexpected failure | +| `Throttled` | `ResourceExhausted` | A probe's worst-case packets did not fit the cell's, the source's or the destination's packet budget; the status carries `RetryInfo`. Only with the gateway's `--aggregate-budgets` | +| `LimiterUnavailable` | `Unavailable` | The gateway is in its 125 s recovery hold or its limiter is full, or a node could not verify the probe's permit. Only with aggregate budgets | +| `OwnershipLost` | `Unavailable` | The gateway could not confirm it holds the election before dispatching a probe. Only with aggregate budgets | Omitted nodes carry no error code: they are reported through `status.nodes[].omittedReason` and `coverage`. A gRPC error diff --git a/docs/fabric-api/configuration.md b/docs/fabric-api/configuration.md index e0538d284..d69eafd85 100644 --- a/docs/fabric-api/configuration.md +++ b/docs/fabric-api/configuration.md @@ -302,6 +302,11 @@ How an identity is checked: debug service an operator may call `Query` and `ListNodes`, and the gateway identity may call only `Query` (the form in which a follower forwards to the leader). Anything else is `Unauthorized`. +- The gateway also accepts node identities, which may call only its + `RequestPermit` and `ReleasePermit` (and the gateway identity, forwarding + them to the leader). The handler further requires the node identity's + namespace to be the gateway's `--namespace` and its pod to be a + `fabric-api-certs` pod on the node the call names. - The gateway also accepts a service identity whose name is in `--service-identities`. A service may call only the Looking Glass service's `GetCapabilities` and `RunDiagnostic`, never `Query`, `ListNodes` or a node. @@ -383,7 +388,9 @@ service presents the certificate on its gRPC connection to the gateway's renews them; the gateway accepts the overlapping-bundle rotation below. The service contract is [service-contract.md](service-contract.md). The gateway does not execute service diagnostics: it answers a valid `RunDiagnostic` -with `ServiceDisabled`, and `GetCapabilities` reports `enabled: false`. +with `ServiceDisabled`, and `GetCapabilities` reports `enabled: false`. With +`--aggregate-budgets`, `GetCapabilities` also lists `aggregate-probe-budgets` +and the cell's admission limits. ### Rotation @@ -469,6 +476,10 @@ variables then apply. Trace-context propagation is always on. | `--search-source` | | `index` | What answers AS-path and community searches: `index` (a local copy of bgpd's Loc-RIB fed over BMP) or `frr` (FRR's own scans, which starve bgpd on full tables) | | `--bmp-station-address` | | `127.0.0.1:9348` | Loopback address the BMP station listens on, with `--search-source=index` | | `--search-index-max-routes` | | `4000000` | Prefixes the index holds at most; announcements for new prefixes beyond it are dropped and counted | +| `--probe-permits` | | `false` | Verify and enforce the gateway's probe permits, and report `probePermits` in `Info`. Needs API access; see [Aggregate probe budgets](#aggregate-probe-budgets) | +| `--require-probe-permits` | | `false` | With `--probe-permits`, refuse any probe without a permit; a direct operator's probe first obtains one from `--gateway-address` | +| `--gateway-address` | | | `host:port` of the cell gateway's gRPC service, from which direct operator probes obtain permits. Required by `--require-probe-permits` | +| `--gateway-lease-name` | | `fabric-api-gateway` | The gateway's election lease, read uncached in `--namespace` to verify each permit's epoch | Not configurable by flag: the 4 MiB FRR read cap, the 2 second socket dial timeout, the duplicate-suppression cache (1024 entries or 32 MiB), the 60 second @@ -485,31 +496,32 @@ FRR, so it follows [Rollout](#rollout). ### `fabric-api gateway` -| Flag | Env | Default | Meaning | -| ------------------------------------- | ------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--site` | `SITE` | | Site this cell serves. Required | -| `--cluster-name` | `CLUSTER_NAME` | | This cell's Karmada member cluster name. Required | -| `--cell` | `CELL` | | Cell name in the mTLS identities. Required | -| `--namespace` | `POD_NAMESPACE` | `galactic-system` | Namespace of the `fabric-router` pods, the election lease and this pod | -| `--pod-name` | `POD_NAME` | | This pod's name. Required | -| `--debug-bind-address` | | | Address the debug service binds to. Empty binds every address in the pod's network namespace, which a port-forward (through the pod's loopback) and the Service both need | -| `--pod-selector` | | `app.kubernetes.io/name=fabric-router` | Label selector of `fabric-router` pods | -| `--certs-selector` | | `app.kubernetes.io/name=fabric-api-certs` | Label selector of the per-node `fabric-api-certs` pods whose identity each sidecar presents | -| `--lease-name` | | `fabric-api-gateway` | Leader election lease name | -| `--debug-port` | | `9346` | Operator debug gRPC port | -| `--metrics-bind-address` | | `:9347` | Address serving `/metrics` | -| `--health-probe-bind-address` | | `:8081` | Address serving `/healthz` and `/readyz` | -| `--tls-cert`, `--tls-key`, `--tls-ca` | `FABRIC_API_TLS_CERT`, `_KEY`, `_CA` | `/var/run/fabric-api/tls/tls.crt`, `tls.key`, `ca.crt` | As for the node | -| `--cell-slots` | | `8` | Node RPCs running at once across all queries | -| `--cell-expensive-slots` | | `2` | Of those, expensive searches | -| `--cell-queue` | | `256` | Node RPCs that may wait for a slot | -| `--max-nodes` | | `32` | Nodes one query executes on in this cell (ceiling 32) | -| `--max-object-bytes` | | `393216` (384 KiB) | Serialized `FabricQuery` size ceiling (ceiling 384 KiB) | -| `--max-node-response-bytes` | | `131072` (128 KiB) | Node response ceiling (ceiling 128 KiB) | -| `--max-in-flight` | | `256` | Queries executing at once; more wait for a requeue | -| `--retention` | | `1h` | Retention the stale-object count assumes; keep equal to the janitor's `--retention` | -| `--cleanup-grace` | | `15m` | Cleanup grace the stale-object count assumes; keep equal to the janitor's `--grace` | -| `--service-identities` | | | Comma-separated names of the Looking Glass service identities allowed to call this gateway. Empty allows none | +| Flag | Env | Default | Meaning | +| ------------------------------------- | ------------------------------------ | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--site` | `SITE` | | Site this cell serves. Required | +| `--cluster-name` | `CLUSTER_NAME` | | This cell's Karmada member cluster name. Required | +| `--cell` | `CELL` | | Cell name in the mTLS identities. Required | +| `--namespace` | `POD_NAMESPACE` | `galactic-system` | Namespace of the `fabric-router` pods, the election lease and this pod | +| `--pod-name` | `POD_NAME` | | This pod's name. Required | +| `--debug-bind-address` | | | Address the debug service binds to. Empty binds every address in the pod's network namespace, which a port-forward (through the pod's loopback) and the Service both need | +| `--pod-selector` | | `app.kubernetes.io/name=fabric-router` | Label selector of `fabric-router` pods | +| `--certs-selector` | | `app.kubernetes.io/name=fabric-api-certs` | Label selector of the per-node `fabric-api-certs` pods whose identity each sidecar presents | +| `--lease-name` | | `fabric-api-gateway` | Leader election lease name | +| `--debug-port` | | `9346` | Operator debug gRPC port | +| `--metrics-bind-address` | | `:9347` | Address serving `/metrics` | +| `--health-probe-bind-address` | | `:8081` | Address serving `/healthz` and `/readyz` | +| `--tls-cert`, `--tls-key`, `--tls-ca` | `FABRIC_API_TLS_CERT`, `_KEY`, `_CA` | `/var/run/fabric-api/tls/tls.crt`, `tls.key`, `ca.crt` | As for the node | +| `--cell-slots` | | `8` | Node RPCs running at once across all queries | +| `--cell-expensive-slots` | | `2` | Of those, expensive searches | +| `--cell-queue` | | `256` | Node RPCs that may wait for a slot | +| `--max-nodes` | | `32` | Nodes one query executes on in this cell (ceiling 32) | +| `--max-object-bytes` | | `393216` (384 KiB) | Serialized `FabricQuery` size ceiling (ceiling 384 KiB) | +| `--max-node-response-bytes` | | `131072` (128 KiB) | Node response ceiling (ceiling 128 KiB) | +| `--max-in-flight` | | `256` | Queries executing at once; more wait for a requeue | +| `--retention` | | `1h` | Retention the stale-object count assumes; keep equal to the janitor's `--retention` | +| `--cleanup-grace` | | `15m` | Cleanup grace the stale-object count assumes; keep equal to the janitor's `--grace` | +| `--service-identities` | | | Comma-separated names of the Looking Glass service identities allowed to call this gateway. Empty allows none | +| `--aggregate-budgets` | | `false` | Enforce the cell's aggregate admission and probe packet budgets on every caller and issue probe permits. Requires `--cell-slots` at most 8; a principal's share is 2 slots and 32 queued jobs, lowered to `--cell-slots` and `--cell-queue` when those are smaller. See [Aggregate probe budgets](#aggregate-probe-budgets) | `--max-nodes`, `--max-object-bytes` and `--max-node-response-bytes` can only lower their ceilings: zero or a value above the ceiling selects the ceiling. The @@ -717,6 +729,90 @@ node response ceiling and no less than 1 KiB. A result that still does not fit w the gateway assembles it is shrunk, the largest observation first, and marked truncated. +## Aggregate probe budgets + +Without `--aggregate-budgets` the cell executor above and each node's packet +pacer are the only limits, and they are local: nothing bounds how many probe +packets the cell as a whole sends to one destination. With it, the leader +gateway holds every budget of the +[service contract](service-contract.md#admission-execution-and-aggregate-accounting) +in memory and charges every probe, whoever asked for it: + +| Budget | Default | Charged to | When exhausted | +| -------------------------------------- | -------------------------- | ------------------------------------------------------------------- | ---------------------------------- | +| Service requests, cell / project | 2/s burst 8, 0.2/s burst 2 | Each `RunDiagnostic` | `Throttled` with `RetryInfo` | +| Probe packets, cell | 100/s burst 640 | Every probe's worst case: ping 3, traceroute 20 | The router's job fails `Throttled` | +| Probe packets, principal | 20/s burst 640 | Per service project, `FabricQuery` source or operator | As above | +| Probe packets, destination host/prefix | 20/s and 40/s, burst 640 | The destination's /32 or /128, and its /24 or /64 | As above | +| Node jobs at once, per principal | 2 | Every node call | Queued | +| Queued node jobs, per principal | 32 | Every node call; a service request reserves all its routers at once | `QueueFull` | +| Live service streams, cell / project | 16 / 2 | Each `RunDiagnostic` | `QueueFull` | + +Principals are the service request's project, a `FabricQuery`'s +`fabricquery//`, and `operator/` for an operator. A probe an +operator sends a node directly is charged to the operator only on a node that +runs both `--probe-permits` and `--require-probe-permits`. Nothing +charged is refunded. Reads (route lookups, BGP summaries) take a node slot but +no packets. The leader confirms it holds the election Lease, reading it uncached, +before every admission and probe, and once a second besides. After it starts, +acquires the election or fails to read the Lease it admits no probe and no +service request for 125 seconds, then starts every bucket empty. A gateway +restart or failover therefore stops operator and `FabricQuery` probes for about +two minutes; reads are unaffected. + +Each probe carries a permit, bound to the Lease's epoch, its node, request, +destination and worst-case packets and a deadline at most 30 seconds away. A +node with `--probe-permits` consumes each permit once, re-reads the Lease to +confirm the epoch, and sends nothing past the permit's packets or deadline. It +refuses every permit for 32 seconds after it starts. The gateway sends a probe +only to a node whose `Info` reports `probePermits`; any other node's job fails +`QueryTypeUnavailable`. With `--require-probe-permits`, a node also refuses a +probe without a permit, and a probe an operator sends it directly first obtains +one from the gateway's `RequestPermit`, charged to that operator. + +When a probe's node call ends without the node's answer, its slot stays held +until the job's deadline plus 2 seconds, since the node may still be sending +it. The rates and caps are the contract's defaults; only `--cell-slots` and +`--cell-queue` change them. + +### Enabling + +The deployment manifests do not set these flags yet. Turn them on in this +order, each step cell by cell: + +1. **Nodes verify permits.** Give the `fabric-router` ServiceAccount `get` on + the gateway's Lease and mount its token into the `fabric-api` container (the + Component mounts it only into `frr-init` and `config-agent`): + + ```yaml + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: fabric-api-node-lease + namespace: galactic-system + rules: + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + resourceNames: ["fabric-api-gateway"] + verbs: ["get"] + ``` + + Bind it to the `fabric-router` ServiceAccount and add `--probe-permits` to + the sidecar's args. This changes the pod template, so it is a routing + rollout: follow [Rollout](#rollout). +2. **The gateway enforces budgets.** Add `--aggregate-budgets` to the gateway. + Expect operator and `FabricQuery` probes to be refused for 125 seconds after + each gateway restart. +3. **Nodes require permits.** Until this step, probes operators send nodes + directly are not charged, and the Looking Glass service must not be + enabled. Add `--require-probe-permits` and + `--gateway-address=fabric-api-gateway.galactic-system.svc:9346` (the gateway + Service) to the sidecar, so direct operator probes are charged too. Another + routing rollout. + +Roll back in the reverse order. Removing `--aggregate-budgets` while nodes still +require permits refuses every gateway probe (`LimiterUnavailable`). + ## Probe sources and destinations ### Source diff --git a/docs/fabric-api/service-contract.md b/docs/fabric-api/service-contract.md index 7ea06c03a..337272ceb 100644 --- a/docs/fabric-api/service-contract.md +++ b/docs/fabric-api/service-contract.md @@ -32,15 +32,18 @@ authenticates service identities and validates their requests (#1043). With `gateway.Service.Enabled` set, the leader streams a request as specified under "Stream grammar and coverage": `Discoverer.Inventory` takes the unique-router snapshot, `Runner.Stream` hands off each router's outcome as it finishes, and -the terminal coverage follows (#1044). No deployment sets `Enabled`, so a valid -`RunDiagnostic` is answered with `ServiceDisabled`, and capabilities do not -advertise `aggregate-probe-budgets`. Not yet implemented: admission and packet -budgets with the atomic queue reservation before the snapshot (#1045), and the -blocked-send bound and Lease-checked ownership (#1046). Until then each router -job queues on its own and a full queue fails that router with `NodeBusy`. -The executor has local concurrency/queue limits and project round robin; nodes -pace packets locally. None establishes the aggregate guarantees. Operator and -FabricQuery discovery still return pod candidates, including duplicates. +the terminal coverage follows (#1044). With the gateway's `--aggregate-budgets`, +the leader enforces "Admission, execution, and aggregate accounting" below +(`internal/fabric/gateway/limit`, `gateway.Admission`, `gateway.Permits`), and +nodes run with `--probe-permits` verify each probe's permit (#1045). Execution +requires the gateway's admission, and capabilities advertise +`aggregate-probe-budgets` only while execution is enabled with it. Nodes +charge direct operator probes only with `--require-probe-permits`, so enabling +execution requires every node to run with it. No deployment sets `Enabled` or +these flags, so a valid `RunDiagnostic` is answered with `ServiceDisabled`. Not yet implemented: the blocked-send bound and +stream-level ownership rules of #1046, and the metrics and packaged +configuration of #1047. Operator and FabricQuery discovery still return pod +candidates, including duplicates. ## Service and identity @@ -92,8 +95,10 @@ The initial feature names are `router-outcomes`, `terminal-coverage`, and `aggregate-probe-budgets`; all three are required to advertise an enabled v1 service. `contract_revision` is the implementing release commit SHA and `policy_revision` is the digest of effective service policy and limits. -It does not probe routers or reserve diagnostic capacity. Cache for at most -30 s. Capabilities advertise policy, not current router availability. Validate +`limits.admission` reports the cell's admission and packet budgets, present +only with `aggregate-probe-budgets`. A router failure refused by a limit +carries the same `scope` and `retry_delay` as a refused request. It does not probe routers or reserve +diagnostic capacity. Cache for at most 30 s. Capabilities advertise policy, not current router availability. Validate again on execution; policy changes may reject a previously advertised request. `RunDiagnosticRequest` fields: @@ -326,16 +331,19 @@ identities. Never use the common service account as the fairness key. After snapshot construction, admit all selected node jobs to the bounded shared executor atomically or refuse the request. Charge one node-job unit per selected router; omitted routers cost no node execution or packets. Maintain FIFO within -a project and round robin between project queues. Retain separate operator -principal queues and FabricQuery's trusted project queues; a FabricQuery and a -service request for the same project use the same fairness key. A project may -hold at most two node slots; direct operator principals have the same cap. +a principal and round robin between principal queues. A service request's +principal is its project UID, an operator's its identity name, and a +FabricQuery's `fabricquery//`: FabricQuery carries no +project UID, so a FabricQuery and a service request for the same project are +separate principals, sharing the executor and the cell and destination packet +budgets but not a fairness key or a project packet budget. A principal may +hold at most two node slots. The shared executor has eight slots total. Keep the existing two-slot ceiling for legacy expensive queries, which this service cannot submit. Queue admission counts reserved snapshot-delivery slots toward the same limits. Live-stream caps do not reserve node-job capacity: a second 32-router stream from a project whose first stream still occupies its queue is refused with `QueueFull`. -FabricQuery work for that project contributes to the same queue limit. +FabricQuery work counts against its own principal's queue limit. Immediately before dispatch of each probe node job, atomically reserve its worst-case packet count from cell, project (when present), and destination @@ -353,17 +361,19 @@ rotating hosts within one prefix still consumes its prefix budget. Avoid a claim of global internet destination protection from a cell-local mechanism. Use bounded maps (4096 project keys, 16384 destination/prefix keys, 4 MiB total -bucket-state storage). A key may be discarded only when fully refilled and no -active/queued work references it. On capacity exhaustion reject new keys with +bucket-state storage). A key may be discarded only when fully refilled: it then +holds no debt, and a key recreated later starts at no more than a full bucket. On capacity exhaustion reject new keys with `LimiterUnavailable`; never evict debt. Persist no diagnostic payload in these maps. Expose aggregate counts rather than key-valued metrics. ### Alternate callers and node enforcement Cell and destination packet buckets include service, operator gateway, -FabricQuery, and direct operator-node probes. Project packet buckets apply to -service and FabricQuery; direct operators use their own principal bucket with -the same rates. Every probe, including direct-node Execute, must obtain a +FabricQuery, and direct operator-node probes. Each principal above has its own +packet bucket at the project rate: a service project, a FabricQuery source, or +an operator, whether through the gateway or directly; a direct probe is +charged only on a node running both `--probe-permits` and +`--require-probe-permits`. Every probe, including direct-node Execute, must obtain a single-node, single-attempt permit from the active cell authority. For direct operators, the node requests it on an authenticated node-only internal RPC; the service has no access to that RPC. That admission uses the same executor @@ -386,7 +396,9 @@ because it can evict completed entries. After node restart or lost permit-consumption state, refuse permits for 32 s, then validate epoch and expiration before accepting new ones; never reuse a surviving permit. Unsupported/old nodes fail closed -for aggregate-budget probes when the feature is enabled. +for aggregate-budget probes when the feature is enabled: a node reports +`probe_permits` in `Info` only when it enforces permits, and the gateway sends +a probe to no other node, failing that router with `QueryTypeUnavailable`. Keep the existing node-wide packet pacing and destination checks as additional limits. Per-node pacing alone cannot substitute for aggregate charging. @@ -544,7 +556,7 @@ A request received at 12:00:00 with the following expiration has 30 s remaining: ``` A request that also lists `aggregate-probe-budgets` is refused with -`VersionUnsupported` until the gateway enforces aggregate probe budgets (#1045); +`VersionUnsupported` by a gateway that does not enforce aggregate probe budgets; a v1 service is advertised as enabled only once all three features are served. A mixed result stream (one JSON object per protobuf event): diff --git a/internal/fabric/errcode/errcode.go b/internal/fabric/errcode/errcode.go index fb20c18de..60afbed02 100644 --- a/internal/fabric/errcode/errcode.go +++ b/internal/fabric/errcode/errcode.go @@ -10,10 +10,12 @@ package errcode import ( "context" "errors" + "time" "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/durationpb" "go.datum.net/galactic/internal/fabric/frr" "go.datum.net/galactic/internal/fabric/probe" @@ -81,6 +83,19 @@ const ( // InventoryTooLarge means the cell's router inventory exceeds what one // Looking Glass service snapshot may list. InventoryTooLarge Code = "InventoryTooLarge" + // Throttled means an admission or packet budget is exhausted; the + // status carries RetryInfo. + Throttled Code = "Throttled" + // QueueFull means the cell's execution queue, a project's share of it, + // or the live-stream limit cannot take the request's work. + QueueFull Code = "QueueFull" + // LimiterUnavailable means the cell's limiter cannot account for new + // work: it is in its recovery hold, its key maps are full, or a node + // cannot verify a probe permit. + LimiterUnavailable Code = "LimiterUnavailable" + // DuplicateRequest means a request ID was reused with identical + // arguments; it is never answered with a saved result. + DuplicateRequest Code = "DuplicateRequest" ) // grpcCodes maps each code to the gRPC status code it travels as. @@ -109,12 +124,92 @@ var grpcCodes = map[Code]codes.Code{ Cancelled: codes.Canceled, QueueTimeout: codes.DeadlineExceeded, InventoryTooLarge: codes.ResourceExhausted, + Throttled: codes.ResourceExhausted, + QueueFull: codes.ResourceExhausted, + LimiterUnavailable: codes.Unavailable, + DuplicateRequest: codes.AlreadyExists, } // MetadataQueryCode is the ErrorInfo metadata key carrying the query // package's own validation code on an InvalidQuery error. const MetadataQueryCode = "queryCode" +// Throttle metadata keys and their execution_started value. +const ( + MetadataScope = "scope" + MetadataExecutionStarted = "execution_started" +) + +// Retry builds a refusal that carries retry guidance: ErrorInfo metadata +// naming the limiting scope (cell, project, destination or queue) and +// execution_started=false, and RetryInfo with delay rounded up to the +// millisecond. +func Retry(code Code, msg, scope string, delay time.Duration) error { + gc, ok := grpcCodes[code] + if !ok { + gc = codes.Unknown + } + if len(msg) > query.MaxErrorMessageLength { + msg = msg[:query.MaxErrorMessageLength] + } + if r := delay % time.Millisecond; r != 0 { + delay += time.Millisecond - r + } + st, err := status.New(gc, msg).WithDetails( + &errdetails.ErrorInfo{Reason: string(code), Domain: Domain, Metadata: map[string]string{ + MetadataScope: scope, MetadataExecutionStarted: "false", + }}, + &errdetails.RetryInfo{RetryDelay: durationpb.New(delay)}, + ) + if err != nil { + return status.Error(gc, msg) + } + return st.Err() +} + +// RetryDelay returns a status's RetryInfo delay, if it carries one. +func RetryDelay(err error) (time.Duration, bool) { + st, ok := status.FromError(err) + if !ok { + return 0, false + } + for _, d := range st.Details() { + if ri, ok := d.(*errdetails.RetryInfo); ok { + return ri.GetRetryDelay().AsDuration(), true + } + } + return 0, false +} + +// Typed reports whether err is a status carrying a fabric-api ErrorInfo, +// i.e. an answer rather than a transport or context failure. +func Typed(err error) bool { + st, ok := status.FromError(err) + if !ok { + return false + } + for _, d := range st.Details() { + if info, ok := d.(*errdetails.ErrorInfo); ok && info.GetDomain() == Domain { + return true + } + } + return false +} + +// Metadata returns a status's ErrorInfo metadata in Domain, if any. +func Metadata(err error) map[string]string { + st, ok := status.FromError(err) + if !ok { + return nil + } + for _, d := range st.Details() { + if info, ok := d.(*errdetails.ErrorInfo); ok && info.GetDomain() == Domain { + return info.GetMetadata() + } + } + return nil +} + // Status builds a gRPC error carrying code as its ErrorInfo reason. func Status(code Code, msg string) error { return StatusWithMetadata(code, msg, nil) diff --git a/internal/fabric/gateway/admission.go b/internal/fabric/gateway/admission.go new file mode 100644 index 000000000..71a9f985f --- /dev/null +++ b/internal/fabric/gateway/admission.go @@ -0,0 +1,149 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "crypto/rand" + "encoding/hex" + "sync" + "time" + + "google.golang.org/protobuf/types/known/timestamppb" + + fabricv1 "go.datum.net/galactic/api/fabric/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/node" + "go.datum.net/galactic/internal/fabric/query" +) + +// ReservationGrace is how long past a probe job's deadline its execution +// slot stays held when the node's answer was lost: the node may still be +// sending it. +const ReservationGrace = 2 * time.Second + +// Admission is the leader's aggregate accounting: service request tokens, +// attempt keys and live streams, and the packet budgets every probe in the +// cell draws from, whatever its caller. Nothing is admitted unless the +// Authority confirms this process holds the election, outside its recovery +// hold. +type Admission struct { + Limits limit.Limits + Buckets *limit.Buckets + Attempts *limit.Attempts + Authority *limit.Authority + // Now returns the current time; nil selects time.Now. + Now func() time.Time + + mu sync.Mutex + streams int + projectStreams map[string]int +} + +// NewAdmission validates l and returns empty accounting under authority, +// which it gives its buckets. +func NewAdmission(l limit.Limits, authority *limit.Authority) (*Admission, error) { + if err := l.Validate(); err != nil { + return nil, err + } + b := limit.NewBuckets(l, time.Now()) + authority.Buckets = b + return &Admission{Limits: l, Buckets: b, Attempts: limit.NewAttempts(l), Authority: authority}, nil +} + +func (a *Admission) now() time.Time { + if a.Now != nil { + return a.Now() + } + return time.Now() +} + +// Executor returns a shared executor bounded by the admission's limits. +func (a *Admission) Executor() *Executor { + e := NewExecutor(a.Limits.Slots, 0, a.Limits.Queue) + e.PrincipalSlots, e.PrincipalQueue = a.Limits.PrincipalSlots, a.Limits.PrincipalQueue + return e +} + +// openStream counts a live service stream for project, or refuses with +// QueueFull when the cell's or the project's stream limit is reached. The +// returned function ends it. +func (a *Admission) openStream(project string) (func(), error) { + a.mu.Lock() + defer a.mu.Unlock() + if a.projectStreams == nil { + a.projectStreams = map[string]int{} + } + if a.streams >= a.Limits.Streams || a.projectStreams[project] >= a.Limits.ProjectStreams { + return nil, errcode.Retry(errcode.QueueFull, "the live stream limit is reached", string(limit.ScopeQueue), + time.Second) + } + a.streams++ + a.projectStreams[project]++ + return func() { + a.mu.Lock() + defer a.mu.Unlock() + a.streams-- + if a.projectStreams[project]--; a.projectStreams[project] <= 0 { + delete(a.projectStreams, project) + } + }, nil +} + +// probeCost is a probe's worst-case packet count. +func probeCost(t query.Type) int { + if t == query.TypeTraceroute { + return limit.TraceroutePackets + } + return limit.PingPackets +} + +// permit confirms ownership, charges q's worst-case packets to the cell, +// principal and destination buckets, and returns a single-attempt permit +// for n until deadline. Nothing is refunded once charged. +func (a *Admission) permit( + ctx context.Context, principal, requestID, nodeName string, q query.Query, deadline time.Time, +) (*fabricv1.ProbePermit, error) { + epoch, _, err := a.Authority.Check(ctx) + if err != nil { + return nil, err + } + dst, err := query.ResolvedProbe(q) + if err != nil { + return nil, errcode.FromError(err) + } + cost := probeCost(q.Type) + if err := a.Buckets.ChargePackets(principal, dst, cost, a.now()); err != nil { + return nil, err + } + return &fabricv1.ProbePermit{ + Id: newPermitID(), + Epoch: epoch.String(), + RequestId: requestID, + Node: nodeName, + Destination: dst.String(), + Operation: node.QueryToProto(q).GetType(), + Packets: uint32(cost), + Deadline: timestamppb.New(deadline), + }, nil +} + +func newPermitID() string { + b := make([]byte, 16) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +// holdUntil releases a slot at until rather than now: a node whose answer +// was lost may still be executing until its deadline plus +// ReservationGrace. +func holdUntil(release func(), until, now time.Time) { + if d := until.Sub(now); d > 0 { + time.AfterFunc(d, release) + return + } + release() +} diff --git a/internal/fabric/gateway/admission_test.go b/internal/fabric/gateway/admission_test.go new file mode 100644 index 000000000..1fb15ea0a --- /dev/null +++ b/internal/fabric/gateway/admission_test.go @@ -0,0 +1,542 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "errors" + "fmt" + "os" + "sync" + "testing" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" + coordinationv1 "k8s.io/api/coordination/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + servicev1 "go.datum.net/galactic/api/fabric/service/v1" + fabricv1 "go.datum.net/galactic/api/fabric/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/node" +) + +const ( + testLease = "fabric-api-gateway" + testHolder = "gateway-0_test" + // probeTarget6 and probeTarget4 are probe destinations. + probeTarget6 = "2001:db8::1" + probeTarget4 = "192.0.2.1" + // podA is router-a's fabric-router pod UID. + podA = "pod-a" +) + +// switchableLease serves an election Lease held by testHolder, whose reads +// fail while failing is set. +type switchableLease struct { + client.Client + mu sync.Mutex + failing bool +} + +func (l *switchableLease) fail(on bool) { + l.mu.Lock() + defer l.mu.Unlock() + l.failing = on +} + +func newSwitchableLease(t *testing.T) *switchableLease { + t.Helper() + s := runtime.NewScheme() + _ = clientgoscheme.AddToScheme(s) + l := &switchableLease{} + l.Client = fake.NewClientBuilder().WithScheme(s).WithObjects(&coordinationv1.Lease{ + ObjectMeta: metav1.ObjectMeta{Namespace: DefaultNamespace, Name: testLease, UID: "lease-uid"}, + Spec: coordinationv1.LeaseSpec{ + HolderIdentity: ptr.To(testHolder), LeaseDurationSeconds: ptr.To[int32](15), + // Renewed in the future, so the term never lapses during a test. + RenewTime: &metav1.MicroTime{Time: time.Now().Add(time.Hour)}, + }, + }).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, + opts ...client.GetOption) error { + l.mu.Lock() + failing := l.failing + l.mu.Unlock() + if failing { + return errors.New("api unavailable") + } + return c.Get(ctx, key, obj, opts...) + }, + }).Build() + return l +} + +// roomyLimits are limits no ordinary test reaches. +func roomyLimits() limit.Limits { + l := limit.Defaults() + big := limit.Rate{PerSecond: 1000, Burst: 10000} + l.RequestCell, l.RequestProject = big, big + l.PacketCell, l.PacketPrincipal, l.PacketHost, l.PacketPrefix = big, big, big, big + l.ProjectStreams = l.Streams + return l +} + +// newTestAdmission returns an admission whose authority has already served +// its recovery hold, with every bucket refilled. +func newTestAdmission(t *testing.T, l limit.Limits) *Admission { + t.Helper() + lease := newSwitchableLease(t) + auth := &limit.Authority{ + Reader: lease, Namespace: DefaultNamespace, Name: testLease, Identity: testHolder, Hold: time.Nanosecond, + } + adm, err := NewAdmission(l, auth) + if err != nil { + t.Fatal(err) + } + activate(t, adm) + return adm +} + +// activate ends the authority's hold and fills its buckets. +func activate(t *testing.T, adm *Admission) { + t.Helper() + _, _, _ = adm.Authority.Check(t.Context()) + time.Sleep(time.Millisecond) + if _, _, err := adm.Authority.Check(t.Context()); err != nil { + t.Fatal(err) + } + adm.Buckets.Reset(time.Now().Add(-time.Hour)) +} + +// withAdmission gives svc and its runner a fresh admission under l, and an +// executor bounded by l. +func withAdmission(t *testing.T, svc *Service, l limit.Limits) *Admission { + t.Helper() + adm := newTestAdmission(t, l) + svc.Admission, svc.Runner.Admission = adm, adm + svc.Runner.Executor = adm.Executor() + return adm +} + +// requestID returns a distinct lowercase UUID for n. +func requestID(n int) string { + return fmt.Sprintf("%08x-926f-43dc-b03d-c29550a827ab", n) +} + +func requestFor(project string, n int, mod func(*runReq)) *runReq { + req := validRequest(time.Now()) + req.ProjectId, req.RequestId = project, requestID(n) + if mod != nil { + mod(req) + } + return req +} + +func wantRetry(t *testing.T, err error, code errcode.Code, scope string) time.Duration { + t.Helper() + if errcode.Of(err) != code { + t.Fatalf("err = %v, want %s", err, code) + } + md := errcode.Metadata(err) + if md[errcode.MetadataScope] != scope || md[errcode.MetadataExecutionStarted] != "false" { + t.Fatalf("metadata = %v, want scope %s", md, scope) + } + d, ok := errcode.RetryDelay(err) + if !ok || d <= 0 { + t.Fatalf("no retry guidance on %v", err) + } + return d +} + +func TestServiceRequestTokens(t *testing.T) { + nodes := &routerNodes{} + svc := newService(t, routerPods(routerA), nodes, 8) + l := roomyLimits() + l.RequestProject = limit.Rate{PerSecond: 0.2, Burst: 2} + withAdmission(t, svc, l) + + for i := range 2 { + if _, err := collect(t, svc, requestFor("project-a", i, nil)); err != nil { + t.Fatalf("request %d: %v", i, err) + } + } + calls := nodes.total() + _, err := collect(t, svc, requestFor("project-a", 2, nil)) + if d := wantRetry(t, err, errcode.Throttled, "project"); d > 5*time.Second { + t.Errorf("retry %s exceeds one token at 0.2/s", d) + } + if nodes.total() != calls { + t.Error("a throttled request reached a router") + } + // Another project, behind the same service identity, is not throttled. + if _, err := collect(t, svc, requestFor("project-b", 3, nil)); err != nil { + t.Errorf("project-b: %v", err) + } +} + +func TestServiceDuplicateAttempts(t *testing.T) { + nodes := &routerNodes{} + svc := newService(t, routerPods(routerA), nodes, 8) + if _, err := collect(t, svc, requestFor("project-a", 1, nil)); err != nil { + t.Fatal(err) + } + calls := nodes.total() + _, err := collect(t, svc, requestFor("project-a", 1, nil)) + if errcode.Of(err) != errcode.DuplicateRequest { + t.Errorf("identical retry: %v", err) + } + // A later expiration is the same attempt. + _, err = collect(t, svc, requestFor("project-a", 1, func(r *runReq) { + r.ExpiresAt = timestamppb.New(time.Now().Add(40 * time.Second)) + })) + if errcode.Of(err) != errcode.DuplicateRequest { + t.Errorf("retry with a later expiration: %v", err) + } + _, err = collect(t, svc, requestFor("project-a", 1, func(r *runReq) { r.Query.Target = "2001:db8::2" })) + if errcode.Of(err) != errcode.DuplicateConflict { + t.Errorf("changed arguments: %v", err) + } + if nodes.total() != calls { + t.Error("a duplicate reached a router") + } + // The same request ID in another project is another attempt. + if _, err := collect(t, svc, requestFor("project-b", 1, nil)); err != nil { + t.Errorf("other project: %v", err) + } +} + +func TestServiceStreamLimit(t *testing.T) { + release := make(chan struct{}) + started := make(chan struct{}, 4) + nodes := &routerNodes{answers: map[string]routerAnswer{routerA: blockAnswer(routerA, release, started)}} + svc := newService(t, routerPods(routerA), nodes, 8) + l := roomyLimits() + l.ProjectStreams = 1 + withAdmission(t, svc, l) + + events, done := run(t, svc, requestFor("project-a", 1, nil), 0) + <-started + _, err := collect(t, svc, requestFor("project-a", 2, nil)) + wantRetry(t, err, errcode.QueueFull, "queue") + close(release) + for range events { + } + if err := <-done; err != nil { + t.Fatal(err) + } + // The ended stream no longer counts. + if _, err := collect(t, svc, requestFor("project-a", 3, nil)); err != nil { + t.Errorf("after the first stream ended: %v", err) + } +} + +// A request's router jobs are admitted to the queue all together or not at +// all: a second request from a project whose first still fills its share +// is refused before its snapshot, and runs nothing. +func TestServiceAtomicQueueReservation(t *testing.T) { + release := make(chan struct{}) + started := make(chan struct{}, 8) + answers := map[string]routerAnswer{} + for _, n := range []string{routerA, routerB, routerC} { + answers[n] = blockAnswer(n, release, started) + } + nodes := &routerNodes{answers: answers} + svc := newService(t, routerPods(routerA, routerB, routerC), nodes, 8) + l := roomyLimits() + l.PrincipalSlots, l.PrincipalQueue = 2, 3 + withAdmission(t, svc, l) + + events, done := run(t, svc, requestFor("project-a", 1, nil), 0) + <-started + <-started + waitDepth(t, svc.Runner.Executor, 1) + got, err := collect(t, svc, requestFor("project-a", 2, nil)) + wantRetry(t, err, errcode.QueueFull, "queue") + if len(got) != 0 { + t.Errorf("a refused request sent %d events", len(got)) + } + // Another project's share is its own. + other, otherDone := run(t, svc, requestFor("project-b", 3, nil), 0) + close(release) + for range events { + } + for range other { + } + if err := <-done; err != nil { + t.Fatal(err) + } + if err := <-otherDone; err != nil { + t.Fatal(err) + } + if n := nodes.total(); n != 6 { + t.Errorf("%d router calls, want 6", n) + } +} + +func TestServicePacketBudget(t *testing.T) { + nodes := &routerNodes{} + svc := newService(t, routerPods(routerA, routerB, routerC), nodes, 8) + l := roomyLimits() + // One traceroute's worth of packets per destination host. + l.PacketHost = limit.Rate{PerSecond: 1, Burst: limit.TraceroutePackets} + withAdmission(t, svc, l) + + events, err := collect(t, svc, requestFor("project-a", 1, func(r *runReq) { + r.Query.Type = fabricv1.QueryType_QUERY_TYPE_TRACEROUTE + })) + if err != nil { + t.Fatal(err) + } + _, outcomes, c := checkGrammar(t, events) + throttled := 0 + for _, o := range outcomes { + if o.GetFailure().GetReason() == string(errcode.Throttled) { + throttled++ + } + } + if throttled != 2 || c.GetSuccessful() != 1 || c.GetReason() != CompletePartialResults { + t.Errorf("throttled %d, complete %v", throttled, c) + } + for _, o := range outcomes { + if f := o.GetFailure(); f != nil && (f.GetScope() != "destination" || f.GetRetryDelay().AsDuration() <= 0) { + t.Errorf("throttled router carries no retry guidance: %v", f) + } + } + if n := nodes.total(); n != 1 { + t.Errorf("%d routers probed, want 1", n) + } +} + +func TestServiceRecoveryHold(t *testing.T) { + nodes := &routerNodes{} + svc := newService(t, routerPods(routerA), nodes, 8) + adm, err := NewAdmission(roomyLimits(), &limit.Authority{ + Reader: newSwitchableLease(t), Namespace: DefaultNamespace, Name: testLease, Identity: testHolder, + }) + if err != nil { + t.Fatal(err) + } + svc.Admission, svc.Runner.Admission = adm, adm + _, err = collect(t, svc, requestFor("project-a", 1, nil)) + if d := wantRetry(t, err, errcode.LimiterUnavailable, "cell"); d > limit.RecoveryHold || + d < limit.RecoveryHold-time.Minute { + t.Errorf("remaining hold %s", d) + } + if nodes.total() != 0 { + t.Error("a request ran during the recovery hold") + } + // Operator and FabricQuery probes wait out the hold too; reads do not. + ping := node.QueryFromProto(&fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_PING, Target: probeTarget6, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV6}) + routers := []Node{{Name: routerA, PodUID: podA, Selected: true}} + out := svc.Runner.Run(t.Context(), "operator/alice", "op-1", ping, routers, nil, time.Now().Add(10*time.Second)) + if errcode.Of(out[0].Err) != errcode.LimiterUnavailable { + t.Errorf("operator probe during the hold: %v", out[0].Err) + } + summary := node.QueryFromProto(&fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_BGP_SUMMARY, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV4}) + out = svc.Runner.Run(t.Context(), "ns/cluster", "fq-1", summary, routers, nil, time.Now().Add(10*time.Second)) + if out[0].Err != nil { + t.Errorf("FabricQuery read during the hold: %v", out[0].Err) + } +} + +// Losing the election cancels the request's running routers and ends the +// stream with OwnershipLost, every selected router accounted for. +func TestServiceOwnershipLost(t *testing.T) { + release := make(chan struct{}) + started := make(chan struct{}, 4) + lease := newSwitchableLease(t) + nodes := &routerNodes{answers: map[string]routerAnswer{ + routerA: blockAnswer(routerA, release, started), routerB: blockAnswer(routerB, release, started), + }} + svc := newService(t, routerPods(routerA, routerB), nodes, 8) + l := roomyLimits() + l.PrincipalSlots = 1 + adm, err := NewAdmission(l, &limit.Authority{ + Reader: lease, Namespace: DefaultNamespace, Name: testLease, Identity: testHolder, Hold: time.Nanosecond, + }) + if err != nil { + t.Fatal(err) + } + activate(t, adm) + svc.Admission, svc.Runner.Admission, svc.Runner.Executor = adm, adm, adm.Executor() + defer close(release) + go adm.Authority.Watch(t.Context(), 50*time.Millisecond) + + events, done := run(t, svc, requestFor("project-a", 1, nil), 0) + <-started + // One router runs and the other waits for its slot when the lease + // becomes unreadable; the watch notices within its interval. + lost := time.Now() + lease.fail(true) + var got []*servicev1.DiagnosticEvent + for ev := range events { + got = append(got, ev) + } + if err := <-done; err != nil { + t.Fatal(err) + } + if d := time.Since(lost); d > 2*time.Second { + t.Errorf("work outlived the loss by %s", d) + } + _, outcomes, c := checkGrammar(t, got) + if len(outcomes) != 2 || c.GetReason() != string(errcode.OwnershipLost) || c.GetFailed() != 2 { + t.Errorf("outcomes %v, complete %v", outcomes, c) + } +} + +func TestRunnerRefusesNodesWithoutPermits(t *testing.T) { + nodes := &routerNodes{legacy: map[string]bool{routerA: true}} + svc := newService(t, routerPods(routerA, routerB), nodes, 8) + events, err := collect(t, svc, requestFor("project-a", 1, nil)) + if err != nil { + t.Fatal(err) + } + _, outcomes, _ := checkGrammar(t, events) + for _, o := range outcomes { + want := "" + if o.GetNode() == routerA { + want = string(errcode.QueryTypeUnavailable) + } + if o.GetFailure().GetReason() != want { + t.Errorf("%s: %v", o.GetNode(), o) + } + } + nodes.mu.Lock() + defer nodes.mu.Unlock() + if nodes.calls[routerA] != 0 { + t.Error("a probe reached a node that does not enforce permits") + } +} + +func TestRunnerAttachesPermit(t *testing.T) { + var mu sync.Mutex + var got *fabricv1.ProbePermit + nodes := &routerNodes{answers: map[string]routerAnswer{routerA: func(_ context.Context, + req *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) { + mu.Lock() + got = req.GetPermit() + mu.Unlock() + return pingObservation(routerA, 3), nil + }}} + svc := newService(t, routerPods(routerA), nodes, 8) + req := requestFor("project-a", 1, nil) + if _, err := collect(t, svc, req); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if got.GetEpoch() != "lease-uid/"+testHolder || got.GetNode() != routerA || got.GetRequestId() != req.GetRequestId() || + got.GetDestination() != probeTarget6 || got.GetPackets() != limit.PingPackets || got.GetId() == "" || + got.GetOperation() != fabricv1.QueryType_QUERY_TYPE_PING || + got.GetDeadline().AsTime().After(req.GetExpiresAt().AsTime()) { + t.Errorf("permit = %v", got) + } +} + +// A probe whose node answer was lost keeps its slot until the job's +// deadline plus the grace: the node may still be sending it. A typed +// answer, or a read without an answer, frees the slot at once. +func TestRunnerHoldsSlotWithoutAnswer(t *testing.T) { + lost := func(context.Context, *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) { + return nil, status.Error(codes.Unavailable, "connection reset") + } + nodes := &routerNodes{answers: map[string]routerAnswer{routerA: lost, routerB: failAnswer(errcode.FRRUnavailable)}} + adm := newTestAdmission(t, roomyLimits()) + r := &Runner{Clients: nodes, Executor: NewExecutor(1, 0, 0), Admission: adm} + summary := node.QueryFromProto(&fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_BGP_SUMMARY, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV4}) + ping := node.QueryFromProto(&fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_PING, Target: probeTarget6, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV6}) + nodeA := []Node{{Name: routerA, PodUID: podA, Selected: true}} + nodeB := []Node{{Name: routerB, PodUID: "pod-b", Selected: true}} + later := time.Now().Add(time.Minute) + + for name, run := range map[string]func(){ + "typed failure": func() { r.Run(t.Context(), "p", "id-1", ping, nodeB, nil, later) }, + "read without answer": func() { r.Run(t.Context(), "p", "id-2", summary, nodeA, nil, later) }, + } { + run() + rel, err := tryAcquire(r.Executor) + if err != nil { + t.Fatalf("%s: slot held: %v", name, err) + } + rel() + } + // A probe without an answer: held. + expires := time.Now().Add(300 * time.Millisecond) + r.Run(t.Context(), "p", "id-3", ping, nodeA, nil, expires) + if _, err := tryAcquire(r.Executor); err == nil { + t.Fatal("slot freed although the node never answered") + } + // Released after the deadline plus the grace. + time.Sleep(time.Until(expires.Add(ReservationGrace + 100*time.Millisecond))) + if rel, err := tryAcquire(r.Executor); err != nil { + t.Fatalf("slot still held past its grace: %v", err) + } else { + rel() + } +} + +func tryAcquire(e *Executor) (func(), error) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + return e.Acquire(ctx, "probe", false) +} + +// The published capabilities fixture shows the contract's default limits +// exactly as a gateway reports them. +func TestCapabilitiesFixtureMatchesDefaults(t *testing.T) { + data, err := os.ReadFile("../../../api/fabric/service/v1/testdata/capabilities.json") + if err != nil { + t.Fatal(err) + } + var caps servicev1.GetCapabilitiesResponse + if err := protojson.Unmarshal(data, &caps); err != nil { + t.Fatal(err) + } + if want := admissionLimits(limit.Defaults()); !proto.Equal(caps.GetLimits().GetAdmission(), want) { + t.Errorf("fixture admission = %v, want %v", caps.GetLimits().GetAdmission(), want) + } +} + +// With aggregate budgets a full principal queue refuses an operator or +// FabricQuery job with QueueFull and retry guidance. +func TestRunnerQueueFull(t *testing.T) { + adm := newTestAdmission(t, roomyLimits()) + e := NewExecutor(1, 0, 1) + r := &Runner{Clients: &routerNodes{}, Executor: e, Admission: adm} + hold, err := e.Acquire(t.Context(), "other", false) + if err != nil { + t.Fatal(err) + } + defer hold() + go func() { + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + if rel, err := e.Acquire(ctx, "other", false); err == nil { + rel() + } + }() + waitDepth(t, e, 1) + summary := node.QueryFromProto(&fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_BGP_SUMMARY, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV4}) + out := r.Run(t.Context(), "ns/cluster", "fq-1", summary, []Node{{Name: routerA, Selected: true}}, nil, + time.Now().Add(10*time.Second)) + wantRetry(t, out[0].Err, errcode.QueueFull, "queue") +} diff --git a/internal/fabric/gateway/debug.go b/internal/fabric/gateway/debug.go index c0f2188e2..64c9ea59f 100644 --- a/internal/fabric/gateway/debug.go +++ b/internal/fabric/gateway/debug.go @@ -22,6 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" forwardv1 "go.datum.net/galactic/api/fabric/forward/v1" + permitv1 "go.datum.net/galactic/api/fabric/permit/v1" servicev1 "go.datum.net/galactic/api/fabric/service/v1" fabricv1 "go.datum.net/galactic/api/fabric/v1" "go.datum.net/galactic/internal/fabric/errcode" @@ -36,9 +37,10 @@ import ( const operatorHeader = "x-fabric-api-operator" // GatewayMethods is the gateway server's per-role method table. Operators -// call the debug service directly and service identities the Looking Glass -// service; the gateway identity appears only on calls a follower forwards to -// the leader. No role may call another role's methods. +// call the debug service directly, service identities the Looking Glass +// service and nodes the permit service; the gateway identity appears only +// on calls a follower forwards to the leader. No role may call another +// role's methods. var GatewayMethods = map[identity.Role]map[string]bool{ identity.RoleOperator: { fabricv1.FabricGatewayService_Query_FullMethodName: true, @@ -47,6 +49,12 @@ var GatewayMethods = map[identity.Role]map[string]bool{ identity.RoleGateway: { fabricv1.FabricGatewayService_Query_FullMethodName: true, forwardv1.ForwardService_ForwardDiagnostic_FullMethodName: true, + permitv1.PermitService_RequestPermit_FullMethodName: true, + permitv1.PermitService_ReleasePermit_FullMethodName: true, + }, + identity.RoleNode: { + permitv1.PermitService_RequestPermit_FullMethodName: true, + permitv1.PermitService_ReleasePermit_FullMethodName: true, }, identity.RoleService: { servicev1.LookingGlassService_GetCapabilities_FullMethodName: true, @@ -122,7 +130,7 @@ func (d *Debug) Query(ctx context.Context, req *fabricv1.QueryRequest) (*fabricv budgets = &fabricv1.Budgets{} } id := "debug-" + randomID() - outcomes := d.Runner.Run(ctx, "operator/"+operator, id, q, nodes, budgets, expires) + outcomes := d.Runner.Run(ctx, operatorPrincipal(operator), id, q, nodes, budgets, expires) resp := &fabricv1.QueryResponse{RequestId: id} for _, o := range outcomes { nr := &fabricv1.NodeResult{Node: o.Node.Name, Observation: o.Observation} diff --git a/internal/fabric/gateway/debug_test.go b/internal/fabric/gateway/debug_test.go index 179e02d36..a217f0c4f 100644 --- a/internal/fabric/gateway/debug_test.go +++ b/internal/fabric/gateway/debug_test.go @@ -47,7 +47,7 @@ const testLeaseName = "fabric-api-gateway" func serveDebug(t *testing.T, d *Debug, creds *identity.Credentials) string { t.Helper() - srv := NewServer(creds, Allowlist{}, d, &Service{Cell: testSite, Elected: d.Elected}) + srv := NewServer(creds, Allowlist{}, d, &Service{Cell: testSite, Elected: d.Elected}, noPermits(d.Elected)) var lc net.ListenConfig l, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") if err != nil { diff --git a/internal/fabric/gateway/executor.go b/internal/fabric/gateway/executor.go index 9adf12e81..953daa5b2 100644 --- a/internal/fabric/gateway/executor.go +++ b/internal/fabric/gateway/executor.go @@ -17,19 +17,29 @@ var ErrQueueFull = errors.New("cell execution queue is full") // Executor is the cell-wide budget for node RPCs, shared by every concurrent // request. It grants at most Slots RPCs at once, at most ExpensiveSlots of // them expensive searches, so searches can never occupy every slot. Waiters -// queue per project and are served round-robin across projects, FIFO within -// one, so one project's burst cannot starve another. The queue is bounded; -// a full queue refuses at once rather than letting waits outlive requests. +// queue per principal (a project, a FabricQuery source or an operator) and +// are served round-robin across principals, FIFO within one, so one +// principal's burst cannot starve another. The queue is bounded; a full +// queue refuses at once rather than letting waits outlive requests. Queue +// capacity may be reserved ahead for a request's jobs, all at once or not at +// all. type Executor struct { slots, expSlots, maxQueue int - mu sync.Mutex - inUse int - expUse int - waiting int - queues map[string][]*waiter - ring []string - next int + // PrincipalSlots, when positive, bounds one principal's granted slots, + // and PrincipalQueue its queued and reserved jobs. Set them before use. + PrincipalSlots, PrincipalQueue int + + mu sync.Mutex + inUse int + expUse int + waiting int + reserved int + queues map[string][]*waiter + active map[string]int + held map[string]int + ring []string + next int // ObserveWait, when set, receives how long each granted waiter waited. ObserveWait func(time.Duration) @@ -55,17 +65,87 @@ func NewExecutor(slots, expensiveSlots, maxQueue int) *Executor { if maxQueue <= 0 { maxQueue = 256 } - return &Executor{slots: slots, expSlots: expensiveSlots, maxQueue: maxQueue, queues: map[string][]*waiter{}} + return &Executor{ + slots: slots, expSlots: expensiveSlots, maxQueue: maxQueue, + queues: map[string][]*waiter{}, active: map[string]int{}, held: map[string]int{}, + } } // Acquire waits for a slot for project until ctx ends. The returned function -// releases it. +// releases it. A full cell queue, or a full share of it for project, refuses +// with ErrQueueFull. func (e *Executor) Acquire(ctx context.Context, project string, expensive bool) (func(), error) { e.mu.Lock() - if e.waiting >= e.maxQueue { + if !e.roomLocked(project, 1) { + e.mu.Unlock() + return nil, ErrQueueFull + } + return e.wait(ctx, project, expensive) +} + +// roomLocked reports whether n more jobs of project fit the cell's queue +// and project's share of it, reservations included. +func (e *Executor) roomLocked(project string, n int) bool { + if e.waiting+e.reserved+n > e.maxQueue { + return false + } + return e.PrincipalQueue <= 0 || len(e.queues[project])+e.held[project]+n <= e.PrincipalQueue +} + +// Reservation holds queue capacity for a request's jobs. +type Reservation struct { + e *Executor + project string + left int +} + +// Reserve holds queue capacity for n jobs of project, or refuses with +// ErrQueueFull without holding any. +func (e *Executor) Reserve(project string, n int) (*Reservation, error) { + e.mu.Lock() + defer e.mu.Unlock() + if !e.roomLocked(project, n) { + return nil, ErrQueueFull + } + e.reserved += n + e.held[project] += n + return &Reservation{e: e, project: project, left: n}, nil +} + +// Acquire turns one reserved job into a waiter and waits for a slot until +// ctx ends, like Executor.Acquire. It fails with ErrQueueFull when the +// reservation is used up. +func (r *Reservation) Acquire(ctx context.Context, expensive bool) (func(), error) { + e := r.e + e.mu.Lock() + if r.left == 0 { e.mu.Unlock() return nil, ErrQueueFull } + r.left-- + e.unholdLocked(r.project, 1) + return e.wait(ctx, r.project, expensive) +} + +// Release returns the reservation's unused capacity. +func (r *Reservation) Release() { + e := r.e + e.mu.Lock() + defer e.mu.Unlock() + e.unholdLocked(r.project, r.left) + r.left = 0 +} + +func (e *Executor) unholdLocked(project string, n int) { + e.reserved -= n + if e.held[project] -= n; e.held[project] <= 0 { + delete(e.held, project) + } +} + +// wait queues a waiter for project, with e.mu held, and waits for its +// grant until ctx ends. +func (e *Executor) wait(ctx context.Context, project string, expensive bool) (func(), error) { w := &waiter{expensive: expensive, ready: make(chan struct{}), queued: time.Now()} if len(e.queues[project]) == 0 { e.ring = append(e.ring, project) @@ -78,6 +158,9 @@ func (e *Executor) Acquire(ctx context.Context, project string, expensive bool) release := func() { e.mu.Lock() e.inUse-- + if e.active[project]--; e.active[project] <= 0 { + delete(e.active, project) + } if w.expensive { e.expUse-- } @@ -111,19 +194,23 @@ func (e *Executor) Depth() int { } // dispatchLocked grants free slots to eligible waiters, round-robin across -// projects. +// projects, skipping a project at its slot share. func (e *Executor) dispatchLocked() { for e.inUse < e.slots && len(e.ring) > 0 { granted := false for i := range len(e.ring) { idx := (e.next + i) % len(e.ring) project := e.ring[idx] + if e.PrincipalSlots > 0 && e.active[project] >= e.PrincipalSlots { + continue + } for _, w := range e.queues[project] { if w.expensive && e.expUse >= e.expSlots { continue } w.granted = true e.inUse++ + e.active[project]++ if w.expensive { e.expUse++ } diff --git a/internal/fabric/gateway/limit/attempts.go b/internal/fabric/gateway/limit/attempts.go new file mode 100644 index 000000000..1835b2dba --- /dev/null +++ b/internal/fabric/gateway/limit/attempts.go @@ -0,0 +1,88 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package limit + +import ( + "sync" + "time" + + "go.datum.net/galactic/internal/fabric/errcode" +) + +// AttemptGrace is how long an attempt key outlives its request's +// expiration. +const AttemptGrace = 2 * time.Second + +// attemptOverhead approximates one entry's bookkeeping beyond its key and +// digest. +const attemptOverhead = 64 + +type attempt struct { + digest string + until time.Time + size int +} + +// Attempts records each admitted attempt key with its argument digest until +// its expiration plus AttemptGrace. It is bounded by entry count and bytes, +// and fails closed when full: a live key is never evicted to admit another. +// It is volatile and lost on restart. +type Attempts struct { + max, maxBytes int + + mu sync.Mutex + bytes int + m map[string]attempt +} + +// NewAttempts returns an empty cache bounded by l. +func NewAttempts(l Limits) *Attempts { + return &Attempts{max: l.Attempts, maxBytes: l.AttemptBytes, m: map[string]attempt{}} +} + +// Register records key with its arguments' digest until expires plus +// AttemptGrace. A live key is refused with DuplicateRequest when its digest +// matches and DuplicateConflict when it does not; a full cache refuses with +// LimiterUnavailable. +func (a *Attempts) Register(key, digest string, expires, now time.Time) error { + a.mu.Lock() + defer a.mu.Unlock() + if prev, ok := a.m[key]; ok && now.Before(prev.until) { + if prev.digest == digest { + return errcode.Status(errcode.DuplicateRequest, "this request ID was already admitted") + } + return errcode.Status(errcode.DuplicateConflict, "this request ID was already admitted with other arguments") + } + size := len(key) + len(digest) + attemptOverhead + if len(a.m) >= a.max || a.bytes+size > a.maxBytes { + a.purge(now) + } + if len(a.m) >= a.max || a.bytes+size > a.maxBytes { + return errcode.Retry(errcode.LimiterUnavailable, "the cell's attempt cache is full", string(ScopeCell), time.Second) + } + if prev, ok := a.m[key]; ok { + a.bytes -= prev.size + } + a.m[key] = attempt{digest: digest, until: expires.Add(AttemptGrace), size: size} + a.bytes += size + return nil +} + +func (a *Attempts) purge(now time.Time) { + for k, v := range a.m { + if !now.Before(v.until) { + delete(a.m, k) + a.bytes -= v.size + } + } +} + +// Len returns the number of recorded keys, expired ones included until the +// next purge. +func (a *Attempts) Len() int { + a.mu.Lock() + defer a.mu.Unlock() + return len(a.m) +} diff --git a/internal/fabric/gateway/limit/authority.go b/internal/fabric/gateway/limit/authority.go new file mode 100644 index 000000000..6526e7d99 --- /dev/null +++ b/internal/fabric/gateway/limit/authority.go @@ -0,0 +1,174 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package limit + +import ( + "context" + "errors" + "sync" + "time" + + coordinationv1 "k8s.io/api/coordination/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + "go.datum.net/galactic/internal/fabric/errcode" +) + +const ( + // RecoveryHold is how long the authority admits nothing after it starts, + // acquires the election, or regains certainty about it. It exceeds the + // 120 s request lifetime plus the 2 s skew and scheduling allowance, and + // every bucket's burst/rate, so no prior-epoch work or token debt + // survives it. + RecoveryHold = 125 * time.Second + // LeaseReadTimeout bounds each uncached election Lease read. + LeaseReadTimeout = time.Second +) + +// Epoch identifies one term of the election: the Lease object's UID and +// the complete holder identity. Recreating the Lease or acquiring it again +// with a new process identity yields a new epoch. +type Epoch struct { + UID string + Holder string +} + +// String renders the epoch as "/", the form a probe permit +// carries. +func (e Epoch) String() string { return e.UID + "/" + e.Holder } + +// ReadEpoch reads the election Lease uncached and returns its epoch when it +// has a holder whose term has not expired at now. The read is bounded by +// LeaseReadTimeout; every failure is OwnershipLost. +func ReadEpoch(ctx context.Context, r client.Reader, namespace, name string, now time.Time) (Epoch, error) { + ctx, cancel := context.WithTimeout(ctx, LeaseReadTimeout) + defer cancel() + var lease coordinationv1.Lease + if err := r.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, &lease); err != nil { + return Epoch{}, errcode.Status(errcode.OwnershipLost, "the election lease could not be read") + } + s := lease.Spec + if s.HolderIdentity == nil || *s.HolderIdentity == "" || s.RenewTime == nil || s.LeaseDurationSeconds == nil { + return Epoch{}, errcode.Status(errcode.OwnershipLost, "the election lease has no holder") + } + if !now.Before(s.RenewTime.Add(time.Duration(*s.LeaseDurationSeconds) * time.Second)) { + return Epoch{}, errcode.Status(errcode.OwnershipLost, "the election lease has expired") + } + return Epoch{UID: string(lease.UID), Holder: *s.HolderIdentity}, nil +} + +// Authority decides whether this gateway may admit and dispatch aggregate +// work. Every Check reads the election Lease uncached and requires this +// process's own unexpired holder identity. The first valid read of a new +// epoch, the first after start, and the first after any failed read begin a +// RecoveryHold, during which Check refuses with LimiterUnavailable and the +// remaining delay; the first valid read after the hold empties the buckets +// and admits from that instant. A failed read, another holder or an expired +// term refuses with OwnershipLost and cancels the context of the epoch's +// work. +type Authority struct { + // Reader must read uncached. + Reader client.Reader + Namespace string + Name string + // Identity is this process's election holder identity, unique to it. + Identity string + // Buckets are emptied when a hold ends. + Buckets *Buckets + // Hold overrides RecoveryHold; tests only. + Hold time.Duration + // Now returns the current time; nil selects time.Now. + Now func() time.Time + + mu sync.Mutex + epoch Epoch + active bool + until time.Time + epochCtx context.Context + cancel context.CancelFunc +} + +func (a *Authority) now() time.Time { + if a.Now != nil { + return a.Now() + } + return time.Now() +} + +// Check confirms ownership and returns the current epoch and a context that +// ends when ownership is lost. Work admitted under the epoch should run +// within that context. The Lease read is not cut short by ctx, only by +// LeaseReadTimeout, so a caller that gives up mid-read is refused with +// Cancelled or DeadlineExceeded and leaves the authority's state alone. +func (a *Authority) Check(ctx context.Context) (Epoch, context.Context, error) { + epoch, err := ReadEpoch(context.WithoutCancel(ctx), a.Reader, a.Namespace, a.Name, a.now()) + if cerr := ctx.Err(); cerr != nil { + if errors.Is(cerr, context.DeadlineExceeded) { + return Epoch{}, nil, errcode.Status(errcode.DeadlineExceeded, "the caller's deadline passed") + } + return Epoch{}, nil, errcode.Status(errcode.Cancelled, "the caller cancelled") + } + now := a.now() + if err == nil && epoch.Holder != a.Identity { + err = errcode.Status(errcode.OwnershipLost, "this gateway does not hold the election lease") + } + a.mu.Lock() + defer a.mu.Unlock() + if err != nil { + a.loseLocked() + return Epoch{}, nil, err + } + if epoch != a.epoch || a.epochCtx == nil { + a.loseLocked() + a.epoch, a.until = epoch, now.Add(a.hold()) + a.epochCtx, a.cancel = context.WithCancel(context.Background()) + } + if !a.active { + if now.Before(a.until) { + return Epoch{}, nil, errcode.Retry(errcode.LimiterUnavailable, "the cell's limiter is in its recovery hold", + string(ScopeCell), a.until.Sub(now)) + } + a.Buckets.Reset(now) + a.active = true + } + return a.epoch, a.epochCtx, nil +} + +// WatchInterval is how often Watch confirms ownership. +const WatchInterval = time.Second + +// Watch calls Check every interval until ctx ends, so a lost or unreadable +// Lease cancels the epoch's work within an interval even when no admission +// or dispatch would check it, and the recovery hold starts when this +// process starts or acquires the election rather than at its first +// request. +func (a *Authority) Watch(ctx context.Context, interval time.Duration) { + t := time.NewTicker(interval) + defer t.Stop() + for { + _, _, _ = a.Check(ctx) + select { + case <-ctx.Done(): + return + case <-t.C: + } + } +} + +func (a *Authority) hold() time.Duration { + if a.Hold > 0 { + return a.Hold + } + return RecoveryHold +} + +// loseLocked ends the current epoch: its work is cancelled and the next +// valid read starts a new hold. +func (a *Authority) loseLocked() { + if a.cancel != nil { + a.cancel() + } + a.epoch, a.active, a.epochCtx, a.cancel = Epoch{}, false, nil, nil +} diff --git a/internal/fabric/gateway/limit/buckets.go b/internal/fabric/gateway/limit/buckets.go new file mode 100644 index 000000000..a346ba472 --- /dev/null +++ b/internal/fabric/gateway/limit/buckets.go @@ -0,0 +1,237 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package limit + +import ( + "math" + "net/netip" + "sync" + "time" + + "go.datum.net/galactic/internal/fabric/errcode" +) + +// Scope names the limit that refused a charge, as throttling metadata +// reports it. It never carries a project or destination. +type Scope string + +// Scopes. +const ( + ScopeCell Scope = "cell" + ScopeProject Scope = "project" + ScopeDestination Scope = "destination" + ScopeQueue Scope = "queue" +) + +// class is one family of buckets sharing a rate and, for keyed families, a +// key bound. +type class int + +const ( + requestCell class = iota + requestProject + packetCell + packetPrincipal + packetHost + packetPrefix +) + +type bucketKey struct { + class class + id string +} + +type bucket struct { + tokens float64 + at time.Time +} + +// Buckets are the cell's request and packet token buckets. Every bucket +// starts empty at the instant of the last Reset and refills from there, so a +// key first seen later starts with at most min(burst, rate × time since the +// reset). A charge debits every bucket it names or none, and never takes a +// bucket below zero. A key is discarded only once its bucket has fully +// refilled, so no debt is ever forgotten; when a key family is full of +// buckets still refilling, a new key is refused with LimiterUnavailable. +type Buckets struct { + limits Limits + + mu sync.Mutex + start time.Time + buckets map[bucketKey]*bucket + // keyed counts the buckets of the project/principal and destination + // families. + projectKeys, destinationKeys int +} + +// NewBuckets returns empty buckets, refilling from now. +func NewBuckets(l Limits, now time.Time) *Buckets { + b := &Buckets{limits: l} + b.Reset(now) + return b +} + +// Reset empties every bucket and restarts refilling from now. +func (b *Buckets) Reset(now time.Time) { + b.mu.Lock() + defer b.mu.Unlock() + b.start = now + b.buckets = map[bucketKey]*bucket{} + b.projectKeys, b.destinationKeys = 0, 0 +} + +func (b *Buckets) rate(c class) Rate { + switch c { + case requestCell: + return b.limits.RequestCell + case requestProject: + return b.limits.RequestProject + case packetCell: + return b.limits.PacketCell + case packetPrincipal: + return b.limits.PacketPrincipal + case packetHost: + return b.limits.PacketHost + } + return b.limits.PacketPrefix +} + +func scopeOf(c class) Scope { + switch c { + case requestCell, packetCell: + return ScopeCell + case requestProject, packetPrincipal: + return ScopeProject + } + return ScopeDestination +} + +// level returns k's tokens at now. +func (b *Buckets) level(k bucketKey, bk *bucket, now time.Time) float64 { + r := b.rate(k.class) + elapsed := max(now.Sub(bk.at).Seconds(), 0) + return math.Min(r.Burst, bk.tokens+r.PerSecond*elapsed) +} + +// ChargeRequest debits one request token from the cell and from project. +func (b *Buckets) ChargeRequest(project string, now time.Time) error { + return b.charge(1, now, bucketKey{requestCell, ""}, bucketKey{requestProject, project}) +} + +// ChargePackets debits packets from the cell, from principal when it is not +// empty, and from dst's host and containing prefix (IPv4 /24, IPv6 /64). +func (b *Buckets) ChargePackets(principal string, dst netip.Addr, packets int, now time.Time) error { + host, prefix := DestinationKeys(dst) + keys := []bucketKey{{packetCell, ""}, {packetHost, host}, {packetPrefix, prefix}} + if principal != "" { + keys = append(keys, bucketKey{packetPrincipal, principal}) + } + return b.charge(float64(packets), now, keys...) +} + +// DestinationKeys returns dst's host key and its containing prefix key. +func DestinationKeys(dst netip.Addr) (host, prefix string) { + dst = dst.Unmap() + bits := 64 + if dst.Is4() { + bits = 24 + } + p, _ := dst.Prefix(bits) + return netip.PrefixFrom(dst, dst.BitLen()).String(), p.String() +} + +// charge debits n from every bucket in keys, or from none. A shortage is +// refused with Throttled and a retry delay of the largest deficit/rate +// among the short buckets, scoped to that bucket's family. +func (b *Buckets) charge(n float64, now time.Time, keys ...bucketKey) error { + b.mu.Lock() + defer b.mu.Unlock() + found := make([]*bucket, len(keys)) + for i, k := range keys { + bk, err := b.lookup(k, now) + if err != nil { + return err + } + found[i] = bk + } + var wait float64 + var scope Scope + for i, k := range keys { + if have := b.level(k, found[i], now); have < n { + if d := (n - have) / b.rate(k.class).PerSecond; d > wait { + wait, scope = d, scopeOf(k.class) + } + } + } + if scope != "" { + return errcode.Retry(errcode.Throttled, "an admission budget is exhausted", string(scope), + time.Duration(math.Ceil(wait*float64(time.Second)))) + } + for i, k := range keys { + // A caller holding an older now never moves a bucket's clock back. + at := now + if found[i].at.After(at) { + at = found[i].at + } + found[i].tokens = b.level(k, found[i], at) - n + found[i].at = at + } + return nil +} + +// lookup returns k's bucket, creating it empty at the reset instant. A full +// key family first discards one fully refilled bucket; with none, the new +// key is refused. +func (b *Buckets) lookup(k bucketKey, now time.Time) (*bucket, error) { + if bk, ok := b.buckets[k]; ok { + return bk, nil + } + count, limit := b.family(k.class) + if count != nil && *count >= limit && !b.evict(k.class, now) { + return nil, errcode.Retry(errcode.LimiterUnavailable, "the cell's limiter has no room for a new key", + string(scopeOf(k.class)), time.Second) + } + bk := &bucket{at: b.start} + b.buckets[k] = bk + if count != nil { + *count++ + } + return bk, nil +} + +// family returns the counter and bound of c's key family, or nil for a +// fixed cell bucket. +func (b *Buckets) family(c class) (*int, int) { + switch c { + case requestProject, packetPrincipal: + return &b.projectKeys, b.limits.ProjectKeys + case packetHost, packetPrefix: + return &b.destinationKeys, b.limits.DestinationKeys + } + return nil, 0 +} + +// evict discards one fully refilled bucket of c's key family. +func (b *Buckets) evict(c class, now time.Time) bool { + count, _ := b.family(c) + for k, bk := range b.buckets { + if other, _ := b.family(k.class); other != count { + continue + } + if b.level(k, bk, now) >= b.rate(k.class).Burst { + delete(b.buckets, k) + *count-- + return true + } + } + return false +} + +// Keys returns how many project/principal and destination buckets exist. +func (b *Buckets) Keys() (project, destination int) { + b.mu.Lock() + defer b.mu.Unlock() + return b.projectKeys, b.destinationKeys +} diff --git a/internal/fabric/gateway/limit/limit_test.go b/internal/fabric/gateway/limit/limit_test.go new file mode 100644 index 000000000..ff3701fce --- /dev/null +++ b/internal/fabric/gateway/limit/limit_test.go @@ -0,0 +1,439 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package limit + +import ( + "context" + "errors" + "fmt" + "math" + "net/netip" + "strings" + "testing" + "time" + + coordinationv1 "k8s.io/api/coordination/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + "go.datum.net/galactic/internal/fabric/errcode" +) + +var t0 = time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC) + +const ( + leaseNS = "ns" + leaseName = "lease" + holderA = "gw-a_1" +) + +func wantCode(t *testing.T, err error, code errcode.Code) { + t.Helper() + if got := errcode.Of(err); got != code { + t.Fatalf("code = %q (%v), want %q", got, err, code) + } +} + +func TestDefaultsValidate(t *testing.T) { + if err := Defaults().Validate(); err != nil { + t.Fatalf("defaults invalid: %v", err) + } +} + +func TestValidateRejects(t *testing.T) { + cases := map[string]func(*Limits){ + "zero rate": func(l *Limits) { l.PacketCell.PerSecond = 0 }, + "NaN rate": func(l *Limits) { l.PacketCell.PerSecond = math.NaN() }, + "infinite rate": func(l *Limits) { l.PacketHost.PerSecond = math.Inf(1) }, + "negative burst": func(l *Limits) { l.RequestCell.Burst = -1 }, + "burst over 120 s": func(l *Limits) { l.PacketHost = Rate{PerSecond: 1, Burst: 121} }, + "short burst": func(l *Limits) { l.PacketPrefix.Burst = 19 }, + "project above cell": func(l *Limits) { l.RequestProject.Burst = 9 }, + "principal above cell": func(l *Limits) { l.PacketPrincipal.PerSecond = 101 }, + "slots above max": func(l *Limits) { l.Slots = 9 }, + "principal slots": func(l *Limits) { l.PrincipalSlots = 9 }, + "queue above max": func(l *Limits) { l.Queue = 257 }, + "principal queue": func(l *Limits) { l.Queue, l.PrincipalQueue = 16, 32 }, + "streams": func(l *Limits) { l.ProjectStreams = 17 }, + "project keys": func(l *Limits) { l.ProjectKeys = MaxProjectKeys + 1 }, + "destination keys": func(l *Limits) { l.DestinationKeys = 0 }, + "attempt bytes": func(l *Limits) { l.AttemptBytes = MaxAttemptBytes + 1 }, + "queue wait": func(l *Limits) { l.QueueWait = 11 * time.Second }, + } + for name, mod := range cases { + t.Run(name, func(t *testing.T) { + l := Defaults() + mod(&l) + if err := l.Validate(); err == nil { + t.Fatal("invalid limits accepted") + } + }) + } +} + +func TestBucketsStartEmptyAndRefill(t *testing.T) { + b := NewBuckets(Defaults(), t0) + // Project: 0.2/s, burst 2. Nothing at the reset instant. + err := b.ChargeRequest("p", t0) + wantCode(t, err, errcode.Throttled) + if d, _ := errcode.RetryDelay(err); d != 5*time.Second { + t.Fatalf("retry = %s, want 5s (1 token at 0.2/s)", d) + } + md := errcode.Metadata(err) + if md[errcode.MetadataScope] != "project" || md[errcode.MetadataExecutionStarted] != "false" { + t.Fatalf("metadata = %v", md) + } + // A refused charge debits nothing, the cell bucket included. + if err := b.ChargeRequest("p", t0.Add(10*time.Second)); err != nil { + t.Fatal(err) + } + if err := b.ChargeRequest("p", t0.Add(10*time.Second)); err != nil { + t.Fatalf("second token: %v", err) + } + wantCode(t, b.ChargeRequest("p", t0.Add(10*time.Second)), errcode.Throttled) + // Another project is independent, but shares the cell's 2/s. + if err := b.ChargeRequest("q", t0.Add(10*time.Second)); err != nil { + t.Fatal(err) + } +} + +func TestBucketsRetryIsLargestDeficit(t *testing.T) { + b := NewBuckets(Defaults(), t0) + dst := netip.MustParseAddr("192.0.2.10") + // At 1 s: cell 100, principal 20, host 20, prefix 40. A traceroute (20) + // fits once; then host and principal are 20 short (1 s at 20/s) and + // prefix 0 short. + now := t0.Add(time.Second) + if err := b.ChargePackets("p", dst, TraceroutePackets, now); err != nil { + t.Fatal(err) + } + err := b.ChargePackets("p", dst, TraceroutePackets, now) + wantCode(t, err, errcode.Throttled) + if d, _ := errcode.RetryDelay(err); d != time.Second { + t.Fatalf("retry = %s, want 1s", d) + } + // Another host in the same /24 under another principal draws on the + // prefix's remaining 20. + if err := b.ChargePackets("q", netip.MustParseAddr("192.0.2.11"), TraceroutePackets, now); err != nil { + t.Fatal(err) + } + err = b.ChargePackets("r", netip.MustParseAddr("192.0.2.12"), TraceroutePackets, now) + wantCode(t, err, errcode.Throttled) + if errcode.Metadata(err)[errcode.MetadataScope] != "destination" { + t.Fatalf("scope = %v, want destination", errcode.Metadata(err)) + } +} + +func TestDestinationKeys(t *testing.T) { + for in, want := range map[string][2]string{ + "192.0.2.10": {"192.0.2.10/32", "192.0.2.0/24"}, + "::ffff:192.0.2.10": {"192.0.2.10/32", "192.0.2.0/24"}, + "2001:db8:1:2:3::4": {"2001:db8:1:2:3::4/128", "2001:db8:1:2::/64"}, + "2001:db8::1": {"2001:db8::1/128", "2001:db8::/64"}, + "2001:db8:0:ffff::1": {"2001:db8:0:ffff::1/128", "2001:db8:0:ffff::/64"}, + } { + h, p := DestinationKeys(netip.MustParseAddr(in)) + if h != want[0] || p != want[1] { + t.Errorf("%s: %s %s, want %v", in, h, p, want) + } + } +} + +func TestBucketsKeyBoundNeverEvictsDebt(t *testing.T) { + l := Defaults() + l.ProjectKeys = 2 + b := NewBuckets(l, t0) + now := t0.Add(time.Minute) + for _, p := range []string{"a", "b"} { + if err := b.ChargeRequest(p, now); err != nil { + t.Fatal(err) + } + } + // Both keys are refilling: a third is refused rather than evicting one. + wantCode(t, b.ChargeRequest("c", now), errcode.LimiterUnavailable) + if p, _ := b.Keys(); p != 2 { + t.Fatalf("project keys = %d", p) + } + // Once "a" and "b" have refilled (1 token at 0.2/s = 5 s), one is + // discarded for "c". + later := now.Add(5 * time.Second) + if err := b.ChargeRequest("c", later); err != nil { + t.Fatalf("after refill: %v", err) + } + if p, _ := b.Keys(); p != 2 { + t.Fatalf("project keys = %d", p) + } +} + +func TestBucketsReset(t *testing.T) { + b := NewBuckets(Defaults(), t0) + now := t0.Add(time.Hour) + if err := b.ChargeRequest("p", now); err != nil { + t.Fatal(err) + } + b.Reset(now) + wantCode(t, b.ChargeRequest("p", now), errcode.Throttled) +} + +// TestPacketEnvelope charges a fan-out of mixed projects and hosts in one +// prefix every 100 ms for a minute and checks that, for every window of +// length T, the prefix bucket admitted at most burst + rate × T packets. +func TestPacketEnvelope(t *testing.T) { + l := Defaults() + b := NewBuckets(l, t0) + type charge struct { + at time.Time + n int + } + var admitted []charge + for i := range 600 { + now := t0.Add(time.Duration(i) * 100 * time.Millisecond) + for j := range 8 { + dst := netip.AddrFrom4([4]byte{198, 51, 100, byte(j)}) + if b.ChargePackets(fmt.Sprintf("project-%d", (i+j)%5), dst, TraceroutePackets, now) == nil { + admitted = append(admitted, charge{now, TraceroutePackets}) + } + } + } + r := l.PacketPrefix + for i := range admitted { + sum := 0 + for j := i; j < len(admitted); j++ { + sum += admitted[j].n + window := admitted[j].at.Sub(admitted[i].at).Seconds() + if float64(sum) > r.Burst+r.PerSecond*window+1e-9 { + t.Fatalf("%d packets in %.1f s exceeds %g + %g×T", sum, window, r.Burst, r.PerSecond) + } + } + } + if len(admitted) == 0 { + t.Fatal("nothing admitted") + } +} + +func TestAttempts(t *testing.T) { + l := Defaults() + l.Attempts = 2 + a := NewAttempts(l) + exp := t0.Add(30 * time.Second) + if err := a.Register("k1", "d1", exp, t0); err != nil { + t.Fatal(err) + } + wantCode(t, a.Register("k1", "d1", exp, t0), errcode.DuplicateRequest) + wantCode(t, a.Register("k1", "d2", exp, t0), errcode.DuplicateConflict) + if err := a.Register("k2", "d", exp, t0); err != nil { + t.Fatal(err) + } + // Full of live keys: fail closed. + wantCode(t, a.Register("k3", "d", exp, t0), errcode.LimiterUnavailable) + // A key lives until expiry + 2 s. + wantCode(t, a.Register("k1", "d1", exp, exp.Add(time.Second)), errcode.DuplicateRequest) + if err := a.Register("k3", "d", exp.Add(time.Minute), exp.Add(AttemptGrace)); err != nil { + t.Fatalf("after expiry: %v", err) + } + if a.Len() != 1 { + t.Fatalf("len = %d after purge", a.Len()) + } +} + +func TestAttemptsByteBound(t *testing.T) { + l := Defaults() + l.AttemptBytes = 200 + a := NewAttempts(l) + exp := t0.Add(time.Minute) + if err := a.Register(strings.Repeat("k", 100), "d", exp, t0); err != nil { + t.Fatal(err) + } + wantCode(t, a.Register(strings.Repeat("j", 100), "d", exp, t0), errcode.LimiterUnavailable) +} + +// leaseClient serves the election Lease and can fail its reads. +type leaseClient struct { + client.Client + fail bool +} + +func newLease(t *testing.T, holder string, renew time.Time) *leaseClient { + t.Helper() + s := runtime.NewScheme() + _ = clientgoscheme.AddToScheme(s) + lc := &leaseClient{} + lc.Client = fake.NewClientBuilder().WithScheme(s).WithObjects(&coordinationv1.Lease{ + ObjectMeta: metav1.ObjectMeta{Namespace: leaseNS, Name: leaseName, UID: "u1"}, + Spec: coordinationv1.LeaseSpec{ + HolderIdentity: ptr.To(holder), LeaseDurationSeconds: ptr.To[int32](15), + RenewTime: &metav1.MicroTime{Time: renew}, + }, + }).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, + opts ...client.GetOption) error { + if lc.fail { + return errors.New("api unavailable") + } + return c.Get(ctx, key, obj, opts...) + }, + }).Build() + return lc +} + +// set replaces the Lease with one of uid held by holderA, renewed at renew. +func (lc *leaseClient) set(t *testing.T, uid string, renew time.Time) { + t.Helper() + old := &coordinationv1.Lease{ObjectMeta: metav1.ObjectMeta{Namespace: leaseNS, Name: leaseName}} + if err := lc.Delete(t.Context(), old); err != nil { + t.Fatal(err) + } + if err := lc.Create(t.Context(), &coordinationv1.Lease{ + ObjectMeta: metav1.ObjectMeta{Namespace: leaseNS, Name: leaseName, UID: types.UID(uid)}, + Spec: coordinationv1.LeaseSpec{ + HolderIdentity: ptr.To(holderA), LeaseDurationSeconds: ptr.To[int32](15), + RenewTime: &metav1.MicroTime{Time: renew}, + }, + }); err != nil { + t.Fatal(err) + } +} + +type clock struct{ now time.Time } + +func (c *clock) Now() time.Time { return c.now } + +func TestAuthorityRecoveryHold(t *testing.T) { + clk := &clock{now: t0} + lc := newLease(t, holderA, t0) + buckets := NewBuckets(Defaults(), t0.Add(-time.Hour)) + a := &Authority{Reader: lc, Namespace: leaseNS, Name: leaseName, Identity: holderA, Buckets: buckets, Now: clk.Now} + + // Process start: held for the full 125 s. + _, _, err := a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + if d, _ := errcode.RetryDelay(err); d != RecoveryHold { + t.Fatalf("remaining hold = %s", d) + } + clk.now = t0.Add(RecoveryHold - time.Millisecond) + lc.set(t, "u1", clk.now) + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + + // After the hold: admitted, and the buckets restart empty from now. + clk.now = t0.Add(RecoveryHold) + lc.set(t, "u1", clk.now) + epoch, ctx, err := a.Check(t.Context()) + if err != nil { + t.Fatal(err) + } + if epoch.String() != "u1/gw-a_1" { + t.Fatalf("epoch = %s", epoch) + } + wantCode(t, buckets.ChargeRequest("p", clk.now), errcode.Throttled) + + // A failed read refuses, cancels the epoch's work, and the next valid + // read holds again. + lc.fail = true + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.OwnershipLost) + if ctx.Err() == nil { + t.Fatal("epoch context survived a failed lease read") + } + lc.fail = false + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) +} + +func TestAuthorityRefusesOtherHolderAndExpiry(t *testing.T) { + clk := &clock{now: t0} + lc := newLease(t, "gw-b_2", t0) + a := &Authority{Reader: lc, Namespace: leaseNS, Name: leaseName, Identity: holderA, + Buckets: NewBuckets(Defaults(), t0), Now: clk.Now, Hold: time.Second} + _, _, err := a.Check(t.Context()) + wantCode(t, err, errcode.OwnershipLost) + + lc.set(t, "u1", t0) + if _, _, err := a.Check(t.Context()); errcode.Of(err) != errcode.LimiterUnavailable { + t.Fatalf("first check: %v", err) + } + clk.now = t0.Add(time.Second) + _, ctx, err := a.Check(t.Context()) + if err != nil { + t.Fatal(err) + } + // The term lapses without renewal. + clk.now = t0.Add(16 * time.Second) + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.OwnershipLost) + if ctx.Err() == nil { + t.Fatal("epoch context survived an expired lease") + } +} + +func TestAuthorityNewEpochHolds(t *testing.T) { + clk := &clock{now: t0} + lc := newLease(t, holderA, t0) + a := &Authority{Reader: lc, Namespace: leaseNS, Name: leaseName, Identity: holderA, + Buckets: NewBuckets(Defaults(), t0), Now: clk.Now, Hold: time.Second} + _, _, _ = a.Check(t.Context()) + clk.now = t0.Add(time.Second) + lc.set(t, "u1", clk.now) + _, ctx, err := a.Check(t.Context()) + if err != nil { + t.Fatal(err) + } + // The Lease is recreated under the same holder: a new epoch. + lc.set(t, "u2", clk.now) + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + if ctx.Err() == nil { + t.Fatal("old epoch's context survived a new epoch") + } +} + +// A caller that gives up during the Lease read is refused for itself +// alone: the authority stays active and its epoch's work keeps running. +func TestAuthorityIgnoresCallerCancellation(t *testing.T) { + clk := &clock{now: t0} + lc := newLease(t, holderA, t0) + var block chan struct{} + reader := interceptor.NewClient(lc.Client.(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, + opts ...client.GetOption) error { + if block != nil { + <-block + } + return c.Get(ctx, key, obj, opts...) + }, + }) + a := &Authority{Reader: reader, Namespace: leaseNS, Name: leaseName, Identity: holderA, + Buckets: NewBuckets(Defaults(), t0), Now: clk.Now, Hold: time.Second} + _, _, _ = a.Check(t.Context()) + clk.now = t0.Add(time.Second) + _, epochCtx, err := a.Check(t.Context()) + if err != nil { + t.Fatal(err) + } + + block = make(chan struct{}) + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error, 1) + go func() { + _, _, err := a.Check(ctx) + done <- err + }() + cancel() + time.Sleep(10 * time.Millisecond) + close(block) + wantCode(t, <-done, errcode.Cancelled) + if epochCtx.Err() != nil { + t.Fatal("a caller's cancellation cancelled the epoch's work") + } + if _, _, err := a.Check(t.Context()); err != nil { + t.Fatalf("authority left its active state: %v", err) + } +} diff --git a/internal/fabric/gateway/limit/limits.go b/internal/fabric/gateway/limit/limits.go new file mode 100644 index 000000000..449cff6c5 --- /dev/null +++ b/internal/fabric/gateway/limit/limits.go @@ -0,0 +1,155 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package limit holds the cell gateway's aggregate admission state: request +// and packet token buckets, the live attempt keys, and the election +// authority that decides when that state may be used. The leader keeps it +// all in bounded memory; followers keep none. +// +// Every probe a cell runs, whether for a service project, a FabricQuery or an +// operator, charges its worst-case packets to the cell, its principal, its +// destination host and its destination prefix; every request or node job +// takes an execution slot. Nothing charged is refunded. After the process +// acquires or loses the election it admits nothing for a recovery hold, then +// starts every bucket empty. +package limit + +import ( + "errors" + "fmt" + "math" + "time" + + "go.datum.net/galactic/internal/fabric/query" +) + +// Rate is a token bucket's sustained refill rate, in tokens per second, and +// its burst. +type Rate struct { + PerSecond float64 + Burst float64 +} + +// Probe packet costs, charged as each probe's worst case. +const ( + PingPackets = query.PingCount + TraceroutePackets = query.TracerouteMaxHops * query.TracerouteProbesPerHop +) + +// Hard bounds on the limiter's own memory and on what one request may hold. +// A configuration may lower them, never raise them. +const ( + MaxProjectKeys = 4096 + MaxDestinationKeys = 16384 + MaxAttempts = 4096 + MaxAttemptBytes = 2 << 20 + MaxSlots = 8 + MaxQueue = 256 + MaxStreams = 16 + // MaxBurstSeconds bounds every bucket's burst/rate, so the recovery + // hold also clears the largest token debt a prior epoch could leave. + MaxBurstSeconds = 120 + // MaxQueueWait bounds a node job's wait for an execution slot. + MaxQueueWait = 10 * time.Second +) + +// Limits are the cell's aggregate admission settings. +type Limits struct { + // RequestCell and RequestProject charge one token per service request. + RequestCell, RequestProject Rate + // PacketCell, PacketPrincipal, PacketHost and PacketPrefix charge each + // probe's worst-case packets; PacketPrincipal is a project's or a direct + // operator's budget. + PacketCell, PacketPrincipal, PacketHost, PacketPrefix Rate + // Slots and PrincipalSlots bound active node jobs in the cell and per + // principal. + Slots, PrincipalSlots int + // Queue and PrincipalQueue bound queued node jobs in the cell and per + // principal. + Queue, PrincipalQueue int + // Streams and ProjectStreams bound live service streams in the cell and + // per project, queued and draining ones included. + Streams, ProjectStreams int + // QueueWait bounds a node job's wait for an execution slot. + QueueWait time.Duration + // ProjectKeys and DestinationKeys bound the limiter's bucket maps. + ProjectKeys, DestinationKeys int + // Attempts and AttemptBytes bound the live attempt-key cache. + Attempts, AttemptBytes int +} + +// Defaults returns the contract's initial limits. +func Defaults() Limits { + return Limits{ + RequestCell: Rate{PerSecond: 2, Burst: 8}, + RequestProject: Rate{PerSecond: 0.2, Burst: 2}, + PacketCell: Rate{PerSecond: 100, Burst: 640}, + PacketPrincipal: Rate{PerSecond: 20, Burst: 640}, + PacketHost: Rate{PerSecond: 20, Burst: 640}, + PacketPrefix: Rate{PerSecond: 40, Burst: 640}, + Slots: MaxSlots, + PrincipalSlots: 2, + Queue: MaxQueue, + PrincipalQueue: 32, + Streams: MaxStreams, + ProjectStreams: 2, + QueueWait: MaxQueueWait, + ProjectKeys: MaxProjectKeys, + DestinationKeys: MaxDestinationKeys, + Attempts: MaxAttempts, + AttemptBytes: MaxAttemptBytes, + } +} + +// Validate refuses limits that break a cross-field rule: a non-positive +// rate, a burst/rate above MaxBurstSeconds, a packet burst that cannot fund +// one traceroute, a per-project or per-principal limit above its cell's, or +// any bound above its hard maximum. +func (l Limits) Validate() error { + var errs []error + rate := func(name string, r Rate, minBurst float64) { + switch { + case !(r.PerSecond > 0) || !(r.Burst > 0) || math.IsInf(r.PerSecond, 0) || math.IsInf(r.Burst, 0): + errs = append(errs, fmt.Errorf("%s: rate and burst must be positive and finite", name)) + case r.Burst/r.PerSecond > MaxBurstSeconds: + errs = append(errs, fmt.Errorf("%s: burst/rate exceeds %d s", name, MaxBurstSeconds)) + case r.Burst < minBurst: + errs = append(errs, fmt.Errorf("%s: burst %g cannot fund a %g-token charge", name, r.Burst, minBurst)) + } + } + rate("request cell", l.RequestCell, 1) + rate("request project", l.RequestProject, 1) + rate("packet cell", l.PacketCell, TraceroutePackets) + rate("packet principal", l.PacketPrincipal, TraceroutePackets) + rate("packet host", l.PacketHost, TraceroutePackets) + rate("packet prefix", l.PacketPrefix, TraceroutePackets) + within := func(name string, inner, outer Rate) { + if inner.PerSecond > outer.PerSecond || inner.Burst > outer.Burst { + errs = append(errs, fmt.Errorf("%s exceeds its cell limit", name)) + } + } + within("request project", l.RequestProject, l.RequestCell) + within("packet principal", l.PacketPrincipal, l.PacketCell) + within("packet host", l.PacketHost, l.PacketCell) + within("packet prefix", l.PacketPrefix, l.PacketCell) + bound := func(name string, v, lo, hi int) { + if v < lo || v > hi { + errs = append(errs, fmt.Errorf("%s must be %d to %d, not %d", name, lo, hi, v)) + } + } + bound("slots", l.Slots, 1, MaxSlots) + bound("principal slots", l.PrincipalSlots, 1, l.Slots) + bound("queue", l.Queue, 1, MaxQueue) + bound("principal queue", l.PrincipalQueue, 1, l.Queue) + bound("streams", l.Streams, 1, MaxStreams) + bound("project streams", l.ProjectStreams, 1, l.Streams) + bound("project keys", l.ProjectKeys, 1, MaxProjectKeys) + bound("destination keys", l.DestinationKeys, 2, MaxDestinationKeys) + bound("attempts", l.Attempts, 1, MaxAttempts) + bound("attempt bytes", l.AttemptBytes, 1, MaxAttemptBytes) + if l.QueueWait <= 0 || l.QueueWait > MaxQueueWait { + errs = append(errs, fmt.Errorf("queue wait must be positive and at most %s", MaxQueueWait)) + } + return errors.Join(errs...) +} diff --git a/internal/fabric/gateway/load_test.go b/internal/fabric/gateway/load_test.go new file mode 100644 index 000000000..1ee05d800 --- /dev/null +++ b/internal/fabric/gateway/load_test.go @@ -0,0 +1,263 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "fmt" + "sync" + "testing" + "time" + + servicev1 "go.datum.net/galactic/api/fabric/service/v1" + fabricv1 "go.datum.net/galactic/api/fabric/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/node" + "go.datum.net/galactic/internal/fabric/query" +) + +// concurrency records running node jobs per principal, and the order in +// which principals' jobs started. +type concurrency struct { + mu sync.Mutex + principal map[string]string // request ID -> principal + running map[string]int + maxRunning map[string]int + total, max int + starts []string +} + +func newConcurrency() *concurrency { + return &concurrency{principal: map[string]string{}, running: map[string]int{}, maxRunning: map[string]int{}} +} + +func (c *concurrency) assign(requestID, principal string) { + c.mu.Lock() + defer c.mu.Unlock() + c.principal[requestID] = principal +} + +func (c *concurrency) answer(name string) routerAnswer { + return func(_ context.Context, req *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) { + c.mu.Lock() + p := c.principal[req.GetRequestId()] + c.running[p]++ + c.total++ + c.maxRunning[p] = max(c.maxRunning[p], c.running[p]) + c.max = max(c.max, c.total) + c.starts = append(c.starts, p) + c.mu.Unlock() + time.Sleep(10 * time.Millisecond) + c.mu.Lock() + c.running[p]-- + c.total-- + c.mu.Unlock() + return pingObservation(name, 3), nil + } +} + +var loadRouters = []string{"router-1", "router-2", "router-3", "router-4", "router-5", "router-6"} + +// TestFairnessUnderLoad queues 10 service streams from five projects and two +// FabricQuery runs behind a full executor, then lets them go. Every job +// completes, no principal ever holds more than its two slots nor the cell +// more than eight, every principal starts within the first round of grants, +// and a third concurrent stream from one project is refused. +func TestFairnessUnderLoad(t *testing.T) { + c := newConcurrency() + answers := map[string]routerAnswer{} + for _, n := range loadRouters { + answers[n] = c.answer(n) + } + nodes := &routerNodes{answers: answers} + svc := newService(t, routerPods(loadRouters...), nodes, 8) + l := roomyLimits() + l.ProjectStreams = limit.Defaults().ProjectStreams + withAdmission(t, svc, l) + svc.Runner.QueueWait = limit.MaxQueueWait + e := svc.Runner.Executor + + // Fill all eight slots with four plug principals. + plugs := make([]func(), 0, 8) + for i := range 8 { + rel, err := e.Acquire(t.Context(), fmt.Sprintf("plug-%d", i/2), false) + if err != nil { + t.Fatal(err) + } + plugs = append(plugs, rel) + } + + projects := []string{"project-0", "project-1", "project-2", "project-3", "project-4"} + type stream struct { + events <-chan *servicev1.DiagnosticEvent + done <-chan error + } + streams := make([]stream, 0, 2*len(projects)) + n := 0 + for _, p := range projects { + for range 2 { + n++ + req := requestFor(p, n, nil) + c.assign(req.GetRequestId(), p) + ev, done := run(t, svc, req, 0) + streams = append(streams, stream{ev, done}) + } + } + // FabricQuery runs share the executor under their own principal. + ping := node.QueryFromProto(&fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_PING, Target: probeTarget6, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV6}) + routers := make([]Node, 0, len(loadRouters)) + for _, r := range loadRouters { + routers = append(routers, Node{Name: r, PodUID: "pod-" + r, Selected: true}) + } + var fq sync.WaitGroup + var fqOutcomes [][]Outcome + var fqMu sync.Mutex + for i := range 2 { + id := fmt.Sprintf("fq-%d", i) + c.assign(id, "ns/cluster") + fq.Go(func() { + out := svc.Runner.Run(t.Context(), "ns/cluster", id, ping, routers, nil, time.Now().Add(30*time.Second)) + fqMu.Lock() + fqOutcomes = append(fqOutcomes, out) + fqMu.Unlock() + }) + } + waitDepth(t, e, 10*len(loadRouters)+2*len(loadRouters)) + + // A third live stream from one project is refused at once. + _, err := collect(t, svc, requestFor("project-0", 999, nil)) + wantRetry(t, err, errcode.QueueFull, "queue") + + for _, rel := range plugs { + rel() + } + for i, s := range streams { + var events []*servicev1.DiagnosticEvent + for ev := range s.events { + events = append(events, ev) + } + if err := <-s.done; err != nil { + t.Fatalf("stream %d: %v", i, err) + } + if _, _, cmp := checkGrammar(t, events); cmp.GetReason() != CompleteSucceeded { + t.Errorf("stream %d: %v", i, cmp) + } + } + fq.Wait() + for _, out := range fqOutcomes { + for _, o := range out { + if o.Err != nil { + t.Errorf("FabricQuery %s: %v", o.Node.Name, o.Err) + } + } + } + + c.mu.Lock() + defer c.mu.Unlock() + if c.max > 8 { + t.Errorf("%d jobs ran at once, above the cell's 8", c.max) + } + for p, m := range c.maxRunning { + if m > 2 { + t.Errorf("%s ran %d jobs at once, above its 2", p, m) + } + } + principals := append(append([]string{}, projects...), "ns/cluster") + for _, p := range principals { + first := -1 + for i, s := range c.starts { + if s == p { + first = i + break + } + } + if first < 0 || first >= 2*len(principals) { + t.Errorf("%s first started at grant %d of %d", p, first, len(c.starts)) + } + } + if len(c.starts) != 12*len(loadRouters) { + t.Errorf("%d jobs ran, want %d", len(c.starts), 12*len(loadRouters)) + } +} + +func traceroute(target string) *fabricv1.Query { + return &fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_TRACEROUTE, Target: target} +} + +// TestDestinationPrefixAcrossProjects sends traceroutes from three projects +// to three hosts of one /64: the prefix budget binds whichever project asks. +func TestDestinationPrefixAcrossProjects(t *testing.T) { + svc := newService(t, routerPods(routerA), &routerNodes{}, 8) + l := roomyLimits() + l.PacketPrefix = limit.Rate{PerSecond: 1, Burst: 2 * limit.TraceroutePackets} + withAdmission(t, svc, l) + for i, target := range []string{probeTarget6, "2001:db8::2", "2001:db8::3"} { + events, err := collect(t, svc, requestFor(fmt.Sprintf("project-%d", i), i, func(r *runReq) { + r.Query = traceroute(target) + })) + if err != nil { + t.Fatal(err) + } + _, outcomes, _ := checkGrammar(t, events) + throttled := outcomes[routerA].GetFailure().GetReason() == string(errcode.Throttled) + if throttled != (i == 2) { + t.Errorf("request %d to %s: %v", i, target, outcomes[routerA]) + } + } +} + +// TestAggregateBudgetsCoverEveryCaller charges a cell packet budget of three +// traceroutes from four callers, each with its own principal and +// destination prefix: the service, a FabricQuery, a direct operator through +// its node's permit, and an operator through the gateway. The fourth is +// refused at the cell scope whichever caller it is. +func TestAggregateBudgetsCoverEveryCaller(t *testing.T) { + nodes := &routerNodes{} + svc := newService(t, routerPods(routerA), nodes, 8) + l := roomyLimits() + small := limit.Rate{PerSecond: 0.5, Burst: 3 * limit.TraceroutePackets} + l.PacketCell, l.PacketPrincipal, l.PacketHost, l.PacketPrefix = small, small, small, small + adm := withAdmission(t, svc, l) + permits := &Permits{Admission: adm, Executor: svc.Runner.Executor, Discoverer: svc.Discoverer, Elected: elected} + routers := []Node{{Name: routerA, PodUID: podA, Selected: true}} + expires := time.Now().Add(30 * time.Second) + + events, err := collect(t, svc, requestFor("project-a", 1, func(r *runReq) { r.Query = traceroute("2001:db8:1::1") })) + if err != nil { + t.Fatal(err) + } + if _, out, _ := checkGrammar(t, events); out[routerA].GetFailure() != nil { + t.Fatalf("service: %v", out[routerA]) + } + trace := func(target string) query.Query { + return node.QueryFromProto(&fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_TRACEROUTE, Target: target, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV6}) + } + out := svc.Runner.Run(t.Context(), "ns/cluster", "fq-1", trace("2001:db8:2::1"), routers, nil, expires) + if out[0].Err != nil { + t.Fatalf("FabricQuery: %v", out[0].Err) + } + req := pingPermitRequest(routerA, "alice", expires) + req.Query = &fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_TRACEROUTE, Target: probeTarget4, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV4} + if _, err := permits.RequestPermit(nodeCaller(t.Context(), routerA), req); err != nil { + t.Fatalf("direct operator: %v", err) + } + + out = svc.Runner.Run(t.Context(), "operator/bob", "op-1", trace("2001:db8:4::1"), routers, nil, expires) + if errcode.Of(out[0].Err) != errcode.Throttled || errcode.Metadata(out[0].Err)[errcode.MetadataScope] != "cell" { + t.Errorf("operator through the gateway past the cell budget: %v", out[0].Err) + } + req.Operator, req.Query.Target = "carol", "198.51.100.1" + _, err = permits.RequestPermit(nodeCaller(t.Context(), routerA), req) + if errcode.Of(err) != errcode.Throttled { + t.Errorf("direct operator past the cell budget: %v", err) + } + if n := nodes.total(); n != 2 { + t.Errorf("%d probes reached routers through the gateway, want 2", n) + } +} diff --git a/internal/fabric/gateway/permit.go b/internal/fabric/gateway/permit.go new file mode 100644 index 000000000..5d901ea28 --- /dev/null +++ b/internal/fabric/gateway/permit.go @@ -0,0 +1,226 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "errors" + "slices" + "sync" + "time" + + "google.golang.org/grpc/metadata" + + permitv1 "go.datum.net/galactic/api/fabric/permit/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/identity" + "go.datum.net/galactic/internal/fabric/node" + "go.datum.net/galactic/internal/fabric/query" +) + +// nodePodHeader carries the calling node identity's pod name on a permit +// call a follower forwards to the leader. +const nodePodHeader = forwardingPrefix + "node-pod" + +// Permits issues probe permits to nodes for the probes operators send them +// directly, from the same executor and packet budgets as the gateway's own +// node calls. A permit holds one execution slot of the operator's principal +// until the node releases it or the permit's deadline plus +// ReservationGrace passes. Only the leader issues; a follower forwards a +// call once. +type Permits struct { + permitv1.UnimplementedPermitServiceServer + + // Admission, when nil, refuses every permit: the cell does not enforce + // aggregate probe budgets. + Admission *Admission + Executor *Executor + // Discoverer maps a node identity's pod to its node. + Discoverer *Discoverer + Elected func() bool + Leader LeaderDialer + // Now returns the current time; nil selects time.Now. + Now func() time.Time + + mu sync.Mutex + held map[string]heldPermit +} + +type heldPermit struct { + node string + release func() +} + +func (p *Permits) now() time.Time { + if p.Now != nil { + return p.Now() + } + return time.Now() +} + +// callerPod returns the node identity's pod a call acts for: the caller +// itself, which must be in namespace, or, on a call a follower forwarded +// after that check, the pod it names. +func callerPod(ctx context.Context, namespace string) (string, error) { + id, ok := node.CallerFrom(ctx) + if ok && id.Role == identity.RoleNode && id.Namespace == namespace { + return id.Name, nil + } + if ok && id.Role == identity.RoleGateway { + md, _ := metadata.FromIncomingContext(ctx) + if v := md.Get(nodePodHeader); len(v) == 1 && v[0] != "" { + return v[0], nil + } + } + return "", errcode.Status(errcode.Unauthorized, "only nodes may request probe permits") +} + +// forwarded reports whether the call came from the gateway identity, which +// only a follower forwarding to the leader presents. +func forwarded(ctx context.Context) bool { + id, ok := node.CallerFrom(ctx) + return ok && id.Role == identity.RoleGateway +} + +// operatorPrincipal is the budget key of an operator, whether it calls the +// gateway or a node. Service project IDs cannot contain "/", and a +// FabricQuery's key starts with "fabricquery/", so the families cannot +// collide. +func operatorPrincipal(name string) string { return "operator/" + name } + +// forwardCtx hands the caller's pod to the leader. +func forwardCtx(ctx context.Context, pod string) context.Context { + return metadata.AppendToOutgoingContext(ctx, nodePodHeader, pod) +} + +// checkNode refuses a node name the caller's pod does not certify. +func (p *Permits) checkNode(ctx context.Context, pod, nodeName string) error { + pods, err := p.Discoverer.certPods(ctx) + if err != nil { + return errcode.Status(errcode.Internal, "node identities could not be read") + } + if !slices.Contains(pods[nodeName], pod) { + return errcode.Status(errcode.Unauthorized, "the caller's identity does not belong to node "+nodeName) + } + return nil +} + +// RequestPermit issues a permit for one probe on the calling node. +func (p *Permits) RequestPermit( + ctx context.Context, req *permitv1.RequestPermitRequest, +) (*permitv1.RequestPermitResponse, error) { + pod, err := callerPod(ctx, p.Discoverer.Namespace) + if err != nil { + return nil, err + } + if !p.Elected() { + if forwarded(ctx) { + return nil, errcode.Status(errcode.OwnershipLost, "this replica is not the leader") + } + conn, err := p.Leader.LeaderConn(ctx) + if err != nil { + return nil, errcode.Status(errcode.OwnershipLost, "no leader can issue probe permits") + } + return permitv1.NewPermitServiceClient(conn).RequestPermit(forwardCtx(ctx, pod), req) + } + if p.Admission == nil { + return nil, errcode.Status(errcode.LimiterUnavailable, "this cell does not issue probe permits") + } + if err := p.checkNode(ctx, pod, req.GetNode()); err != nil { + return nil, err + } + if _, err := identity.Parse(identity.Operator("cell", req.GetOperator()).URI()); err != nil || + req.GetOperator() == "" { + return nil, errcode.Status(errcode.InvalidQuery, "operator is not a valid identity name") + } + q := node.QueryFromProto(req.GetQuery()) + if c, err := query.Canonicalize(q); err != nil || c != q || !q.Type.Probe() { + return nil, errcode.Status(errcode.InvalidQuery, "query is not a canonical probe") + } + now := p.now() + if !req.GetExpiresAt().IsValid() || !req.GetExpiresAt().AsTime().After(now) { + return nil, errcode.Status(errcode.DeadlineExceeded, "the request has expired") + } + deadline := now.Add(query.MaxNodeExecution) + if e := req.GetExpiresAt().AsTime(); e.Before(deadline) { + deadline = e + } + principal := operatorPrincipal(req.GetOperator()) + + wait := min(p.Admission.Limits.QueueWait, deadline.Sub(now)) + actx, cancel := context.WithTimeout(ctx, wait) + defer cancel() + release, err := p.Executor.Acquire(actx, principal, false) + switch { + case errors.Is(err, ErrQueueFull): + return nil, errcode.Retry(errcode.QueueFull, "the cell's execution queue is full", string(limit.ScopeQueue), + time.Second) + case err != nil: + return nil, errcode.Status(errcode.QueueTimeout, "waited too long for a cell execution slot") + } + permit, err := p.Admission.permit(ctx, principal, req.GetRequestId(), req.GetNode(), q, deadline) + if err != nil { + release() + return nil, err + } + p.hold(permit.GetId(), req.GetNode(), release, deadline.Add(ReservationGrace)) + return &permitv1.RequestPermitResponse{Permit: permit}, nil +} + +// hold keeps a permit's slot until it is released or until. +func (p *Permits) hold(id, nodeName string, release func(), until time.Time) { + var once sync.Once + free := func() { once.Do(release) } + p.mu.Lock() + if p.held == nil { + p.held = map[string]heldPermit{} + } + p.held[id] = heldPermit{node: nodeName, release: free} + p.mu.Unlock() + holdUntil(func() { + p.mu.Lock() + delete(p.held, id) + p.mu.Unlock() + free() + }, until, p.now()) +} + +// ReleasePermit frees a finished permit's slot. Only the node the permit +// was issued to may release it; an unknown permit is not an error. +func (p *Permits) ReleasePermit( + ctx context.Context, req *permitv1.ReleasePermitRequest, +) (*permitv1.ReleasePermitResponse, error) { + pod, err := callerPod(ctx, p.Discoverer.Namespace) + if err != nil { + return nil, err + } + if !p.Elected() { + if forwarded(ctx) { + return nil, errcode.Status(errcode.OwnershipLost, "this replica is not the leader") + } + conn, err := p.Leader.LeaderConn(ctx) + if err != nil { + return nil, errcode.Status(errcode.OwnershipLost, "no leader holds probe permits") + } + return permitv1.NewPermitServiceClient(conn).ReleasePermit(forwardCtx(ctx, pod), req) + } + if p.Admission == nil { + return &permitv1.ReleasePermitResponse{}, nil + } + if err := p.checkNode(ctx, pod, req.GetNode()); err != nil { + return nil, err + } + p.mu.Lock() + h, ok := p.held[req.GetId()] + if ok && h.node == req.GetNode() { + delete(p.held, req.GetId()) + } + p.mu.Unlock() + if ok && h.node == req.GetNode() { + h.release() + } + return &permitv1.ReleasePermitResponse{}, nil +} diff --git a/internal/fabric/gateway/permit_test.go b/internal/fabric/gateway/permit_test.go new file mode 100644 index 000000000..e7273a886 --- /dev/null +++ b/internal/fabric/gateway/permit_test.go @@ -0,0 +1,257 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "net" + "path/filepath" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/types/known/timestamppb" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + permitv1 "go.datum.net/galactic/api/fabric/permit/v1" + servicev1 "go.datum.net/galactic/api/fabric/service/v1" + fabricv1 "go.datum.net/galactic/api/fabric/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/identity" + "go.datum.net/galactic/internal/fabric/node" + "go.datum.net/galactic/internal/fabric/testpki" +) + +// nodeCaller is the identity the sidecar on n presents: its certs pod's. +func nodeCaller(ctx context.Context, n string) context.Context { + return node.WithCaller(ctx, identity.Node(testSite, DefaultNamespace, "certs-"+n)) +} + +func newPermits(t *testing.T, objs []client.Object, l limit.Limits, slots int) *Permits { + t.Helper() + s := runtime.NewScheme() + _ = clientgoscheme.AddToScheme(s) + sel, _ := labels.Parse(DefaultPodSelector) + certs, _ := labels.Parse(DefaultCertsSelector) + adm := newTestAdmission(t, l) + return &Permits{ + Admission: adm, Executor: NewExecutor(slots, 0, 0), Elected: elected, + Discoverer: &Discoverer{Reader: fake.NewClientBuilder().WithScheme(s).WithObjects(objs...).Build(), + Namespace: DefaultNamespace, Selector: sel, CertsSelector: certs}, + } +} + +func pingPermitRequest(n, operator string, expires time.Time) *permitv1.RequestPermitRequest { + return &permitv1.RequestPermitRequest{ + Node: n, Operator: operator, RequestId: "op-" + n, + Query: &fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_PING, Target: probeTarget4, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV4}, + ExpiresAt: timestamppb.New(expires), + } +} + +func TestPermitAuthorization(t *testing.T) { + dir := t.TempDir() + ca := testpki.NewCA(t, testSite) + gwCreds := loadCreds(t, ca, dir, identity.Gateway(testSite)) + addr := serveGateway(t, gwCreds, &Debug{Elected: elected}, + &Service{Cell: testSite, Allowlist: testAllowlist, Elected: elected}) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + req := pingPermitRequest(routerA, "alice", time.Now().Add(10*time.Second)) + + // A node reaches the permit service (which issues nothing without an + // admission), and nothing else. + nodeConn := dialAs(t, addr, loadCreds(t, ca, filepath.Join(dir, "node"), + identity.Node(testSite, DefaultNamespace, "certs-"+routerA))) + _, err := permitv1.NewPermitServiceClient(nodeConn).RequestPermit(ctx, req) + if errcode.Of(err) != errcode.LimiterUnavailable { + t.Errorf("node RequestPermit: %v", err) + } + _, err = fabricv1.NewFabricGatewayServiceClient(nodeConn).Query(ctx, &fabricv1.QueryRequest{}) + if errcode.Of(err) != errcode.Unauthorized { + t.Errorf("node Query: %v", err) + } + _, err = servicev1.NewLookingGlassServiceClient(nodeConn).GetCapabilities(ctx, + &servicev1.GetCapabilitiesRequest{Cell: testSite, ApiMajor: ServiceAPIMajor}) + if errcode.Of(err) != errcode.Unauthorized { + t.Errorf("node GetCapabilities: %v", err) + } + + // No other role may request a permit, and a node of another namespace + // is refused by the handler. + for _, id := range []identity.ID{ + identity.Operator(testSite, "alice"), identity.Service(testSite, testService), + identity.Node(testSite, "elsewhere", "certs-"+routerA), + } { + conn := dialAs(t, addr, loadCreds(t, ca, filepath.Join(dir, string(id.Role)+id.Namespace), id)) + _, err := permitv1.NewPermitServiceClient(conn).RequestPermit(ctx, req) + if errcode.Of(err) != errcode.Unauthorized { + t.Errorf("%s RequestPermit: %v", id, err) + } + } +} + +func TestPermitIssueHoldRelease(t *testing.T) { + l := roomyLimits() + l.QueueWait = 50 * time.Millisecond + p := newPermits(t, routerPods(routerA, routerB), l, 1) + ctxA, ctxB := nodeCaller(t.Context(), routerA), nodeCaller(t.Context(), routerB) + expires := time.Now().Add(10 * time.Second) + + resp, err := p.RequestPermit(ctxA, pingPermitRequest(routerA, "alice", expires)) + if err != nil { + t.Fatal(err) + } + pm := resp.GetPermit() + if pm.GetNode() != routerA || pm.GetRequestId() != "op-"+routerA || pm.GetDestination() != probeTarget4 || + pm.GetPackets() != limit.PingPackets || pm.GetEpoch() != "lease-uid/"+testHolder || + pm.GetDeadline().AsTime().After(expires) { + t.Errorf("permit = %v", pm) + } + // The permit holds the cell's only slot. + _, err = p.RequestPermit(ctxB, pingPermitRequest(routerB, "bob", expires)) + if errcode.Of(err) != errcode.QueueTimeout { + t.Errorf("second permit while the slot is held: %v", err) + } + // Only the node it was issued to may release it. + _, err = p.ReleasePermit(ctxB, &permitv1.ReleasePermitRequest{Node: routerA, Id: pm.GetId()}) + if errcode.Of(err) != errcode.Unauthorized { + t.Errorf("release by another node: %v", err) + } + if _, err := p.ReleasePermit(ctxB, &permitv1.ReleasePermitRequest{Node: routerB, Id: pm.GetId()}); err != nil { + t.Errorf("release of an unknown permit: %v", err) + } + _, err = p.RequestPermit(ctxB, pingPermitRequest(routerB, "bob", expires)) + if errcode.Of(err) != errcode.QueueTimeout { + t.Errorf("slot freed by another node's release: %v", err) + } + if _, err := p.ReleasePermit(ctxA, &permitv1.ReleasePermitRequest{Node: routerA, Id: pm.GetId()}); err != nil { + t.Fatal(err) + } + if _, err := p.RequestPermit(ctxB, pingPermitRequest(routerB, "bob", expires)); err != nil { + t.Errorf("after release: %v", err) + } +} + +func TestPermitRefusals(t *testing.T) { + p := newPermits(t, routerPods(routerA, routerB), roomyLimits(), 8) + ctxA := nodeCaller(t.Context(), routerA) + expires := time.Now().Add(10 * time.Second) + for name, tc := range map[string]struct { + mod func(*permitv1.RequestPermitRequest) + code errcode.Code + }{ + "another node": {func(r *permitv1.RequestPermitRequest) { r.Node = routerB }, errcode.Unauthorized}, + "no operator": {func(r *permitv1.RequestPermitRequest) { r.Operator = "" }, errcode.InvalidQuery}, + "bad operator": {func(r *permitv1.RequestPermitRequest) { r.Operator = "a/b" }, errcode.InvalidQuery}, + "a read": {func(r *permitv1.RequestPermitRequest) { + r.Query = &fabricv1.Query{Type: fabricv1.QueryType_QUERY_TYPE_BGP_SUMMARY, + AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV4} + }, errcode.InvalidQuery}, + "not canonical": {func(r *permitv1.RequestPermitRequest) { r.Query.AddressFamily = 0 }, errcode.InvalidQuery}, + "past expiry": {func(r *permitv1.RequestPermitRequest) { + r.ExpiresAt = timestamppb.New(time.Now().Add(-time.Second)) + }, errcode.DeadlineExceeded}, + } { + req := pingPermitRequest(routerA, "alice", expires) + tc.mod(req) + if _, err := p.RequestPermit(ctxA, req); errcode.Of(err) != tc.code { + t.Errorf("%s: %v, want %s", name, err, tc.code) + } + } + // An unreleased permit's slot frees after its deadline plus the grace. + p = newPermits(t, routerPods(routerA), roomyLimits(), 1) + short := time.Now().Add(200 * time.Millisecond) + if _, err := p.RequestPermit(ctxA, pingPermitRequest(routerA, "alice", short)); err != nil { + t.Fatal(err) + } + time.Sleep(time.Until(short.Add(ReservationGrace + 100*time.Millisecond))) + if rel, err := tryAcquire(p.Executor); err != nil { + t.Errorf("slot still held past the permit's grace: %v", err) + } else { + rel() + } +} + +// leaderConn dials one leader address as the gateway. +type leaderConn struct{ conn *grpc.ClientConn } + +func (l leaderConn) LeaderConn(context.Context) (*grpc.ClientConn, error) { return l.conn, nil } + +func TestPermitForwarding(t *testing.T) { + dir := t.TempDir() + ca := testpki.NewCA(t, testSite) + gwCreds := loadCreds(t, ca, dir, identity.Gateway(testSite)) + leader := newPermits(t, routerPods(routerA), roomyLimits(), 8) + serve := func(p *Permits) string { + srv := NewServer(gwCreds, testAllowlist, &Debug{Elected: p.Elected}, + &Service{Cell: testSite, Allowlist: testAllowlist, Elected: p.Elected}, p) + var lc net.ListenConfig + lis, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis.Addr().String() + } + leaderAddr := serve(leader) + follower := &Permits{ + Elected: func() bool { return false }, Discoverer: &Discoverer{Namespace: DefaultNamespace}, + Leader: leaderConn{conn: dialAs(t, leaderAddr, gwCreds)}, + } + followerAddr := serve(follower) + + nodeConn := dialAs(t, followerAddr, loadCreds(t, ca, filepath.Join(dir, "node"), + identity.Node(testSite, DefaultNamespace, "certs-"+routerA))) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + resp, err := permitv1.NewPermitServiceClient(nodeConn).RequestPermit(ctx, + pingPermitRequest(routerA, "alice", time.Now().Add(10*time.Second))) + if err != nil || resp.GetPermit().GetNode() != routerA { + t.Fatalf("forwarded RequestPermit = %v, %v", resp, err) + } + // The leader sees the node's pod, not the follower's identity: another + // node's pod cannot be claimed through the follower. + _, err = permitv1.NewPermitServiceClient(nodeConn).RequestPermit(ctx, + pingPermitRequest(routerB, "alice", time.Now().Add(10*time.Second))) + if errcode.Of(err) != errcode.Unauthorized { + t.Errorf("forwarded request for another node: %v", err) + } + if _, err := permitv1.NewPermitServiceClient(nodeConn).ReleasePermit(ctx, + &permitv1.ReleasePermitRequest{Node: routerA, Id: resp.GetPermit().GetId()}); err != nil { + t.Errorf("forwarded ReleasePermit: %v", err) + } +} + +func TestPermitForwardedToFollowerRefused(t *testing.T) { + p := &Permits{ + Elected: func() bool { return false }, Discoverer: &Discoverer{Namespace: DefaultNamespace}, + Leader: leaderConn{}, + } + ctx := node.WithCaller(t.Context(), identity.Gateway(testSite)) + ctx = metadata.NewIncomingContext(ctx, metadata.Pairs(nodePodHeader, "certs-"+routerA)) + _, err := p.RequestPermit(ctx, pingPermitRequest(routerA, "alice", time.Now().Add(10*time.Second))) + if errcode.Of(err) != errcode.OwnershipLost { + t.Errorf("forwarded RequestPermit at a follower: %v", err) + } + _, err = p.ReleasePermit(ctx, &permitv1.ReleasePermitRequest{Node: routerA, Id: "x"}) + if errcode.Of(err) != errcode.OwnershipLost { + t.Errorf("forwarded ReleasePermit at a follower: %v", err) + } +} + +func TestPrincipalFamiliesDoNotCollide(t *testing.T) { + if fabricQueryPrincipal("operator", "bob") == operatorPrincipal("bob") { + t.Error("a FabricQuery in namespace operator shares an operator's key") + } +} diff --git a/internal/fabric/gateway/reconciler.go b/internal/fabric/gateway/reconciler.go index 1b291eb9c..9b5346ba4 100644 --- a/internal/fabric/gateway/reconciler.go +++ b/internal/fabric/gateway/reconciler.go @@ -327,7 +327,7 @@ func (r *Reconciler) launch(fq *fabricapi.FabricQuery, q query.Query, nodes []No }() log := slog.With("fabricQuery", key.String(), "requestID", spec.RequestID, "attempt", attempt) started := r.now() - outcomes := r.Runner.Run(ctx, spec.Source.Namespace+"/"+spec.Source.Cluster, spec.RequestID, + outcomes := r.Runner.Run(ctx, fabricQueryPrincipal(spec.Source.Namespace, spec.Source.Cluster), spec.RequestID, q, nodes, wire, spec.ExpiresAt.Time) if r.Metrics != nil { r.Metrics.stageLatency.WithLabelValues("execution").Observe(r.now().Sub(started).Seconds()) @@ -696,3 +696,10 @@ func nodesFromStatus(targets []fabricapi.NodeTarget) []Node { } return out } + +// fabricQueryPrincipal is the budget key of a FabricQuery source. Its +// "fabricquery/" prefix keeps it apart from an operator's key and from a +// service project's, whose IDs cannot contain "/". +func fabricQueryPrincipal(namespace, cluster string) string { + return "fabricquery/" + namespace + "/" + cluster +} diff --git a/internal/fabric/gateway/runner.go b/internal/fabric/gateway/runner.go index fdd51c5f8..341936901 100644 --- a/internal/fabric/gateway/runner.go +++ b/internal/fabric/gateway/runner.go @@ -19,6 +19,7 @@ import ( fabricv1 "go.datum.net/galactic/api/fabric/v1" "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" "go.datum.net/galactic/internal/fabric/identity" "go.datum.net/galactic/internal/fabric/node" "go.datum.net/galactic/internal/fabric/query" @@ -121,13 +122,27 @@ type Runner struct { Clients NodeClients Executor *Executor Metrics *Metrics + // Admission, when set, enforces the cell's aggregate probe budgets on + // every caller: each probe is dispatched only with a permit charged to + // its principal, destination and cell, a probe's slot whose node answer + // was lost stays held until the job's deadline plus ReservationGrace, + // and a full principal or cell queue is QueueFull with retry guidance. + Admission *Admission // QueueWait bounds a Stream job's wait for an execution slot; zero // selects ServiceQueueWait. QueueWait time.Duration // Now returns the current time; nil selects time.Now. Now func() time.Time + + // permitPods caches, per sidecar pod UID, whether the node enforces + // probe permits; it is cleared when it reaches maxPermitPods. + permitMu sync.Mutex + permitPods map[string]bool } +// maxPermitPods bounds the probe-permit capability cache. +const maxPermitPods = 1024 + func (r *Runner) now() time.Time { if r.Now != nil { return r.Now() @@ -146,6 +161,11 @@ type runOptions struct { // requestCodes reports a failure caused by ctx ending as // DeadlineExceeded or Cancelled rather than Timeout. requestCodes bool + // reservation, when set, holds the queue capacity every job uses. + reservation *Reservation + // checkOwnership confirms the election before every dispatch, not + // only a probe's. + checkOwnership bool } // Run executes q on every selected node in nodes and returns one outcome per @@ -173,14 +193,16 @@ func (r *Runner) Run(ctx context.Context, project, requestID string, q query.Que // never repeats a node call, bounds each job's wait for a slot by // QueueWait (QueueTimeout), and reports a job cut short by ctx ending // as DeadlineExceeded or Cancelled; a node's own 30 s bound stays Timeout. +// Jobs queue on res when it is set, and with Admission set every dispatch +// first confirms the election. func (r *Runner) Stream(ctx context.Context, project, requestID string, q query.Query, nodes []Node, - budgets *fabricv1.Budgets, expires time.Time, emit func(Outcome)) { + budgets *fabricv1.Budgets, expires time.Time, res *Reservation, emit func(Outcome)) { wait := r.QueueWait if wait <= 0 { wait = ServiceQueueWait } r.fanOut(ctx, project, requestID, q, nodes, budgets, expires, - runOptions{queueWait: wait, requestCodes: true}, emit) + runOptions{queueWait: wait, requestCodes: true, reservation: res, checkOwnership: true}, emit) } func (r *Runner) fanOut(ctx context.Context, project, requestID string, q query.Query, nodes []Node, @@ -198,7 +220,7 @@ func (r *Runner) fanOut(ctx context.Context, project, requestID string, q query. wg.Go(func() { nctx, cancel := context.WithDeadline(ctx, deadline) defer cancel() - obs, err := r.one(nctx, project, requestID, wire, q, n, budgets, expires, opts) + obs, err := r.one(nctx, project, requestID, wire, q, n, budgets, expires, deadline, opts) if opts.requestCodes { // When the request's expiration is the node's deadline, the // node's timer can fire before ctx's: both mean the request @@ -212,8 +234,13 @@ func (r *Runner) fanOut(ctx context.Context, project, requestID string, q query. wg.Wait() } +// errOwnershipLost is the cause with which a service request's execution is +// cancelled when the gateway loses the election. +var errOwnershipLost = errors.New("the gateway lost execution ownership") + // requestErr reports a failure that ctx's end, or the request's expiration, -// caused as the request's own DeadlineExceeded or Cancelled. +// caused as the request's own DeadlineExceeded, Cancelled or, when the +// election was lost, OwnershipLost. func requestErr(ctx context.Context, err error, expired bool) error { if err == nil || (ctx.Err() == nil && !expired) { return err @@ -223,6 +250,9 @@ func requestErr(ctx context.Context, err error, expired bool) error { default: return err } + if errors.Is(context.Cause(ctx), errOwnershipLost) { + return errcode.Status(errcode.OwnershipLost, "the gateway lost execution ownership before the router finished") + } if expired || errors.Is(ctx.Err(), context.DeadlineExceeded) { return errcode.Status(errcode.DeadlineExceeded, "the request's deadline passed before the router finished") } @@ -230,16 +260,26 @@ func requestErr(ctx context.Context, err error, expired bool) error { } func (r *Runner) one(ctx context.Context, project, requestID string, wire *fabricv1.Query, q query.Query, n Node, - budgets *fabricv1.Budgets, expires time.Time, opts runOptions) (*fabricv1.Observation, error) { + budgets *fabricv1.Budgets, expires, deadline time.Time, opts runOptions) (*fabricv1.Observation, error) { actx := ctx if opts.queueWait > 0 { var cancel context.CancelFunc actx, cancel = context.WithTimeout(ctx, opts.queueWait) defer cancel() } - release, err := r.Executor.Acquire(actx, project, q.Type.Expensive()) + var release func() + var err error + if opts.reservation != nil { + release, err = opts.reservation.Acquire(actx, q.Type.Expensive()) + } else { + release, err = r.Executor.Acquire(actx, project, q.Type.Expensive()) + } if err != nil { if errors.Is(err, ErrQueueFull) { + if r.Admission != nil { + return nil, errcode.Retry(errcode.QueueFull, "the cell's execution queue is full", + string(limit.ScopeQueue), time.Second) + } return nil, errcode.Status(errcode.NodeBusy, "cell execution queue is full") } if ctx.Err() == nil { @@ -247,7 +287,12 @@ func (r *Runner) one(ctx context.Context, project, requestID string, wire *fabri } return nil, errcode.Status(errcode.Timeout, "deadline passed waiting for a cell execution slot") } - defer release() + held := false + defer func() { + if !held { + release() + } + }() c, err := r.Clients.Client(n) if err != nil { @@ -256,8 +301,28 @@ func (r *Runner) one(ctx context.Context, project, requestID string, wire *fabri req := &fabricv1.ExecuteRequest{ RequestId: requestID, Node: n.Name, Query: wire, Budgets: budgets, ExpiresAt: timestamppb.New(expires), } + if a := r.Admission; a != nil { + switch { + case q.Type.Probe(): + if err := r.checkPermits(ctx, c, n); err != nil { + return nil, err + } + if req.Permit, err = a.permit(ctx, project, requestID, n.Name, q, deadline); err != nil { + return nil, err + } + case opts.checkOwnership: + if _, _, err := a.Authority.Check(ctx); err != nil { + return nil, err + } + } + } start := r.now() resp, err := c.Execute(ctx, req) + if r.Admission != nil && q.Type.Probe() && err != nil && !errcode.Typed(err) { + // No answer from the node: it may still be sending the probe. + held = true + holdUntil(release, deadline.Add(ReservationGrace), r.now()) + } // A cheap read that failed to connect is safe to repeat once: the node // deduplicates by request ID. Searches and probes are never retried // within an attempt, since their first execution may have run. @@ -280,3 +345,29 @@ func (r *Runner) one(ctx context.Context, project, requestID string, wire *fabri } return resp.GetObservation(), nil } + +// checkPermits refuses a node whose sidecar does not enforce probe permits: +// it would ignore its permit's allowance and deadline. The answer is cached +// per pod, whose UID changes with its image. +func (r *Runner) checkPermits(ctx context.Context, c fabricv1.FabricServiceClient, n Node) error { + r.permitMu.Lock() + ok, cached := r.permitPods[n.PodUID] + r.permitMu.Unlock() + if !cached { + info, err := c.Info(ctx, &fabricv1.InfoRequest{}) + if err != nil { + return errcode.Status(errcode.NodeUnreachable, "the node did not report its capabilities") + } + ok = info.GetProbePermits() + r.permitMu.Lock() + if r.permitPods == nil || len(r.permitPods) >= maxPermitPods { + r.permitPods = map[string]bool{} + } + r.permitPods[n.PodUID] = ok + r.permitMu.Unlock() + } + if !ok { + return errcode.Status(errcode.QueryTypeUnavailable, "the node does not enforce probe permits") + } + return nil +} diff --git a/internal/fabric/gateway/service.go b/internal/fabric/gateway/service.go index 248be7c10..235b7c3ef 100644 --- a/internal/fabric/gateway/service.go +++ b/internal/fabric/gateway/service.go @@ -12,6 +12,7 @@ import ( "fmt" "io" "regexp" + "slices" "strings" "time" @@ -24,9 +25,11 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" forwardv1 "go.datum.net/galactic/api/fabric/forward/v1" + permitv1 "go.datum.net/galactic/api/fabric/permit/v1" servicev1 "go.datum.net/galactic/api/fabric/service/v1" fabricv1 "go.datum.net/galactic/api/fabric/v1" "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" "go.datum.net/galactic/internal/fabric/identity" "go.datum.net/galactic/internal/fabric/node" "go.datum.net/galactic/internal/fabric/query" @@ -59,13 +62,16 @@ const ( FeatureAggregateProbeBudgets = "aggregate-probe-budgets" ) -// serviceFeatures maps every known feature to whether this gateway serves -// it. Aggregate probe budgets are not enforced yet, so a request requiring -// them is refused. -var serviceFeatures = map[string]bool{ - FeatureRouterOutcomes: true, - FeatureTerminalCoverage: true, - FeatureAggregateProbeBudgets: false, +// features lists the features this gateway serves: aggregate probe budgets +// only while it executes requests under an Admission. Enabling execution +// asserts that every node also requires probe permits, so direct operator +// probes are charged too. +func (s *Service) features() []string { + f := []string{FeatureRouterOutcomes, FeatureTerminalCoverage} + if s.Enabled && s.Admission != nil { + f = append(f, FeatureAggregateProbeBudgets) + } + return f } // Terminal reasons of a stream's complete event. @@ -116,11 +122,11 @@ func (a Allowlist) Check(id identity.ID) error { return nil } -// Handshake is the gateway server's handshake check: operators, the gateway -// and listed service identities may connect. +// Handshake is the gateway server's handshake check: operators, the +// gateway, nodes and listed service identities may connect. func (a Allowlist) Handshake(id identity.ID) error { switch id.Role { - case identity.RoleOperator, identity.RoleGateway: + case identity.RoleOperator, identity.RoleGateway, identity.RoleNode: return nil case identity.RoleService: return a.Check(id) @@ -172,13 +178,14 @@ type contextStream struct { func (s *contextStream) Context() context.Context { return s.ctx } // NewServer returns the gateway's gRPC server: the operator debug service, -// the Looking Glass service and the gateway-only forwarding service on one -// mTLS listener. Every call, unary or streaming, is authorized per role from +// the Looking Glass service, the node-only permit service and the +// gateway-only forwarding service on one mTLS listener. Every call, unary or streaming, is authorized per role from // GatewayMethods against a peer certificate re-verified on that call, bounded // by the certificate's expiry, and stripped of forwarding metadata unless // the gateway identity sent it. opts are appended. func NewServer( - creds *identity.Credentials, allowlist Allowlist, debug *Debug, service *Service, opts ...grpc.ServerOption, + creds *identity.Credentials, allowlist Allowlist, debug *Debug, service *Service, permits *Permits, + opts ...grpc.ServerOption, ) *grpc.Server { auth := &node.Authorizer{Methods: GatewayMethods, Credentials: creds, Allow: allowlist.Check} gs := grpc.NewServer(append([]grpc.ServerOption{ @@ -189,6 +196,7 @@ func NewServer( fabricv1.RegisterFabricGatewayServiceServer(gs, debug) servicev1.RegisterLookingGlassServiceServer(gs, service) forwardv1.RegisterForwardServiceServer(gs, service.Forwarder()) + permitv1.RegisterPermitServiceServer(gs, permits) return gs } @@ -199,8 +207,8 @@ type LeaderDialer interface { // Service implements the Looking Glass service. Any replica authenticates // and validates a request; a follower forwards it once to the leader, which -// validates it again before executing. Unless Enabled, the leader refuses a -// valid request with ServiceDisabled. +// validates it again before executing. Unless Enabled and given an +// Admission, the leader refuses a valid request with ServiceDisabled. type Service struct { servicev1.UnimplementedLookingGlassServiceServer @@ -208,6 +216,9 @@ type Service struct { Cell string // Enabled makes the leader execute valid requests. Enabled bool + // Admission enforces the cell's aggregate admission and probe budgets. + // It must be the Runner's; without it nothing executes. + Admission *Admission // Discoverer takes each request's router inventory; it should read // uncached, so the snapshot carries the pod list's resourceVersion. Discoverer *Discoverer @@ -257,14 +268,14 @@ func (s *Service) capabilities() *servicev1.GetCapabilitiesResponse { resp := &servicev1.GetCapabilitiesResponse{ Cell: s.Cell, ApiMajor: ServiceAPIMajor, - Enabled: s.Enabled, + Enabled: s.Enabled && s.Admission != nil, Operations: []*servicev1.Operation{ {Type: fabricv1.QueryType_QUERY_TYPE_ROUTE_LOOKUP, AddressFamilies: families}, {Type: fabricv1.QueryType_QUERY_TYPE_BGP_SUMMARY, AddressFamilies: families}, {Type: fabricv1.QueryType_QUERY_TYPE_PING, AddressFamilies: families}, {Type: fabricv1.QueryType_QUERY_TYPE_TRACEROUTE, AddressFamilies: families}, }, - Features: []string{FeatureRouterOutcomes, FeatureTerminalCoverage}, + Features: s.features(), Limits: &servicev1.Limits{ MaxRequestLifetime: durationpb.New(MaxServiceRequestLifetime), MaxNodeExecution: durationpb.New(query.MaxNodeExecution), @@ -273,6 +284,9 @@ func (s *Service) capabilities() *servicev1.GetCapabilitiesResponse { MaxBudgets: maxServiceBudgets(), }, } + if slices.Contains(resp.Features, FeatureAggregateProbeBudgets) { + resp.Limits.Admission = admissionLimits(s.Admission.Limits) + } policy, err := proto.MarshalOptions{Deterministic: true}.Marshal(resp) if err == nil { sum := sha256.Sum256(policy) @@ -283,6 +297,30 @@ func (s *Service) capabilities() *servicev1.GetCapabilitiesResponse { return resp } +// admissionLimits reports a cell's aggregate limits. +func admissionLimits(l limit.Limits) *servicev1.AdmissionLimits { + r := func(r limit.Rate) *servicev1.TokenRate { + return &servicev1.TokenRate{PerSecond: r.PerSecond, Burst: r.Burst} + } + return &servicev1.AdmissionLimits{ + RequestCell: r(l.RequestCell), + RequestProject: r(l.RequestProject), + PacketCell: r(l.PacketCell), + PacketProject: r(l.PacketPrincipal), + PacketDestinationHost: r(l.PacketHost), + PacketDestinationPrefix: r(l.PacketPrefix), + ActiveJobs: uint32(l.Slots), + ProjectActiveJobs: uint32(l.PrincipalSlots), + QueuedJobs: uint32(l.Queue), + ProjectQueuedJobs: uint32(l.PrincipalQueue), + Streams: uint32(l.Streams), + ProjectStreams: uint32(l.ProjectStreams), + QueueWait: durationpb.New(l.QueueWait), + PingPackets: limit.PingPackets, + TraceroutePackets: limit.TraceroutePackets, + } +} + // maxServiceBudgets are the largest result budgets a service request may // ask for: the node ceilings. func maxServiceBudgets() *fabricv1.Budgets { @@ -312,7 +350,7 @@ func (s *Service) RunDiagnostic( if !s.Elected() { return s.forward(ctx, caller, canonical, received, deadline, stream) } - return s.execute(ctx, canonical, deadline, stream.Send) + return s.execute(ctx, caller, canonical, deadline, stream.Send) } // Forwarder returns the gateway-only service a follower forwards to. @@ -362,7 +400,7 @@ func (f *forwarder) ForwardDiagnostic( if !now.Before(deadline) { return errcode.Status(errcode.DeadlineExceeded, "forwarded request's deadline has passed") } - return s.execute(ctx, canonical, deadline, stream.Send) + return s.execute(ctx, svc, canonical, deadline, stream.Send) } // serviceCaller returns the authenticated service identity of a call. @@ -417,7 +455,7 @@ func (s *Service) validate( if err := checkBudgets(req.GetBudgets()); err != nil { return nil, time.Time{}, err } - if err := checkFeatures(req.GetRequiredFeatures()); err != nil { + if err := checkFeatures(req.GetRequiredFeatures(), s.features()); err != nil { return nil, time.Time{}, err } out := proto.CloneOf(req) @@ -468,10 +506,10 @@ func checkNodes(nodes []string) error { // checkBudgets refuses a budget above its advertised maximum. func checkBudgets(b *fabricv1.Budgets) error { - limit := maxServiceBudgets() - if b.GetMaxResponseBytes() > limit.GetMaxResponseBytes() || b.GetMaxPrefixes() > limit.GetMaxPrefixes() || - b.GetMaxPathsPerPrefix() > limit.GetMaxPathsPerPrefix() || - b.GetMaxCommunitiesPerPath() > limit.GetMaxCommunitiesPerPath() { + ceiling := maxServiceBudgets() + if b.GetMaxResponseBytes() > ceiling.GetMaxResponseBytes() || b.GetMaxPrefixes() > ceiling.GetMaxPrefixes() || + b.GetMaxPathsPerPrefix() > ceiling.GetMaxPathsPerPrefix() || + b.GetMaxCommunitiesPerPath() > ceiling.GetMaxCommunitiesPerPath() { return errcode.Status(errcode.InvalidQuery, "a budget exceeds its advertised maximum") } return nil @@ -479,9 +517,9 @@ func checkBudgets(b *fabricv1.Budgets) error { // checkFeatures refuses a required feature this gateway does not serve, // known or not. -func checkFeatures(features []string) error { - for _, f := range features { - if !serviceFeatures[f] { +func checkFeatures(required, served []string) error { + for _, f := range required { + if !slices.Contains(served, f) { return errcode.Status(errcode.VersionUnsupported, "a required feature is not available") } } @@ -528,28 +566,55 @@ func (s *Service) forward( // execute runs a validated request on the leader and sends its events: one // snapshot of the cell's routers before any router executes, each selected -// router's outcome as it finishes, and the terminal coverage. Events are -// sent by this goroutine alone; finished outcomes wait for it in a buffer of -// outcomeBuffer, and a failed send cancels every router still running. A +// router's outcome as it finishes, and the terminal coverage. Before +// discovery it confirms the election, charges the cell's and the project's +// request tokens, registers the attempt key and opens a live stream; after +// discovery it reserves queue capacity for every selected router at once, +// before the snapshot is sent. Events are sent by this goroutine alone; +// finished outcomes wait for it in a buffer of outcomeBuffer, and a failed +// send or the loss of the election cancels every router still running. A // failure before the snapshot is returned as the call's status; once the // snapshot is sent the stream ends with complete and status OK, whatever // the diagnostic's own result. func (s *Service) execute( - ctx context.Context, req *servicev1.RunDiagnosticRequest, deadline time.Time, + ctx context.Context, caller identity.ID, req *servicev1.RunDiagnosticRequest, deadline time.Time, send func(*servicev1.DiagnosticEvent) error, ) error { if !s.now().Before(deadline) { return errcode.Status(errcode.DeadlineExceeded, "request's deadline has passed") } - if !s.Enabled || s.Discoverer == nil || s.Runner == nil { + adm := s.Admission + if !s.Enabled || adm == nil || s.Discoverer == nil || s.Runner == nil { return errcode.Status(errcode.ServiceDisabled, "this cell does not execute Looking Glass service diagnostics") } + project := req.GetProjectId() + _, epochCtx, err := adm.Authority.Check(ctx) + if err != nil { + return err + } + if err := adm.Buckets.ChargeRequest(project, adm.now()); err != nil { + return err + } + if err := adm.Attempts.Register(attemptKey(caller, req), requestDigest(req), req.GetExpiresAt().AsTime(), + adm.now()); err != nil { + return err + } + closeStream, err := adm.openStream(project) + if err != nil { + return err + } + defer closeStream() + // sendCtx ends when the stream does or a send fails; runCtx also ends - // at the deadline. Outcomes a deadline cuts short still reach the - // writer, so the consumer can see them while the stream lasts. + // at the deadline or when the election is lost. Outcomes a deadline or + // the loss cuts short still reach the writer, so the consumer can see + // them while the stream lasts. sendCtx, abort := context.WithCancel(ctx) defer abort() - runCtx, cancel := context.WithDeadline(sendCtx, deadline) + ownedCtx, lose := context.WithCancelCause(sendCtx) + defer lose(nil) + defer context.AfterFunc(epochCtx, func() { lose(errOwnershipLost) })() + runCtx, cancel := context.WithDeadline(ownedCtx, deadline) defer cancel() inv, err := s.Discoverer.Inventory(runCtx, req.GetNodes(), MaxServiceNodes, s.now()) @@ -558,6 +623,8 @@ func (s *Service) execute( return err } switch { + case errors.Is(context.Cause(runCtx), errOwnershipLost): + return errcode.Status(errcode.OwnershipLost, "the election was lost during router discovery") case errors.Is(runCtx.Err(), context.DeadlineExceeded): return errcode.Status(errcode.DeadlineExceeded, "request's deadline passed during router discovery") case runCtx.Err() != nil: @@ -569,6 +636,12 @@ func (s *Service) execute( if proto.Size(snapshot) > maxSnapshotBytes { return errcode.Status(errcode.InventoryTooLarge, "the cell's router snapshot exceeds its size bound") } + res, err := s.Runner.Executor.Reserve(project, selectedCount(inv.Routers)) + if err != nil { + return errcode.Retry(errcode.QueueFull, "the cell's execution queue cannot take this request", + string(limit.ScopeQueue), time.Second) + } + defer res.Release() var seq uint64 next := func(ev *servicev1.DiagnosticEvent) error { seq++ @@ -588,7 +661,7 @@ func (s *Service) execute( outcomes := make(chan Outcome, outcomeBuffer) go func() { defer close(outcomes) - s.Runner.Stream(runCtx, req.GetProjectId(), req.GetRequestId(), q, inv.Routers, budgets, deadline, + s.Runner.Stream(runCtx, project, req.GetRequestId(), q, inv.Routers, budgets, deadline, res, func(o Outcome) { select { case outcomes <- o: @@ -611,6 +684,32 @@ func (s *Service) execute( }}) } +func selectedCount(routers []Node) int { + n := 0 + for _, r := range routers { + if r.Selected { + n++ + } + } + return n +} + +// attemptKey identifies an attempt within its service identity, project +// and cell. +func attemptKey(caller identity.ID, req *servicev1.RunDiagnosticRequest) string { + return caller.URI() + "|" + req.GetProjectId() + "|" + req.GetRequestId() +} + +// requestDigest digests a canonical request's execution arguments: every +// field but its expiration. +func requestDigest(req *servicev1.RunDiagnosticRequest) string { + args := proto.CloneOf(req) + args.ExpiresAt = nil + b, _ := proto.MarshalOptions{Deterministic: true}.Marshal(args) + sum := sha256.Sum256(b) + return hex.EncodeToString(sum[:]) +} + func snapshotEvent(inv Inventory) *servicev1.Snapshot { out := &servicev1.Snapshot{ SnapshotId: inv.ID, @@ -632,9 +731,13 @@ func outcomeEvent(o Outcome) *servicev1.DiagnosticEvent { out := &servicev1.RouterOutcome{Node: o.Node.Name, PodUid: o.Node.PodUID, CompletedAt: timestamppb.New(o.Completed)} if o.Err != nil { code := errcode.Of(o.Err) - out.Result = &servicev1.RouterOutcome_Failure{Failure: &servicev1.Failure{ - Reason: string(code), Message: failureMessage(code), - }} + f := &servicev1.Failure{ + Reason: string(code), Message: failureMessage(code), Scope: errcode.Metadata(o.Err)[errcode.MetadataScope], + } + if d, ok := errcode.RetryDelay(o.Err); ok { + f.RetryDelay = durationpb.New(d) + } + out.Result = &servicev1.RouterOutcome_Failure{Failure: f} } else { out.Result = &servicev1.RouterOutcome_Observation{Observation: o.Observation} } @@ -659,6 +762,14 @@ func failureMessage(code errcode.Code) string { return "request was cancelled before the router finished" case errcode.FRRUnavailable: return "router's routing daemon is unavailable" + case errcode.Throttled: + return "a probe packet budget is exhausted" + case errcode.QueueFull: + return "the cell's execution queue is full" + case errcode.OwnershipLost: + return "the gateway lost execution ownership" + case errcode.LimiterUnavailable: + return "the cell's limiter is unavailable" } return "router diagnostic failed" } @@ -666,8 +777,8 @@ func failureMessage(code errcode.Code) string { // streamCoverage counts a stream's outcomes. type streamCoverage struct { successful, failed, truncated int - // stopped is the request-level reason, DeadlineExceeded or Cancelled, - // that cut a router short, if any. + // stopped is the request-level reason, DeadlineExceeded, Cancelled or + // OwnershipLost, that cut a router short, if any. stopped errcode.Code } @@ -681,7 +792,7 @@ func (c *streamCoverage) add(o Outcome) { } c.failed++ switch code := errcode.Of(o.Err); code { - case errcode.DeadlineExceeded, errcode.Cancelled: + case errcode.DeadlineExceeded, errcode.Cancelled, errcode.OwnershipLost: if c.stopped == "" { c.stopped = code } @@ -689,7 +800,7 @@ func (c *streamCoverage) add(o Outcome) { } // complete returns the terminal coverage. A request cut short by its -// deadline or cancellation reports that first; otherwise no selected router +// deadline, cancellation or the loss of the election reports that first; otherwise no selected router // is NoNodesAvailable, no success ExecutionFailed, and any failure, // truncation or omission other than NotRequested PartialResults. func (c *streamCoverage) complete(inv Inventory, now time.Time) *servicev1.Complete { diff --git a/internal/fabric/gateway/service_execution_test.go b/internal/fabric/gateway/service_execution_test.go index a7ae21a78..30429b702 100644 --- a/internal/fabric/gateway/service_execution_test.go +++ b/internal/fabric/gateway/service_execution_test.go @@ -10,6 +10,7 @@ import ( "fmt" "io" "path/filepath" + "slices" "sync" "testing" "time" @@ -29,6 +30,7 @@ import ( servicev1 "go.datum.net/galactic/api/fabric/service/v1" fabricv1 "go.datum.net/galactic/api/fabric/v1" "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" "go.datum.net/galactic/internal/fabric/identity" "go.datum.net/galactic/internal/fabric/node" "go.datum.net/galactic/internal/fabric/testpki" @@ -44,11 +46,13 @@ const ( type routerAnswer func(ctx context.Context, req *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) // routerNodes is a NodeClients whose routers each answer with their own -// function, ok by default, and which counts every call. +// function, ok by default, and which counts every call. Every router +// enforces probe permits unless it is listed in legacy. type routerNodes struct { mu sync.Mutex answers map[string]routerAnswer calls map[string]int + legacy map[string]bool } func (f *routerNodes) Client(n Node) (fabricv1.FabricServiceClient, error) { @@ -92,6 +96,14 @@ func (c *routerClient) Execute( return &fabricv1.ExecuteResponse{Observation: obs}, nil } +func (c *routerClient) Info( + context.Context, *fabricv1.InfoRequest, ...grpc.CallOption, +) (*fabricv1.InfoResponse, error) { + c.f.mu.Lock() + defer c.f.mu.Unlock() + return &fabricv1.InfoResponse{Node: c.node, ProbePermits: !c.f.legacy[c.node]}, nil +} + func okAnswer(name string) routerAnswer { return func(context.Context, *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) { return pingObservation(name, 3), nil @@ -160,10 +172,13 @@ func newService(t *testing.T, objs []client.Object, nodes *routerNodes, slots in reader := fake.NewClientBuilder().WithScheme(s).WithObjects(objs...).Build() sel, _ := labels.Parse(DefaultPodSelector) certs, _ := labels.Parse(DefaultCertsSelector) + adm := newTestAdmission(t, roomyLimits()) return &Service{ Cell: testSite, Allowlist: testAllowlist, Elected: elected, Enabled: true, Revision: "abc123", Discoverer: &Discoverer{Reader: reader, Namespace: DefaultNamespace, Selector: sel, CertsSelector: certs}, - Runner: &Runner{Clients: nodes, Executor: NewExecutor(slots, 0, 0), QueueWait: 200 * time.Millisecond}, + Runner: &Runner{Clients: nodes, Executor: NewExecutor(slots, 0, 0), QueueWait: 200 * time.Millisecond, + Admission: adm}, + Admission: adm, } } @@ -251,7 +266,7 @@ func checkGrammar(t *testing.T, events []*servicev1.DiagnosticEvent) ( t.Fatalf("stream has %d events", len(events)) } for i, ev := range events { - if ev.GetSequence() != uint64(i+1) || ev.GetRequestId() != testRequestID { + if ev.GetSequence() != uint64(i+1) || ev.GetRequestId() == "" || ev.GetRequestId() != events[0].GetRequestId() { t.Fatalf("event %d: sequence %d, request %q", i, ev.GetSequence(), ev.GetRequestId()) } } @@ -536,7 +551,10 @@ func TestServiceDiscoveryCutShort(t *testing.T) { ctx, cancel := context.WithCancel(node.WithCaller(t.Context(), identity.Service(testSite, testService))) stream := &chanStream{ctx: ctx, events: make(chan *servicev1.DiagnosticEvent, 1)} time.AfterFunc(100*time.Millisecond, cancel) - if err := svc.RunDiagnostic(validRequest(time.Now()), stream); errcode.Of(err) != errcode.Cancelled { + // A new attempt: the first one's request ID stays registered. + req = validRequest(time.Now()) + req.RequestId = "c0ffee00-926f-43dc-b03d-c29550a827ab" + if err := svc.RunDiagnostic(req, stream); errcode.Of(err) != errcode.Cancelled { t.Errorf("cancelled during discovery: %v", err) } } @@ -628,13 +646,20 @@ func TestServiceStreamFailureStopsExecution(t *testing.T) { // An outcome cannot be delivered: the router still running is // cancelled and RunDiagnostic returns. - cancelled := make(chan struct{}) + // router-b answers only once router-a is running, so router-a is under + // way when the stream breaks. + cancelled, running := make(chan struct{}), make(chan struct{}) nodes = &routerNodes{answers: map[string]routerAnswer{ routerA: func(ctx context.Context, _ *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) { + close(running) <-ctx.Done() close(cancelled) return nil, errcode.Status(errcode.Timeout, "cancelled") }, + routerB: func(context.Context, *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) { + <-running + return pingObservation(routerB, 3), nil + }, }} svc = newService(t, routerPods(routerA, routerB), nodes, 8) events, done = run(t, svc, validRequest(time.Now()), 1) @@ -662,7 +687,7 @@ func TestRunnerStreamNeverRetries(t *testing.T) { AddressFamily: fabricv1.AddressFamily_ADDRESS_FAMILY_IPV4}) routers := []Node{{Name: routerA, Selected: true}} expires := time.Now().Add(10 * time.Second) - r.Stream(t.Context(), "p", "id", q, routers, nil, expires, func(Outcome) {}) + r.Stream(t.Context(), "p", "id", q, routers, nil, expires, nil, func(Outcome) {}) if n := nodes.total(); n != 1 { t.Errorf("Stream called the router %d times", n) } @@ -690,13 +715,23 @@ func TestServiceCapabilities(t *testing.T) { t.Errorf("operation %v serves %d families", op.GetType(), len(op.GetAddressFamilies())) } } - // Aggregate probe budgets are not advertised until they are enforced. - if f := on.GetFeatures(); len(f) != 2 || f[0] != FeatureRouterOutcomes || f[1] != FeatureTerminalCoverage { + if a := on.GetLimits().GetAdmission(); a.GetProjectActiveJobs() != 2 || a.GetTraceroutePackets() != 20 || + a.GetRequestProject().GetBurst() != roomyLimits().RequestProject.Burst || + a.GetQueueWait().AsDuration() != limit.MaxQueueWait { + t.Errorf("admission limits = %v", a) + } + if f := on.GetFeatures(); !slices.Equal(f, []string{ + FeatureRouterOutcomes, FeatureTerminalCoverage, FeatureAggregateProbeBudgets, + }) { t.Errorf("features = %v", f) } again, _ := svc.GetCapabilities(ctx, req) svc.Enabled = false off, _ := svc.GetCapabilities(ctx, req) + // With execution off nothing is advertised as enforced. + if slices.Contains(off.GetFeatures(), FeatureAggregateProbeBudgets) || off.GetLimits().GetAdmission() != nil { + t.Errorf("disabled capabilities = %v", off) + } if again.GetPolicyRevision() != on.GetPolicyRevision() || off.GetPolicyRevision() == on.GetPolicyRevision() { t.Errorf("policy revisions %q, %q, %q", on.GetPolicyRevision(), again.GetPolicyRevision(), off.GetPolicyRevision()) } @@ -705,9 +740,8 @@ func TestServiceCapabilities(t *testing.T) { // maximum, is refused before any work. svc.Enabled = true for name, edit := range map[string]func(*runReq){ - "aggregate budgets": func(r *runReq) { r.RequiredFeatures = []string{FeatureAggregateProbeBudgets} }, - "unknown feature": func(r *runReq) { r.RequiredFeatures = []string{"router-outcomes-v2"} }, - "large budget": func(r *runReq) { r.Budgets = &fabricv1.Budgets{MaxPathsPerPrefix: 9} }, + "unknown feature": func(r *runReq) { r.RequiredFeatures = []string{"router-outcomes-v2"} }, + "large budget": func(r *runReq) { r.Budgets = &fabricv1.Budgets{MaxPathsPerPrefix: 9} }, } { req := validRequest(time.Now()) edit(req) @@ -716,11 +750,29 @@ func TestServiceCapabilities(t *testing.T) { } } req2 := validRequest(time.Now()) - req2.RequiredFeatures = []string{FeatureRouterOutcomes, FeatureTerminalCoverage} + req2.RequiredFeatures = []string{FeatureRouterOutcomes, FeatureTerminalCoverage, FeatureAggregateProbeBudgets} req2.Budgets = &fabricv1.Budgets{MaxPathsPerPrefix: 8} if _, err := collect(t, svc, req2); err != nil { t.Errorf("served features: %v", err) } + + // Without an Admission the service is neither advertised as enabled nor + // executes, and aggregate probe budgets are neither advertised nor + // accepted as a requirement. + svc.Admission = nil + bare, _ := svc.GetCapabilities(ctx, req) + if bare.GetEnabled() || slices.Contains(bare.GetFeatures(), FeatureAggregateProbeBudgets) || + bare.GetLimits().GetAdmission() != nil { + t.Errorf("capabilities without admission = %v", bare) + } + req3 := validRequest(time.Now()) + req3.RequiredFeatures = []string{FeatureAggregateProbeBudgets} + if _, err := collect(t, svc, req3); errcode.Of(err) != errcode.VersionUnsupported { + t.Errorf("aggregate budgets required without admission: %v", err) + } + if _, err := collect(t, svc, validRequest(time.Now())); errcode.Of(err) != errcode.ServiceDisabled { + t.Errorf("execution without admission: %v", err) + } } // The generated public client receives the whole stream over mTLS, from the @@ -729,12 +781,15 @@ func TestServiceStreamOverTransport(t *testing.T) { dir := t.TempDir() ca := testpki.NewCA(t, testSite) gwCreds := loadCreds(t, ca, dir, identity.Gateway(testSite)) - leader := newService(t, routerPods(routerA, routerB), &routerNodes{}, 8) - leaderAddr := serveGateway(t, gwCreds, &Debug{Elected: elected}, leader) - followerAddr := serveFollower(t, gwCreds, leaderAddr) - svcCreds := loadCreds(t, ca, filepath.Join(dir, "svc"), identity.Service(testSite, testService)) - for name, addr := range map[string]string{"leader": leaderAddr, "follower": followerAddr} { + for _, name := range []string{"leader", "follower"} { + // Each path gets its own leader, whose attempt cache has not seen + // the request ID. + leader := newService(t, routerPods(routerA, routerB), &routerNodes{}, 8) + addr := serveGateway(t, gwCreds, &Debug{Elected: elected}, leader) + if name == "follower" { + addr = serveFollower(t, gwCreds, addr) + } ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) stream, err := servicev1.NewLookingGlassServiceClient(dialAs(t, addr, svcCreds)). RunDiagnostic(ctx, validRequest(time.Now())) @@ -753,8 +808,51 @@ func TestServiceStreamOverTransport(t *testing.T) { events = append(events, ev) } cancel() + if len(events) == 0 || events[0].GetRequestId() != testRequestID { + t.Errorf("%s: events do not echo the request ID", name) + } if _, _, c := checkGrammar(t, events); c.GetReason() != CompleteSucceeded || c.GetSuccessful() != 2 { t.Errorf("%s: complete = %v", name, c) } } } + +// stallReader blocks every List until its context ends. +type stallReader struct { + client.Reader + listing chan struct{} +} + +func (r stallReader) List(ctx context.Context, _ client.ObjectList, _ ...client.ListOption) error { + r.listing <- struct{}{} + <-ctx.Done() + return ctx.Err() +} + +func TestServiceOwnershipLostDuringDiscovery(t *testing.T) { + lease := newSwitchableLease(t) + svc := newService(t, routerPods(routerA), &routerNodes{}, 8) + adm, err := NewAdmission(roomyLimits(), &limit.Authority{ + Reader: lease, Namespace: DefaultNamespace, Name: testLease, Identity: testHolder, Hold: time.Nanosecond, + }) + if err != nil { + t.Fatal(err) + } + activate(t, adm) + svc.Admission, svc.Runner.Admission, svc.Runner.Executor = adm, adm, adm.Executor() + listing := make(chan struct{}, 1) + svc.Discoverer.Reader = stallReader{Reader: svc.Discoverer.Reader, listing: listing} + go adm.Authority.Watch(t.Context(), 50*time.Millisecond) + + _, done := run(t, svc, requestFor("project-a", 1, nil), 0) + <-listing + lease.fail(true) + select { + case err := <-done: + if errcode.Of(err) != errcode.OwnershipLost { + t.Errorf("err = %v, want OwnershipLost", err) + } + case <-time.After(5 * time.Second): + t.Fatal("discovery outlived the election") + } +} diff --git a/internal/fabric/gateway/service_test.go b/internal/fabric/gateway/service_test.go index 783f47097..fb4a889c5 100644 --- a/internal/fabric/gateway/service_test.go +++ b/internal/fabric/gateway/service_test.go @@ -53,7 +53,7 @@ type ( func serveGateway(t *testing.T, creds *identity.Credentials, d *Debug, svc *Service, opts ...grpc.ServerOption) string { t.Helper() - srv := NewServer(creds, svc.Allowlist, d, svc, opts...) + srv := NewServer(creds, svc.Allowlist, d, svc, noPermits(d.Elected), opts...) var lc net.ListenConfig l, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") if err != nil { @@ -64,6 +64,11 @@ func serveGateway(t *testing.T, creds *identity.Credentials, d *Debug, svc *Serv return l.Addr().String() } +// noPermits is a permit service that issues no permits. +func noPermits(elected func() bool) *Permits { + return &Permits{Elected: elected, Discoverer: &Discoverer{Namespace: DefaultNamespace}} +} + func dialTLS(t *testing.T, addr string, cfg *tls.Config) *grpc.ClientConn { t.Helper() conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(credentials.NewTLS(cfg))) @@ -577,7 +582,9 @@ func TestParseAllowlist(t *testing.T) { if err := (Allowlist{}).Handshake(identity.Service(testSite, testService)); err == nil { t.Error("an empty allowlist accepted a service") } - if err := (Allowlist{}).Handshake(identity.Node(testSite, "ns", "pod")); err == nil { - t.Error("the gateway accepted a node identity") + // A node connects for the permit service alone; GatewayMethods keeps + // it from every other method (TestPermitAuthorization). + if err := (Allowlist{}).Handshake(identity.Node(testSite, "ns", "pod")); err != nil { + t.Errorf("the gateway refused a node identity: %v", err) } } diff --git a/internal/fabric/node/permit.go b/internal/fabric/node/permit.go new file mode 100644 index 000000000..5164b7e13 --- /dev/null +++ b/internal/fabric/node/permit.go @@ -0,0 +1,205 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package node + +import ( + "context" + "log/slog" + "sync" + "time" + + "google.golang.org/grpc" + "sigs.k8s.io/controller-runtime/pkg/client" + + permitv1 "go.datum.net/galactic/api/fabric/permit/v1" + fabricv1 "go.datum.net/galactic/api/fabric/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/query" +) + +// Probe permit bounds on the node. +const ( + // PermitStartupRefusal is how long after start a node refuses every + // permit: its record of consumed permits was lost with its last process, + // and a surviving permit lives at most 30 s plus skew. + PermitStartupRefusal = 32 * time.Second + // PermitGrace is how long a consumed permit ID is kept past its + // deadline. + PermitGrace = 2 * time.Second + // MaxPermitLifetime bounds how far away a permit's deadline may be, + // with one second of clock skew allowed. + MaxPermitLifetime = query.MaxNodeExecution + time.Second + // DefaultConsumedPermits and DefaultConsumedPermitBytes bound the + // consumed-permit set. + DefaultConsumedPermits = 4096 + DefaultConsumedPermitBytes = 2 << 20 + // permitReleaseTimeout bounds the best-effort release of a direct + // operator permit. + permitReleaseTimeout = 2 * time.Second + consumedOverhead = 64 +) + +// PermitGateway obtains and releases permits from the cell's gateway on a +// direct operator's behalf. permitv1.PermitServiceClient satisfies it. +type PermitGateway interface { + RequestPermit(ctx context.Context, in *permitv1.RequestPermitRequest, + opts ...grpc.CallOption) (*permitv1.RequestPermitResponse, error) + ReleasePermit(ctx context.Context, in *permitv1.ReleasePermitRequest, + opts ...grpc.CallOption) (*permitv1.ReleasePermitResponse, error) +} + +// Permits verifies and consumes probe permits. A permit is accepted once: +// for this node, request, operation and destination, before its deadline, +// at least PermitStartupRefusal after the node started, and only while the +// gateway election Lease, read uncached, still carries the permit's epoch. +// Consumed IDs are kept until their deadline plus PermitGrace in a set that +// fails closed when full. +type Permits struct { + // Reader reads the gateway's election Lease uncached. + Reader client.Reader + Namespace string + LeaseName string + // Require refuses a probe without a permit. A direct operator's probe + // then obtains one from Gateway. + Require bool + // Gateway issues permits for direct operator probes; nil refuses them + // when Require is set. + Gateway PermitGateway + // Started is when this process started. + Started time.Time + // MaxConsumed and MaxConsumedBytes bound the consumed set; zero selects + // the defaults. + MaxConsumed, MaxConsumedBytes int + + mu sync.Mutex + consumed map[string]consumedPermit + bytes int +} + +type consumedPermit struct { + until time.Time + size int +} + +// grant is a consumed permit's packet allowance and deadline. +type grant struct { + packets int + deadline time.Time +} + +// consume verifies p for q on node and records it consumed. +func (p *Permits) consume(ctx context.Context, pm *fabricv1.ProbePermit, node, requestID string, q query.Query, + now time.Time) (grant, error) { + refuse := func(msg string) (grant, error) { + return grant{}, errcode.Status(errcode.LimiterUnavailable, msg) + } + dst, err := query.ResolvedProbe(q) + if err != nil { + return grant{}, errcode.FromError(err) + } + deadline := pm.GetDeadline().AsTime() + switch { + case pm.GetId() == "" || !pm.GetDeadline().IsValid(): + return refuse("the probe permit is malformed") + case pm.GetNode() != node || pm.GetRequestId() != requestID || + pm.GetOperation() != QueryToProto(q).GetType() || pm.GetDestination() != dst.String(): + return refuse("the probe permit does not match this probe") + case !now.Before(deadline) || deadline.Sub(now) > MaxPermitLifetime: + return refuse("the probe permit has expired or is too long-lived") + case p.starting(now): + return refuse("this node accepts no probe permit until its startup refusal ends") + } + epoch, err := limit.ReadEpoch(ctx, p.Reader, p.Namespace, p.LeaseName, now) + if err != nil { + return grant{}, err + } + if epoch.String() != pm.GetEpoch() { + return grant{}, errcode.Status(errcode.OwnershipLost, "the probe permit is from another gateway epoch") + } + if err := p.record(pm.GetId(), deadline.Add(PermitGrace), now); err != nil { + return grant{}, err + } + return grant{packets: int(pm.GetPackets()), deadline: deadline}, nil +} + +// starting reports whether the node is still in its startup refusal. +func (p *Permits) starting(now time.Time) bool { + return now.Before(p.Started.Add(PermitStartupRefusal)) +} + +// record adds id to the consumed set, refusing a consumed ID and failing +// closed when the set is full of live entries. +func (p *Permits) record(id string, until, now time.Time) error { + maxN, maxBytes := p.MaxConsumed, p.MaxConsumedBytes + if maxN <= 0 { + maxN = DefaultConsumedPermits + } + if maxBytes <= 0 { + maxBytes = DefaultConsumedPermitBytes + } + p.mu.Lock() + defer p.mu.Unlock() + if p.consumed == nil { + p.consumed = map[string]consumedPermit{} + } + if c, ok := p.consumed[id]; ok && now.Before(c.until) { + return errcode.Status(errcode.LimiterUnavailable, "the probe permit was already used") + } + size := len(id) + consumedOverhead + if len(p.consumed) >= maxN || p.bytes+size > maxBytes { + for k, c := range p.consumed { + if !now.Before(c.until) { + delete(p.consumed, k) + p.bytes -= c.size + } + } + } + if len(p.consumed) >= maxN || p.bytes+size > maxBytes { + return errcode.Status(errcode.LimiterUnavailable, "this node's consumed-permit set is full") + } + p.consumed[id] = consumedPermit{until: until, size: size} + p.bytes += size + return nil +} + +// obtain asks the gateway for a permit for a direct operator's probe. A +// node in its startup refusal asks for none, since it could not use it and +// the gateway refunds nothing. +func (p *Permits) obtain(ctx context.Context, node, operator string, req *fabricv1.ExecuteRequest, now time.Time, +) (*fabricv1.ProbePermit, error) { + if p.Gateway == nil { + return nil, errcode.Status(errcode.LimiterUnavailable, "this node cannot obtain probe permits") + } + if p.starting(now) { + return nil, errcode.Status(errcode.LimiterUnavailable, + "this node accepts no probe permit until its startup refusal ends") + } + resp, err := p.Gateway.RequestPermit(ctx, &permitv1.RequestPermitRequest{ + Node: node, Operator: operator, RequestId: req.GetRequestId(), Query: req.GetQuery(), + ExpiresAt: req.GetExpiresAt(), + }) + if err != nil { + if errcode.Typed(err) { + return nil, err + } + return nil, errcode.Status(errcode.LimiterUnavailable, "the gateway did not issue a probe permit") + } + return resp.GetPermit(), nil +} + +// release tells the gateway a direct operator's permit is finished, so its +// slot frees before the permit expires. It is best effort: a lost release +// holds the slot only until the permit's deadline plus its grace. +func (p *Permits) release(node, id string) { + if p.Gateway == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), permitReleaseTimeout) + defer cancel() + if _, err := p.Gateway.ReleasePermit(ctx, &permitv1.ReleasePermitRequest{Node: node, Id: id}); err != nil { + slog.Debug("probe permit release failed", "code", errcode.Of(err)) + } +} diff --git a/internal/fabric/node/permit_test.go b/internal/fabric/node/permit_test.go new file mode 100644 index 000000000..e34a6ca82 --- /dev/null +++ b/internal/fabric/node/permit_test.go @@ -0,0 +1,362 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package node + +import ( + "context" + "errors" + "fmt" + "net/netip" + "sync" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/timestamppb" + coordinationv1 "k8s.io/api/coordination/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + permitv1 "go.datum.net/galactic/api/fabric/permit/v1" + fabricv1 "go.datum.net/galactic/api/fabric/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/identity" + "go.datum.net/galactic/internal/fabric/probe" + "go.datum.net/galactic/internal/fabric/query" +) + +const ( + leaseNS = "galactic-system" + leaseName = "fabric-api-gateway" + leaseEpoch = "lease-uid/gateway-0_a" +) + +func leaseReader(t *testing.T, holder string) client.Client { + t.Helper() + s := runtime.NewScheme() + _ = clientgoscheme.AddToScheme(s) + return fake.NewClientBuilder().WithScheme(s).WithObjects(&coordinationv1.Lease{ + ObjectMeta: metav1.ObjectMeta{Namespace: leaseNS, Name: leaseName, UID: "lease-uid"}, + Spec: coordinationv1.LeaseSpec{ + HolderIdentity: ptr.To(holder), LeaseDurationSeconds: ptr.To[int32](15), + RenewTime: &metav1.MicroTime{Time: time.Now().Add(time.Hour)}, + }, + }).Build() +} + +// packetProber sends packets probe packets through the limiter, stopping +// at the first refusal, and reports how many it sent. +type packetProber struct { + packets int + sent atomic.Int32 +} + +func (p *packetProber) send(ctx context.Context, opts probe.Options) error { + for range p.packets { + if err := opts.Limiter.Wait(ctx); err != nil { + return err + } + p.sent.Add(1) + } + return nil +} + +func (p *packetProber) Ping( + ctx context.Context, src, dst netip.Addr, opts probe.Options, +) (*fabricv1.PingResult, error) { + if err := p.send(ctx, opts); err != nil { + return nil, err + } + return &fabricv1.PingResult{Source: src.String(), Destination: dst.String(), Sent: uint32(p.packets)}, nil +} + +func (p *packetProber) Traceroute( + ctx context.Context, src, dst netip.Addr, opts probe.Options, +) (*fabricv1.TracerouteResult, error) { + if err := p.send(ctx, opts); err != nil { + return nil, err + } + return &fabricv1.TracerouteResult{Source: src.String(), Destination: dst.String()}, nil +} + +func permitServer(t *testing.T, prober Prober, mod func(*Permits)) *Server { + t.Helper() + p := &Permits{ + Reader: leaseReader(t, "gateway-0_a"), Namespace: leaseNS, LeaseName: leaseName, + Started: time.Now().Add(-time.Hour), + } + if mod != nil { + mod(p) + } + return newServer(t, newFakeFRR(t), func(c *Config) { + c.Prober = prober + c.Permits = p + c.PacketRate, c.PacketBurst = 1000, 1000 + }) +} + +// permitFor returns a gateway permit matching req, for a ping's packets. +func permitFor(req *fabricv1.ExecuteRequest) *fabricv1.ProbePermit { + q := QueryFromProto(req.GetQuery()) + dst, _ := query.ResolvedProbe(q) + return &fabricv1.ProbePermit{ + Id: "permit-" + req.GetRequestId(), Epoch: leaseEpoch, RequestId: req.GetRequestId(), Node: testNode, + Destination: dst.String(), Operation: req.GetQuery().GetType(), Packets: query.PingCount, + Deadline: timestamppb.New(time.Now().Add(20 * time.Second)), + } +} + +func TestPermitConsumedOnce(t *testing.T) { + prober := &packetProber{packets: 3} + s := permitServer(t, prober, nil) + ctx := WithCaller(t.Context(), identity.Gateway("dfw")) + + req := request(query.Query{Type: query.TypePing, Target: testPingDst}) + req.Permit = permitFor(req) + if _, err := s.Execute(ctx, req); err != nil { + t.Fatal(err) + } + // The same permit on another attempt is refused, though the request + // itself is new. + again := request(query.Query{Type: query.TypePing, Target: testPingDst}) + again.Permit = req.GetPermit() + again.Permit.RequestId = again.GetRequestId() + _, err := s.Execute(ctx, again) + wantCode(t, err, errcode.LimiterUnavailable) + if n := prober.sent.Load(); n != 3 { + t.Errorf("sent %d packets, want 3", n) + } + if info, _ := s.Info(ctx, &fabricv1.InfoRequest{}); !info.GetProbePermits() { + t.Error("Info does not report probe permits") + } +} + +func TestPermitRefusals(t *testing.T) { + ctx := WithCaller(t.Context(), identity.Gateway("dfw")) + cases := map[string]struct { + mod func(*fabricv1.ProbePermit) + perm func(*Permits) + code errcode.Code + }{ + "other epoch": { + mod: func(p *fabricv1.ProbePermit) { p.Epoch = "lease-uid/gateway-1_b" }, + code: errcode.OwnershipLost, + }, + "other node": {mod: func(p *fabricv1.ProbePermit) { p.Node = "other" }, code: errcode.LimiterUnavailable}, + "other request": {mod: func(p *fabricv1.ProbePermit) { p.RequestId = "x" }, code: errcode.LimiterUnavailable}, + "other dest": { + mod: func(p *fabricv1.ProbePermit) { p.Destination = "9.9.9.9" }, + code: errcode.LimiterUnavailable, + }, + "other operation": { + mod: func(p *fabricv1.ProbePermit) { p.Operation = fabricv1.QueryType_QUERY_TYPE_TRACEROUTE }, + code: errcode.LimiterUnavailable, + }, + "expired": {mod: func(p *fabricv1.ProbePermit) { + p.Deadline = timestamppb.New(time.Now().Add(-time.Second)) + }, code: errcode.LimiterUnavailable}, + "too long-lived": {mod: func(p *fabricv1.ProbePermit) { + p.Deadline = timestamppb.New(time.Now().Add(time.Minute)) + }, code: errcode.LimiterUnavailable}, + "no id": {mod: func(p *fabricv1.ProbePermit) { p.Id = "" }, code: errcode.LimiterUnavailable}, + "startup refusal": {perm: func(p *Permits) { p.Started = time.Now() }, code: errcode.LimiterUnavailable}, + "lease unreadable": {perm: func(p *Permits) { + p.Reader = leaseReader(t, "gateway-0_a") + p.LeaseName = "missing" + }, code: errcode.OwnershipLost}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + prober := &packetProber{packets: 3} + s := permitServer(t, prober, tc.perm) + req := request(query.Query{Type: query.TypePing, Target: testPingDst}) + req.Permit = permitFor(req) + if tc.mod != nil { + tc.mod(req.Permit) + } + _, err := s.Execute(ctx, req) + wantCode(t, err, tc.code) + if prober.sent.Load() != 0 { + t.Error("a refused permit sent packets") + } + }) + } +} + +func TestPermitSetFailsClosed(t *testing.T) { + s := permitServer(t, &packetProber{packets: 3}, func(p *Permits) { p.MaxConsumed = 1 }) + ctx := WithCaller(t.Context(), identity.Gateway("dfw")) + first := request(query.Query{Type: query.TypePing, Target: testPingDst}) + first.Permit = permitFor(first) + if _, err := s.Execute(ctx, first); err != nil { + t.Fatal(err) + } + second := request(query.Query{Type: query.TypePing, Target: testPingDst}) + second.Permit = permitFor(second) + _, err := s.Execute(ctx, second) + wantCode(t, err, errcode.LimiterUnavailable) +} + +func TestPermitAllowanceAndDeadline(t *testing.T) { + ctx := WithCaller(t.Context(), identity.Gateway("dfw")) + // A prober that would send more than the permit allows is stopped at + // the allowance. + prober := &packetProber{packets: 5} + s := permitServer(t, prober, nil) + req := request(query.Query{Type: query.TypePing, Target: testPingDst}) + req.Permit = permitFor(req) + if _, err := s.Execute(ctx, req); err == nil { + t.Fatal("a probe past its allowance succeeded") + } + if n := prober.sent.Load(); n != 3 { + t.Errorf("sent %d packets, want the allowance of 3", n) + } + + // The permit's deadline bounds the probe. + var deadline time.Time + s = permitServer(t, proberFunc(func(ctx context.Context) { + deadline, _ = ctx.Deadline() + }), nil) + req = request(query.Query{Type: query.TypePing, Target: testPingDst}) + req.Permit = permitFor(req) + want := req.GetPermit().GetDeadline().AsTime() + if _, err := s.Execute(ctx, req); err != nil { + t.Fatal(err) + } + if deadline.After(want) { + t.Errorf("probe deadline %s is after the permit's %s", deadline, want) + } +} + +type proberFunc func(context.Context) + +func (f proberFunc) Ping(ctx context.Context, src, dst netip.Addr, _ probe.Options) (*fabricv1.PingResult, error) { + f(ctx) + return &fabricv1.PingResult{Source: src.String(), Destination: dst.String()}, nil +} + +func (f proberFunc) Traceroute(ctx context.Context, src, dst netip.Addr, _ probe.Options, +) (*fabricv1.TracerouteResult, error) { + f(ctx) + return &fabricv1.TracerouteResult{Source: src.String(), Destination: dst.String()}, nil +} + +func TestPermitRequired(t *testing.T) { + gw := WithCaller(t.Context(), identity.Gateway("dfw")) + op := WithCaller(t.Context(), identity.Operator("dfw", "alice")) + + required := permitServer(t, &packetProber{packets: 3}, func(p *Permits) { p.Require = true }) + _, err := required.Execute(gw, request(query.Query{Type: query.TypePing, Target: testPingDst})) + wantCode(t, err, errcode.LimiterUnavailable) + // Reads never need a permit. + if _, err := required.Execute(gw, request(query.Query{Type: query.TypeBGPSummary})); err != nil { + t.Errorf("summary: %v", err) + } + // With no gateway to ask, a direct operator probe is refused. + _, err = required.Execute(op, request(query.Query{Type: query.TypePing, Target: testPingDst})) + wantCode(t, err, errcode.LimiterUnavailable) + + // An operator may never supply its own permit. + optional := permitServer(t, &packetProber{packets: 3}, nil) + req := request(query.Query{Type: query.TypePing, Target: testPingDst}) + req.Permit = permitFor(req) + _, err = optional.Execute(op, req) + wantCode(t, err, errcode.InvalidQuery) + + // A node without a permit checker refuses a permit it cannot verify. + bare := newServer(t, newFakeFRR(t), nil) + req = request(query.Query{Type: query.TypePing, Target: testPingDst}) + req.Permit = permitFor(req) + _, err = bare.Execute(gw, req) + wantCode(t, err, errcode.LimiterUnavailable) + if info, _ := bare.Info(gw, &fabricv1.InfoRequest{}); info.GetProbePermits() { + t.Error("a node without a permit checker reports probe permits") + } +} + +// fakeGateway issues permits for direct operator probes and records +// releases. +type fakeGateway struct { + mu sync.Mutex + requests []*permitv1.RequestPermitRequest + released []string + refuse error +} + +func (g *fakeGateway) RequestPermit(_ context.Context, in *permitv1.RequestPermitRequest, + _ ...grpc.CallOption) (*permitv1.RequestPermitResponse, error) { + g.mu.Lock() + defer g.mu.Unlock() + g.requests = append(g.requests, in) + if g.refuse != nil { + return nil, g.refuse + } + req := &fabricv1.ExecuteRequest{RequestId: in.GetRequestId(), Query: in.GetQuery()} + pm := permitFor(req) + pm.Id = fmt.Sprintf("direct-%d", len(g.requests)) + return &permitv1.RequestPermitResponse{Permit: pm}, nil +} + +func (g *fakeGateway) ReleasePermit(_ context.Context, in *permitv1.ReleasePermitRequest, + _ ...grpc.CallOption) (*permitv1.ReleasePermitResponse, error) { + g.mu.Lock() + defer g.mu.Unlock() + g.released = append(g.released, in.GetId()) + return &permitv1.ReleasePermitResponse{}, nil +} + +func TestDirectOperatorPermit(t *testing.T) { + gw := &fakeGateway{} + prober := &packetProber{packets: 3} + s := permitServer(t, prober, func(p *Permits) { p.Require = true; p.Gateway = gw }) + op := WithCaller(t.Context(), identity.Operator("dfw", "alice")) + + req := request(query.Query{Type: query.TypePing, Target: testPingDst}) + if _, err := s.Execute(op, req); err != nil { + t.Fatal(err) + } + gw.mu.Lock() + if len(gw.requests) != 1 || gw.requests[0].GetOperator() != "alice" || gw.requests[0].GetNode() != testNode || + gw.requests[0].GetRequestId() != req.GetRequestId() { + t.Errorf("permit requests = %v", gw.requests) + } + if len(gw.released) != 1 || gw.released[0] != "direct-1" { + t.Errorf("released = %v", gw.released) + } + gw.refuse = errcode.Retry(errcode.Throttled, "budget", "destination", time.Second) + gw.mu.Unlock() + + // A throttled operator probe reaches the operator as Throttled, with + // its retry guidance, and sends nothing. + _, err := s.Execute(op, request(query.Query{Type: query.TypePing, Target: testPingDst})) + wantCode(t, err, errcode.Throttled) + if d, ok := errcode.RetryDelay(err); !ok || d != time.Second { + t.Errorf("retry = %s, %v", d, ok) + } + if n := prober.sent.Load(); n != 3 { + t.Errorf("sent %d packets, want 3", n) + } + + gw.mu.Lock() + gw.refuse = errors.New("connection refused") + gw.mu.Unlock() + _, err = s.Execute(op, request(query.Query{Type: query.TypePing, Target: testPingDst})) + wantCode(t, err, errcode.LimiterUnavailable) + + // During its startup refusal a node does not ask for a permit it could + // not use, which would charge the operator's budget for nothing. + starting := &fakeGateway{} + s = permitServer(t, prober, func(p *Permits) { p.Require, p.Gateway, p.Started = true, starting, time.Now() }) + _, err = s.Execute(op, request(query.Query{Type: query.TypePing, Target: testPingDst})) + wantCode(t, err, errcode.LimiterUnavailable) + if len(starting.requests) != 0 { + t.Error("a starting node requested a permit") + } +} diff --git a/internal/fabric/node/server.go b/internal/fabric/node/server.go index d92606698..77072c45e 100644 --- a/internal/fabric/node/server.go +++ b/internal/fabric/node/server.go @@ -111,6 +111,10 @@ type Config struct { // are refused until the index has the full table; they never fall back // to scans. Index *index.Index + // Permits, when set, verifies and enforces each probe's permit from + // the cell gateway, and Info reports probe_permits. Without it a probe + // carrying a permit is refused. + Permits *Permits // Credentials reports whether mTLS credentials are loaded; nil means // always loaded. Credentials interface{ Err() error } @@ -333,10 +337,64 @@ func (s *Server) Execute( args := fmt.Sprintf("%s|%s|%s|%v", q.Type, q.AddressFamily, q.Target, req.GetBudgets().String()) policy := s.policyFor(ctx) return s.dedup.do(ctx, key, args, req.GetExpiresAt().AsTime(), func() (*fabricv1.ExecuteResponse, error) { - return s.execute(ctx, q, effectiveBudgets(req.GetBudgets(), s.cfg.Ceilings), policy) + var g *grant + if q.Type.Probe() { + pg, release, err := s.probeGrant(ctx, req, q) + if err != nil { + return nil, err + } + defer release() + g = pg + } + return s.execute(ctx, q, effectiveBudgets(req.GetBudgets(), s.cfg.Ceilings), policy, g) }) } +// probeGrant returns the permit grant a probe runs under, or nil when none +// is required. A gateway's permit is consumed; a direct operator's probe, +// when permits are required, obtains one from the gateway first and +// releases it when done. An operator may not supply a permit. The returned +// function, never nil, runs after the probe. +func (s *Server) probeGrant(ctx context.Context, req *fabricv1.ExecuteRequest, q query.Query, +) (*grant, func(), error) { + none := func() {} + p := s.cfg.Permits + pm := req.GetPermit() + caller, _ := CallerFrom(ctx) + if caller.Role == identity.RoleOperator { + if pm != nil { + return nil, none, errcode.Status(errcode.InvalidQuery, "only the cell gateway may supply a probe permit") + } + if p == nil || !p.Require { + return nil, none, nil + } + var err error + if pm, err = p.obtain(ctx, s.cfg.NodeName, caller.Name, req, s.cfg.Now()); err != nil { + return nil, none, err + } + release := func() { p.release(s.cfg.NodeName, pm.GetId()) } + g, err := p.consume(ctx, pm, s.cfg.NodeName, req.GetRequestId(), q, s.cfg.Now()) + if err != nil { + release() + return nil, none, err + } + return &g, release, nil + } + switch { + case pm == nil && (p == nil || !p.Require): + return nil, none, nil + case pm == nil: + return nil, none, errcode.Status(errcode.LimiterUnavailable, "this node requires a probe permit") + case p == nil: + return nil, none, errcode.Status(errcode.LimiterUnavailable, "this node cannot verify probe permits") + } + g, err := p.consume(ctx, pm, s.cfg.NodeName, req.GetRequestId(), q, s.cfg.Now()) + if err != nil { + return nil, none, err + } + return &g, none, nil +} + // validate checks a request and returns its canonical query and the // absolute deadline that bounds it, queueing included. func (s *Server) validate(ctx context.Context, req *fabricv1.ExecuteRequest) (query.Query, time.Time, error) { @@ -396,9 +454,10 @@ func (s *Server) policyFor(ctx context.Context) query.DestinationPolicy { return s.cfg.PublicPolicy } -// execute runs a validated query within the node's budgets. +// execute runs a validated query within the node's budgets, and a probe +// within its permit grant g, when one applies. func (s *Server) execute( - ctx context.Context, q query.Query, b budgets, policy query.DestinationPolicy, + ctx context.Context, q query.Query, b budgets, policy query.DestinationPolicy, g *grant, ) (*fabricv1.ExecuteResponse, error) { select { case s.sem <- struct{}{}: @@ -419,7 +478,7 @@ func (s *Server) execute( obs := &fabricv1.Observation{Node: s.cfg.NodeName, SampleTime: timestamppb.New(started)} var err error if q.Type.Probe() { - err = s.runProbe(ctx, q, policy, obs) + err = s.runProbe(ctx, q, policy, obs, g) } else { err = s.runFRR(ctx, q, b, obs) } @@ -618,7 +677,7 @@ func (s *Server) run(ctx context.Context, cmd frr.Command) (frr.Response, error) // runProbe sends a ping or traceroute from this node's source for the // query's family. func (s *Server) runProbe( - ctx context.Context, q query.Query, policy query.DestinationPolicy, obs *fabricv1.Observation, + ctx context.Context, q query.Query, policy query.DestinationPolicy, obs *fabricv1.Observation, g *grant, ) error { dst, err := query.ResolvedProbe(q) if err != nil { @@ -642,7 +701,16 @@ func (s *Server) runProbe( default: return errcode.Status(errcode.NodeBusy, "the node's probe budget is full") } - opts := probe.Options{Limiter: packetLimiter{s}} + limiter := &packetLimiter{s: s, allowance: -1} + if g != nil { + // No packet leaves after the permit's deadline or beyond its + // allowance. + var cancel context.CancelFunc + ctx, cancel = context.WithDeadline(ctx, g.deadline) + defer cancel() + limiter.allowance = g.packets + } + opts := probe.Options{Limiter: limiter} if q.Type == query.TypePing { res, err := s.cfg.Prober.Ping(ctx, src, dst, opts) if err != nil { @@ -660,13 +728,23 @@ func (s *Server) runProbe( } // packetLimiter paces probe packets through the node-wide rate limiter and -// counts them. -type packetLimiter struct{ s *Server } +// counts them. A non-negative allowance is a permit's packet budget; a +// packet beyond it is refused. +type packetLimiter struct { + s *Server + allowance int +} -func (l packetLimiter) Wait(ctx context.Context) error { +func (l *packetLimiter) Wait(ctx context.Context) error { + if l.allowance == 0 { + return errcode.Status(errcode.LimiterUnavailable, "the probe permit's packet allowance is spent") + } if err := l.s.limiter.Wait(ctx); err != nil { return err } + if l.allowance > 0 { + l.allowance-- + } if m := l.s.cfg.Metrics; m != nil { m.probePackets.Inc() } @@ -850,6 +928,7 @@ func (s *Server) Info(context.Context, *fabricv1.InfoRequest) (*fabricv1.InfoRes FrrVersion: st.version.Raw, DiagnosticsAvailable: reason == "", UnavailableReason: reason, + ProbePermits: s.cfg.Permits != nil, } for _, t := range query.Types { if t.Expensive() && s.searchUnavailable() != "" {