diff --git a/cmd/uncloud/caddy/root.go b/cmd/uncloud/caddy/root.go index 1f71475f..b02a5e2a 100644 --- a/cmd/uncloud/caddy/root.go +++ b/cmd/uncloud/caddy/root.go @@ -12,6 +12,7 @@ func NewRootCommand() *cobra.Command { cmd.AddCommand( NewConfigCommand(), NewDeployCommand(), + NewUpstreamsCommand(), ) return cmd } diff --git a/cmd/uncloud/caddy/upstreams.go b/cmd/uncloud/caddy/upstreams.go new file mode 100644 index 00000000..6f9b43f0 --- /dev/null +++ b/cmd/uncloud/caddy/upstreams.go @@ -0,0 +1,76 @@ +package caddy + +import ( + "context" + "fmt" + "os" + "slices" + "strings" + "text/tabwriter" + + "github.com/psviderski/uncloud/internal/cli" + "github.com/psviderski/uncloud/internal/machine/api/pb" + "github.com/spf13/cobra" +) + +type upstreamsOptions struct { + machine string +} + +func NewUpstreamsCommand() *cobra.Command { + opts := upstreamsOptions{} + + cmd := &cobra.Command{ + Use: "upstreams", + Short: "List Caddy upstreams and their health status.", + Long: "List Caddy upstreams and their health status from the connected machine or a specified one.", + RunE: func(cmd *cobra.Command, args []string) error { + uncli := cmd.Context().Value("cli").(*cli.CLI) + return runUpstreams(cmd.Context(), uncli, opts) + }, + } + + cmd.Flags().StringVarP(&opts.machine, "machine", "m", "", + "Name or ID of the machine to get the upstreams from. (default is connected machine)") + + return cmd +} + +func runUpstreams(ctx context.Context, uncli *cli.CLI, opts upstreamsOptions) error { + clusterClient, err := uncli.ConnectCluster(ctx) + if err != nil { + return fmt.Errorf("connect to cluster: %w", err) + } + defer clusterClient.Close() + + if opts.machine != "" { + // If a specific machine is requested, use it to get the Caddy upstreams. + ctx, _, err = clusterClient.ProxyMachinesContext(ctx, []string{opts.machine}) + if err != nil { + return err + } + } + + resp, err := clusterClient.Caddy.GetUpstreams(ctx, nil) + if err != nil { + return fmt.Errorf("get Caddy upstreams: %w", err) + } + + w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0) + fmt.Fprintln(w, "HOST\tUPSTREAMS") + + slices.SortFunc(resp.Hosts, func(a, b *pb.HostUpstreams) int { + return strings.Compare(a.Host, b.Host) + }) + + for _, host := range resp.Hosts { + var upstreamsStrs []string + for _, u := range host.Upstreams { + s := fmt.Sprintf("%s (%s, reqs: %d, fails: %d)", + u.Address, u.Status, u.NumRequests, u.Fails) + upstreamsStrs = append(upstreamsStrs, s) + } + fmt.Fprintf(w, "%s\t%s\n", host.Host, strings.Join(upstreamsStrs, ", ")) + } + return w.Flush() +} diff --git a/internal/machine/api/pb/caddy.pb.go b/internal/machine/api/pb/caddy.pb.go index dae4ef8a..f7074508 100644 --- a/internal/machine/api/pb/caddy.pb.go +++ b/internal/machine/api/pb/caddy.pb.go @@ -79,6 +79,179 @@ func (x *GetCaddyConfigResponse) GetModifiedAt() *timestamppb.Timestamp { return nil } +type GetCaddyUpstreamsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Hosts []*HostUpstreams `protobuf:"bytes,1,rep,name=hosts,proto3" json:"hosts,omitempty"` +} + +func (x *GetCaddyUpstreamsResponse) Reset() { + *x = GetCaddyUpstreamsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_internal_machine_api_pb_caddy_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetCaddyUpstreamsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCaddyUpstreamsResponse) ProtoMessage() {} + +func (x *GetCaddyUpstreamsResponse) ProtoReflect() protoreflect.Message { + mi := &file_internal_machine_api_pb_caddy_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCaddyUpstreamsResponse.ProtoReflect.Descriptor instead. +func (*GetCaddyUpstreamsResponse) Descriptor() ([]byte, []int) { + return file_internal_machine_api_pb_caddy_proto_rawDescGZIP(), []int{1} +} + +func (x *GetCaddyUpstreamsResponse) GetHosts() []*HostUpstreams { + if x != nil { + return x.Hosts + } + return nil +} + +type HostUpstreams struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"` + Upstreams []*Upstream `protobuf:"bytes,2,rep,name=upstreams,proto3" json:"upstreams,omitempty"` +} + +func (x *HostUpstreams) Reset() { + *x = HostUpstreams{} + if protoimpl.UnsafeEnabled { + mi := &file_internal_machine_api_pb_caddy_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *HostUpstreams) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HostUpstreams) ProtoMessage() {} + +func (x *HostUpstreams) ProtoReflect() protoreflect.Message { + mi := &file_internal_machine_api_pb_caddy_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HostUpstreams.ProtoReflect.Descriptor instead. +func (*HostUpstreams) Descriptor() ([]byte, []int) { + return file_internal_machine_api_pb_caddy_proto_rawDescGZIP(), []int{2} +} + +func (x *HostUpstreams) GetHost() string { + if x != nil { + return x.Host + } + return "" +} + +func (x *HostUpstreams) GetUpstreams() []*Upstream { + if x != nil { + return x.Upstreams + } + return nil +} + +type Upstream struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` + Fails int64 `protobuf:"varint,3,opt,name=fails,proto3" json:"fails,omitempty"` + NumRequests int64 `protobuf:"varint,4,opt,name=num_requests,json=numRequests,proto3" json:"num_requests,omitempty"` +} + +func (x *Upstream) Reset() { + *x = Upstream{} + if protoimpl.UnsafeEnabled { + mi := &file_internal_machine_api_pb_caddy_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Upstream) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Upstream) ProtoMessage() {} + +func (x *Upstream) ProtoReflect() protoreflect.Message { + mi := &file_internal_machine_api_pb_caddy_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Upstream.ProtoReflect.Descriptor instead. +func (*Upstream) Descriptor() ([]byte, []int) { + return file_internal_machine_api_pb_caddy_proto_rawDescGZIP(), []int{3} +} + +func (x *Upstream) GetAddress() string { + if x != nil { + return x.Address + } + return "" +} + +func (x *Upstream) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *Upstream) GetFails() int64 { + if x != nil { + return x.Fails + } + return 0 +} + +func (x *Upstream) GetNumRequests() int64 { + if x != nil { + return x.NumRequests + } + return 0 +} + var File_internal_machine_api_pb_caddy_proto protoreflect.FileDescriptor var file_internal_machine_api_pb_caddy_proto_rawDesc = []byte{ @@ -95,16 +268,38 @@ var file_internal_machine_api_pb_caddy_proto_rawDesc = []byte{ 0x12, 0x3b, 0x0a, 0x0b, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, - 0x70, 0x52, 0x0a, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x41, 0x74, 0x32, 0x49, 0x0a, - 0x05, 0x43, 0x61, 0x64, 0x64, 0x79, 0x12, 0x40, 0x0a, 0x09, 0x47, 0x65, 0x74, 0x43, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1b, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x61, 0x64, 0x64, 0x79, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x37, 0x5a, 0x35, 0x67, 0x69, 0x74, 0x68, - 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x70, 0x73, 0x76, 0x69, 0x64, 0x65, 0x72, 0x73, 0x6b, - 0x69, 0x2f, 0x75, 0x6e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, - 0x61, 0x6c, 0x2f, 0x6d, 0x61, 0x63, 0x68, 0x69, 0x6e, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x70, - 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x70, 0x52, 0x0a, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x41, 0x74, 0x22, 0x45, 0x0a, + 0x19, 0x47, 0x65, 0x74, 0x43, 0x61, 0x64, 0x64, 0x79, 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, + 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x05, 0x68, 0x6f, + 0x73, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x61, 0x70, 0x69, 0x2e, + 0x48, 0x6f, 0x73, 0x74, 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x52, 0x05, 0x68, + 0x6f, 0x73, 0x74, 0x73, 0x22, 0x50, 0x0a, 0x0d, 0x48, 0x6f, 0x73, 0x74, 0x55, 0x70, 0x73, 0x74, + 0x72, 0x65, 0x61, 0x6d, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x12, 0x2b, 0x0a, 0x09, 0x75, 0x70, 0x73, + 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x61, + 0x70, 0x69, 0x2e, 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x09, 0x75, 0x70, 0x73, + 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x22, 0x75, 0x0a, 0x08, 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, + 0x61, 0x6d, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x16, 0x0a, 0x06, + 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x74, + 0x61, 0x74, 0x75, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x61, 0x69, 0x6c, 0x73, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x03, 0x52, 0x05, 0x66, 0x61, 0x69, 0x6c, 0x73, 0x12, 0x21, 0x0a, 0x0c, 0x6e, 0x75, + 0x6d, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, + 0x52, 0x0b, 0x6e, 0x75, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x73, 0x32, 0x91, 0x01, + 0x0a, 0x05, 0x43, 0x61, 0x64, 0x64, 0x79, 0x12, 0x40, 0x0a, 0x09, 0x47, 0x65, 0x74, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1b, 0x2e, 0x61, + 0x70, 0x69, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x61, 0x64, 0x64, 0x79, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x46, 0x0a, 0x0c, 0x47, 0x65, 0x74, + 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, + 0x79, 0x1a, 0x1e, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x61, 0x64, 0x64, 0x79, + 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x42, 0x37, 0x5a, 0x35, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, + 0x70, 0x73, 0x76, 0x69, 0x64, 0x65, 0x72, 0x73, 0x6b, 0x69, 0x2f, 0x75, 0x6e, 0x63, 0x6c, 0x6f, + 0x75, 0x64, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x6d, 0x61, 0x63, 0x68, + 0x69, 0x6e, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x33, } var ( @@ -119,21 +314,28 @@ func file_internal_machine_api_pb_caddy_proto_rawDescGZIP() []byte { return file_internal_machine_api_pb_caddy_proto_rawDescData } -var file_internal_machine_api_pb_caddy_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_internal_machine_api_pb_caddy_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_internal_machine_api_pb_caddy_proto_goTypes = []any{ - (*GetCaddyConfigResponse)(nil), // 0: api.GetCaddyConfigResponse - (*timestamppb.Timestamp)(nil), // 1: google.protobuf.Timestamp - (*emptypb.Empty)(nil), // 2: google.protobuf.Empty + (*GetCaddyConfigResponse)(nil), // 0: api.GetCaddyConfigResponse + (*GetCaddyUpstreamsResponse)(nil), // 1: api.GetCaddyUpstreamsResponse + (*HostUpstreams)(nil), // 2: api.HostUpstreams + (*Upstream)(nil), // 3: api.Upstream + (*timestamppb.Timestamp)(nil), // 4: google.protobuf.Timestamp + (*emptypb.Empty)(nil), // 5: google.protobuf.Empty } var file_internal_machine_api_pb_caddy_proto_depIdxs = []int32{ - 1, // 0: api.GetCaddyConfigResponse.modified_at:type_name -> google.protobuf.Timestamp - 2, // 1: api.Caddy.GetConfig:input_type -> google.protobuf.Empty - 0, // 2: api.Caddy.GetConfig:output_type -> api.GetCaddyConfigResponse - 2, // [2:3] is the sub-list for method output_type - 1, // [1:2] is the sub-list for method input_type - 1, // [1:1] is the sub-list for extension type_name - 1, // [1:1] is the sub-list for extension extendee - 0, // [0:1] is the sub-list for field type_name + 4, // 0: api.GetCaddyConfigResponse.modified_at:type_name -> google.protobuf.Timestamp + 2, // 1: api.GetCaddyUpstreamsResponse.hosts:type_name -> api.HostUpstreams + 3, // 2: api.HostUpstreams.upstreams:type_name -> api.Upstream + 5, // 3: api.Caddy.GetConfig:input_type -> google.protobuf.Empty + 5, // 4: api.Caddy.GetUpstreams:input_type -> google.protobuf.Empty + 0, // 5: api.Caddy.GetConfig:output_type -> api.GetCaddyConfigResponse + 1, // 6: api.Caddy.GetUpstreams:output_type -> api.GetCaddyUpstreamsResponse + 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_internal_machine_api_pb_caddy_proto_init() } @@ -154,6 +356,42 @@ func file_internal_machine_api_pb_caddy_proto_init() { return nil } } + file_internal_machine_api_pb_caddy_proto_msgTypes[1].Exporter = func(v any, i int) any { + switch v := v.(*GetCaddyUpstreamsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_internal_machine_api_pb_caddy_proto_msgTypes[2].Exporter = func(v any, i int) any { + switch v := v.(*HostUpstreams); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_internal_machine_api_pb_caddy_proto_msgTypes[3].Exporter = func(v any, i int) any { + switch v := v.(*Upstream); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } } type x struct{} out := protoimpl.TypeBuilder{ @@ -161,7 +399,7 @@ func file_internal_machine_api_pb_caddy_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_internal_machine_api_pb_caddy_proto_rawDesc, NumEnums: 0, - NumMessages: 1, + NumMessages: 4, NumExtensions: 0, NumServices: 1, }, diff --git a/internal/machine/api/pb/caddy.proto b/internal/machine/api/pb/caddy.proto index 5425ab6e..ea5393e3 100644 --- a/internal/machine/api/pb/caddy.proto +++ b/internal/machine/api/pb/caddy.proto @@ -10,6 +10,9 @@ import "google/protobuf/timestamp.proto"; service Caddy { // GetConfig retrieves the current Caddy configuration from the machine. rpc GetConfig(google.protobuf.Empty) returns (GetCaddyConfigResponse); + + // GetUpstreams retrieves the status of Caddy upstreams. + rpc GetUpstreams(google.protobuf.Empty) returns (GetCaddyUpstreamsResponse); } message GetCaddyConfigResponse { @@ -17,4 +20,20 @@ message GetCaddyConfigResponse { string caddyfile = 1; // Timestamp when the config was last modified. google.protobuf.Timestamp modified_at = 2; +} + +message GetCaddyUpstreamsResponse { + repeated HostUpstreams hosts = 1; +} + +message HostUpstreams { + string host = 1; + repeated Upstream upstreams = 2; +} + +message Upstream { + string address = 1; + string status = 2; + int64 fails = 3; + int64 num_requests = 4; } \ No newline at end of file diff --git a/internal/machine/api/pb/caddy_grpc.pb.go b/internal/machine/api/pb/caddy_grpc.pb.go index ab140a5f..c8891485 100644 --- a/internal/machine/api/pb/caddy_grpc.pb.go +++ b/internal/machine/api/pb/caddy_grpc.pb.go @@ -20,7 +20,8 @@ import ( const _ = grpc.SupportPackageIsVersion9 const ( - Caddy_GetConfig_FullMethodName = "/api.Caddy/GetConfig" + Caddy_GetConfig_FullMethodName = "/api.Caddy/GetConfig" + Caddy_GetUpstreams_FullMethodName = "/api.Caddy/GetUpstreams" ) // CaddyClient is the client API for Caddy service. @@ -29,6 +30,8 @@ const ( type CaddyClient interface { // GetConfig retrieves the current Caddy configuration from the machine. GetConfig(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GetCaddyConfigResponse, error) + // GetUpstreams retrieves the status of Caddy upstreams. + GetUpstreams(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GetCaddyUpstreamsResponse, error) } type caddyClient struct { @@ -49,12 +52,24 @@ func (c *caddyClient) GetConfig(ctx context.Context, in *emptypb.Empty, opts ... return out, nil } +func (c *caddyClient) GetUpstreams(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GetCaddyUpstreamsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetCaddyUpstreamsResponse) + err := c.cc.Invoke(ctx, Caddy_GetUpstreams_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // CaddyServer is the server API for Caddy service. // All implementations must embed UnimplementedCaddyServer // for forward compatibility. type CaddyServer interface { // GetConfig retrieves the current Caddy configuration from the machine. GetConfig(context.Context, *emptypb.Empty) (*GetCaddyConfigResponse, error) + // GetUpstreams retrieves the status of Caddy upstreams. + GetUpstreams(context.Context, *emptypb.Empty) (*GetCaddyUpstreamsResponse, error) mustEmbedUnimplementedCaddyServer() } @@ -68,6 +83,9 @@ type UnimplementedCaddyServer struct{} func (UnimplementedCaddyServer) GetConfig(context.Context, *emptypb.Empty) (*GetCaddyConfigResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetConfig not implemented") } +func (UnimplementedCaddyServer) GetUpstreams(context.Context, *emptypb.Empty) (*GetCaddyUpstreamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetUpstreams not implemented") +} func (UnimplementedCaddyServer) mustEmbedUnimplementedCaddyServer() {} func (UnimplementedCaddyServer) testEmbeddedByValue() {} @@ -107,6 +125,24 @@ func _Caddy_GetConfig_Handler(srv interface{}, ctx context.Context, dec func(int return interceptor(ctx, in, info, handler) } +func _Caddy_GetUpstreams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(emptypb.Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CaddyServer).GetUpstreams(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Caddy_GetUpstreams_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CaddyServer).GetUpstreams(ctx, req.(*emptypb.Empty)) + } + return interceptor(ctx, in, info, handler) +} + // Caddy_ServiceDesc is the grpc.ServiceDesc for Caddy service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -118,6 +154,10 @@ var Caddy_ServiceDesc = grpc.ServiceDesc{ MethodName: "GetConfig", Handler: _Caddy_GetConfig_Handler, }, + { + MethodName: "GetUpstreams", + Handler: _Caddy_GetUpstreams_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "internal/machine/api/pb/caddy.proto", diff --git a/internal/machine/caddyconfig/client.go b/internal/machine/caddyconfig/client.go index c988e8f1..d2b43bb9 100644 --- a/internal/machine/caddyconfig/client.go +++ b/internal/machine/caddyconfig/client.go @@ -140,3 +140,64 @@ func (c *CaddyAdminClient) Validate(ctx context.Context, caddyfile string) error _, err := c.Adapt(ctx, caddyfile) return err } + +type UpstreamStatus struct { + Address string `json:"address"` + Fails int64 `json:"fails"` + NumRequests int64 `json:"num_requests"` +} + +// GetUpstreams retrieves the status of Caddy upstreams. +func (c *CaddyAdminClient) GetUpstreams(ctx context.Context) ([]UpstreamStatus, error) { + req, err := http.NewRequestWithContext(ctx, "GET", "http://localhost/reverse_proxy/upstreams", nil) + if err != nil { + return nil, fmt.Errorf("create upstreams request: %w", err) + } + + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("send upstreams request: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read response body: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("unexpected status code %d: %s", resp.StatusCode, string(body)) + } + + var upstreams []UpstreamStatus + if err := json.Unmarshal(body, &upstreams); err != nil { + return nil, fmt.Errorf("decode upstreams response: %w", err) + } + + return upstreams, nil +} + +// GetConfigJSON retrieves the current Caddy configuration as a raw JSON byte slice. +func (c *CaddyAdminClient) GetConfigJSON(ctx context.Context) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, "GET", "http://localhost/config/", nil) + if err != nil { + return nil, fmt.Errorf("create config request: %w", err) + } + + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("send config request: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read response body: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("unexpected status code %d: %s", resp.StatusCode, string(body)) + } + + return body, nil +} diff --git a/internal/machine/caddyconfig/server.go b/internal/machine/caddyconfig/server.go index 018ca4fb..fdce4cf6 100644 --- a/internal/machine/caddyconfig/server.go +++ b/internal/machine/caddyconfig/server.go @@ -37,3 +37,41 @@ func (s *Server) GetConfig(ctx context.Context, _ *emptypb.Empty) (*pb.GetCaddyC ModifiedAt: timestamppb.New(modifiedAt), }, nil } + +// GetUpstreams retrieves the status of Caddy upstreams. +func (s *Server) GetUpstreams(ctx context.Context, _ *emptypb.Empty) (*pb.GetCaddyUpstreamsResponse, error) { + hostUpstreams, err := s.service.GetUpstreams(ctx) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + var pbHosts []*pb.HostUpstreams + for host, upstreams := range hostUpstreams { + var pbUpstreams []*pb.Upstream + for _, u := range upstreams { + // TODO: This logic assumes the default Caddy health check configuration where max_fails is 1. + // If a custom configuration increases max_fails, an upstream with fails > 0 might still be healthy. + // For accurate status in all cases, we should query the Caddy /metrics endpoint and check + // the 'caddy_reverse_proxy_upstreams_healthy' gauge. + statusStr := "healthy" + if u.Fails > 0 { + statusStr = "unhealthy" + } + + pbUpstreams = append(pbUpstreams, &pb.Upstream{ + Address: u.Address, + Status: statusStr, + Fails: u.Fails, + NumRequests: u.NumRequests, + }) + } + pbHosts = append(pbHosts, &pb.HostUpstreams{ + Host: host, + Upstreams: pbUpstreams, + }) + } + + return &pb.GetCaddyUpstreamsResponse{ + Hosts: pbHosts, + }, nil +} diff --git a/internal/machine/caddyconfig/service.go b/internal/machine/caddyconfig/service.go index 4ba72ba9..ae88f347 100644 --- a/internal/machine/caddyconfig/service.go +++ b/internal/machine/caddyconfig/service.go @@ -1,20 +1,28 @@ package caddyconfig import ( + "context" + "encoding/json" "fmt" "os" "path/filepath" "time" ) -// Service provides methods to interact with the Caddy configuration on the machine. +// Service provides methods to interact with the Caddy configuration on the machine +// and the running Caddy instance via its Admin API. type Service struct { configDir string + client *CaddyAdminClient } -// NewService creates a new Service instance with the specified Caddy configuration directory. -func NewService(configDir string) *Service { - return &Service{configDir: configDir} +// NewService creates a new Service instance with the specified Caddy configuration directory +// and Admin API socket path. +func NewService(configDir, adminSock string) *Service { + return &Service{ + configDir: configDir, + client: NewCaddyAdminClient(adminSock), + } } // Caddyfile retrieves the current Caddy configuration (Caddyfile) from the machine's config directory. @@ -33,3 +41,112 @@ func (s *Service) Caddyfile() (string, time.Time, error) { return string(content), fileInfo.ModTime(), nil } + +// GetUpstreams retrieves the status of Caddy upstreams grouped by host. +func (s *Service) GetUpstreams(ctx context.Context) (map[string][]UpstreamStatus, error) { + if !s.client.IsAvailable(ctx) { + return nil, fmt.Errorf("caddy is not running") + } + + // Get the flat list of upstream statuses. + statuses, err := s.client.GetUpstreams(ctx) + if err != nil { + return nil, fmt.Errorf("get upstreams status: %w", err) + } + statusMap := make(map[string]UpstreamStatus, len(statuses)) + for _, st := range statuses { + statusMap[st.Address] = st + } + + // Get the current configuration to map upstreams to hosts. + configJSON, err := s.client.GetConfigJSON(ctx) + if err != nil { + return nil, fmt.Errorf("get caddy config: %w", err) + } + + var config caddyConfig + if err := json.Unmarshal(configJSON, &config); err != nil { + return nil, fmt.Errorf("parse caddy config: %w", err) + } + + result := make(map[string][]UpstreamStatus) + + for _, server := range config.Apps.HTTP.Servers { + collectUpstreams(server.Routes, nil, statusMap, result) + } + + return result, nil +} + +func collectUpstreams(routes []caddyRoute, parentHosts []string, statusMap map[string]UpstreamStatus, result map[string][]UpstreamStatus) { + for _, route := range routes { + // Calculate the hosts for this route. + var currentHosts []string + for _, m := range route.Match { + currentHosts = append(currentHosts, m.Host...) + } + + effectiveHosts := parentHosts + if len(currentHosts) > 0 { + if len(parentHosts) > 0 { + // Intersection of hosts. + var intersection []string + for _, h1 := range parentHosts { + for _, h2 := range currentHosts { + if h1 == h2 { + intersection = append(intersection, h1) + } + } + } + effectiveHosts = intersection + } else { + effectiveHosts = currentHosts + } + } + + for _, h := range route.Handle { + if h.Handler == "reverse_proxy" { + for _, u := range h.Upstreams { + if st, ok := statusMap[u.Dial]; ok { + for _, host := range effectiveHosts { + result[host] = append(result[host], st) + } + } + } + } else if h.Handler == "subroute" { + collectUpstreams(h.Routes, effectiveHosts, statusMap, result) + } + } + } +} + +type caddyConfig struct { + Apps struct { + HTTP struct { + Servers map[string]caddyServer `json:"servers"` + } `json:"http"` + } `json:"apps"` +} + +type caddyServer struct { + Routes []caddyRoute `json:"routes"` +} + +type caddyRoute struct { + Match []caddyMatch `json:"match"` + Handle []caddyHandle `json:"handle"` +} + +type caddyMatch struct { + Host []string `json:"host"` +} + +type caddyHandle struct { + Handler string `json:"handler"` + Routes []caddyRoute `json:"routes"` // For subroute + Upstreams []caddyUpstream `json:"upstreams"` // For reverse_proxy +} + +type caddyUpstream struct { + Dial string `json:"dial"` +} diff --git a/internal/machine/machine.go b/internal/machine/machine.go index a2d1749b..eaaf2883 100644 --- a/internal/machine/machine.go +++ b/internal/machine/machine.go @@ -290,7 +290,7 @@ func NewMachine(config *Config) (*Machine, error) { NetworkReady: m.IsNetworkReady, WaitForNetworkReady: m.WaitForNetworkReady, }) - caddyServer := caddyconfig.NewServer(caddyconfig.NewService(config.CaddyConfigDir)) + caddyServer := caddyconfig.NewServer(caddyconfig.NewService(config.CaddyConfigDir, DefaultCaddyAdminSockPath)) m.localMachineServer = newGRPCServer(m, c, m.dockerServer, caddyServer) if m.Initialised() {