跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

kubernetesservice.go

233 行 · 5.6 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package kubernetesservice
5
6import (
7 "bufio"
8 "bytes"
9 "context"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "io"
14 "net"
15 "os"
16 "os/exec"
17 "strings"
18 "sync"
19 "time"
20
21 "github.com/docker/go-units"
22 "github.com/sirupsen/logrus"
23)
24
25type Protocol string
26
27const (
28 TCP Protocol = "tcp"
29 UDP Protocol = "udp"
30)
31
32type Entry struct {
33 Protocol Protocol
34 IP net.IP
35 Port uint16
36}
37
38type ServiceWatcher struct {
39 rwMutex sync.RWMutex
40 // key: namespace/name
41 serviceSpecs map[string]*serviceSpec
42}
43
44func NewServiceWatcher() *ServiceWatcher {
45 return &ServiceWatcher{serviceSpecs: make(map[string]*serviceSpec)}
46}
47
48func (s *ServiceWatcher) Start(ctx context.Context) {
49 logrus.Info("Monitoring kubernetes services")
50 go s.loopAttemptToStartKubectl(ctx)
51}
52
53func (s *ServiceWatcher) loopAttemptToStartKubectl(ctx context.Context) {
54 const retryInterval = 10 * time.Second
55
56 for i := 0; ; i++ {
57 // The first iteration does not need to wait for retryInterval.
58 if i > 0 {
59 select {
60 case <-ctx.Done():
61 return
62 case <-time.After(retryInterval):
63 }
64 }
65 s.attemptToStartKubectl(ctx)
66 }
67}
68
69func (s *ServiceWatcher) attemptToStartKubectl(ctx context.Context) {
70 kubectl, err := exec.LookPath("kubectl")
71 if err != nil {
72 logrus.WithError(err).Debugf("kubectl not available; will retry")
73 return
74 }
75 kubeconfig := chooseKubeconfig()
76 // TODO: ensure that kubeconfig points to a local cluster
77 if err := canGetServices(ctx, kubectl, kubeconfig); err != nil {
78 logrus.WithError(err).Debugf("kubectl auth can-i ... failed; will retry")
79 return
80 }
81
82 cmd := exec.CommandContext(ctx, kubectl,
83 "get", "--all-namespaces", "service", "--watch", "--output-watch-events", "--output", "json")
84 if kubeconfig != "" {
85 cmd.Env = append(os.Environ(), "KUBECONFIG="+kubeconfig)
86 }
87 if err := s.startAndStreamKubectl(cmd); err != nil {
88 logrus.WithError(err).Warn("kubectl watch failed; will retry")
89 }
90}
91
92func chooseKubeconfig() string {
93 if kubeconfig := os.Getenv("KUBECONFIG"); kubeconfig != "" {
94 return kubeconfig
95 }
96 candidateKubeConfigs := []string{
97 "/etc/rancher/k3s/k3s.yaml",
98 "/root/.kube/config.localhost", // Created by template:k8s
99 "/root/.kube/config",
100 }
101 for _, kc := range candidateKubeConfigs {
102 if _, err := os.Stat(kc); !errors.Is(err, os.ErrNotExist) {
103 return kc
104 }
105 }
106 return ""
107}
108
109func canGetServices(ctx context.Context, kubectl, kubeconfig string) error {
110 cmd := exec.CommandContext(ctx, kubectl, "auth", "can-i", "get", "service")
111 if kubeconfig != "" {
112 cmd.Env = append(os.Environ(), "KUBECONFIG="+kubeconfig)
113 }
114 var stdout, stderr bytes.Buffer
115 cmd.Stdout = &stdout
116 cmd.Stderr = &stderr
117 if err := cmd.Run(); err != nil {
118 return fmt.Errorf("failed to run %v: %w; stdout=%#q, stderr=%#q", cmd.Args, err, stdout.String(), stderr.String())
119 }
120 if strings.TrimSpace(stdout.String()) != "yes" {
121 return fmt.Errorf("failed to run %v: expected `yes`, got %#q", cmd.Args, stdout.String())
122 }
123 return nil
124}
125
126func (s *ServiceWatcher) startAndStreamKubectl(cmd *exec.Cmd) error {
127 stdout, err := cmd.StdoutPipe()
128 if err != nil {
129 return err
130 }
131
132 var stderr bytes.Buffer
133 cmd.Stderr = &stderr
134
135 if err := cmd.Start(); err != nil {
136 return fmt.Errorf("failed to run %v: %w; stderr=%#q", cmd.Args, err, stderr.String())
137 }
138
139 readErr := s.readKubectlStream(stdout)
140 waitErr := cmd.Wait()
141 if waitErr != nil {
142 waitErr = fmt.Errorf("failed to run %v: %w; stderr=%#q", cmd.Args, waitErr, stderr.String())
143 }
144 return errors.Join(readErr, waitErr)
145}
146
147// readKubectlStream reads kubectl JSON watch events from r and updates the internal
148// services map. The stream is newline-delimited JSON objects representing "WatchEvent".
149func (s *ServiceWatcher) readKubectlStream(r io.Reader) error {
150 scanner := bufio.NewScanner(r)
151 // increase buffer in case of large JSON objects
152 const maxBuf = 10 * units.MiB
153 buf := make([]byte, 0, 64*units.KiB)
154 scanner.Buffer(buf, maxBuf)
155
156 for scanner.Scan() {
157 line := scanner.Bytes()
158 line = bytes.TrimSpace(line)
159 if len(line) == 0 {
160 continue
161 }
162
163 var ev struct {
164 Type eventType `json:"type"`
165 Object json.RawMessage `json:"object"`
166 }
167 if err := json.Unmarshal(line, &ev); err != nil {
168 return fmt.Errorf("failed to unmarshal line %#q: %w", string(line), err)
169 }
170
171 var svc service
172 if err := json.Unmarshal(ev.Object, &svc); err != nil {
173 return fmt.Errorf("failed to unmarshal service object: %w (line=%#q)", err, line)
174 }
175
176 key := svc.Metadata.Namespace + "/" + svc.Metadata.Name
177 s.rwMutex.Lock()
178 switch ev.Type {
179 case added, modified:
180 s.serviceSpecs[key] = &svc.Spec
181 case deleted:
182 delete(s.serviceSpecs, key)
183 default:
184 // NOP
185 }
186 s.rwMutex.Unlock()
187 }
188
189 if err := scanner.Err(); err != nil {
190 return fmt.Errorf("failed to scan kubectl event stream: %w", err)
191 }
192 return nil
193}
194
195func (s *ServiceWatcher) GetPorts() []Entry {
196 s.rwMutex.RLock()
197 defer s.rwMutex.RUnlock()
198
199 var entries []Entry
200 for key, spec := range s.serviceSpecs {
201 if spec.Type != serviceTypeNodePort &&
202 spec.Type != serviceTypeLoadBalancer {
203 continue
204 }
205
206 for _, portEntry := range spec.Ports {
207 switch portEntry.Protocol {
208 case protocolTCP, protocolUDP:
209 // NOP
210 default:
211 logrus.Debugf("unsupported protocol %s for service %#q, skipping",
212 portEntry.Protocol, key)
213 continue
214 }
215
216 var port int32
217 switch spec.Type {
218 case serviceTypeNodePort:
219 port = portEntry.NodePort
220 case serviceTypeLoadBalancer:
221 port = portEntry.Port
222 }
223
224 entries = append(entries, Entry{
225 Protocol: Protocol(strings.ToLower(string(portEntry.Protocol))),
226 IP: net.IPv4zero,
227 Port: uint16(port),
228 })
229 }
230 }
231
232 return entries
233}