跳到主要内容

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

浏览文件

krunkit_darwin_arm64.go

261 行 · 7.7 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package krunkit
5
6import (
7 "context"
8 "errors"
9 "fmt"
10 "net"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "strconv"
15
16 "github.com/docker/go-units"
17 "github.com/inetaf/tcpproxy"
18 "github.com/lima-vm/go-qcow2reader/image/raw"
19 "github.com/sirupsen/logrus"
20
21 "github.com/lima-vm/lima/v2/pkg/driver/vz"
22 "github.com/lima-vm/lima/v2/pkg/imgutil/proxyimgutil"
23 "github.com/lima-vm/lima/v2/pkg/limatype"
24 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
25 "github.com/lima-vm/lima/v2/pkg/limayaml"
26 "github.com/lima-vm/lima/v2/pkg/networks"
27 "github.com/lima-vm/lima/v2/pkg/networks/usernet"
28 "github.com/lima-vm/lima/v2/pkg/store"
29)
30
31const logLevelInfo = "3"
32
33// Cmdline constructs the command line arguments for krunkit based on the instance configuration.
34func Cmdline(inst *limatype.Instance) (*exec.Cmd, error) {
35 memBytes, err := units.RAMInBytes(*inst.Config.Memory)
36 if err != nil {
37 return nil, err
38 }
39
40 args := []string{
41 // Memory in MiB
42 "--memory", strconv.FormatInt(memBytes/units.MiB, 10),
43 "--cpus", fmt.Sprintf("%d", *inst.Config.CPUs),
44 "--device", fmt.Sprintf("virtio-serial,logFilePath=%s", filepath.Join(inst.Dir, filenames.SerialLog)),
45 "--krun-log-level", logLevelInfo,
46 "--restful-uri", "none://",
47
48 // First virtio-blk device is the boot disk
49 "--device", fmt.Sprintf("virtio-blk,path=%s,format=raw", filepath.Join(inst.Dir, filenames.Disk)),
50 "--device", fmt.Sprintf("virtio-blk,path=%s", filepath.Join(inst.Dir, filenames.CIDataISO)),
51 "--device", fmt.Sprintf("virtio-vsock,port=%d,socketURL=%s,connect", vSockPort, filepath.Join(inst.Dir, filenames.GuestAgentSock)),
52 }
53
54 if inst.Config.SSH.OverVsock != nil && *inst.Config.SSH.OverVsock {
55 sshVsockPath := filepath.Join(inst.Dir, sshVsockSock)
56 args = append(args, "--device", fmt.Sprintf("virtio-vsock,port=22,socketURL=%s,connect", sshVsockPath))
57 }
58
59 // Add additional disks
60 if len(inst.Config.AdditionalDisks) > 0 {
61 ctx := context.Background()
62 diskUtil := proxyimgutil.NewDiskUtil(ctx)
63 for _, d := range inst.Config.AdditionalDisks {
64 disk, derr := store.InspectDisk(d.Name, d.FSType)
65 if derr != nil {
66 return nil, fmt.Errorf("failed to load disk %#q: %w", d.Name, derr)
67 }
68 if disk.Instance != "" {
69 return nil, fmt.Errorf("failed to run attach disk %#q, in use by instance %#q", disk.Name, disk.Instance)
70 }
71 if lerr := disk.Lock(inst.Dir); lerr != nil {
72 return nil, fmt.Errorf("failed to lock disk %#q: %w", d.Name, lerr)
73 }
74 extraDiskPath := filepath.Join(disk.Dir, filenames.DataDisk)
75 logrus.Infof("Mounting disk %#q on %#q", disk.Name, disk.MountPoint)
76 if cerr := diskUtil.Convert(ctx, raw.Type, extraDiskPath, extraDiskPath, nil, true); cerr != nil {
77 return nil, fmt.Errorf("failed to convert extra disk %#q to raw: %w", extraDiskPath, cerr)
78 }
79 args = append(args, "--device", fmt.Sprintf("virtio-blk,path=%s,format=raw", extraDiskPath))
80 }
81 }
82
83 // Network commands
84 networkArgs, err := buildNetworkArgs(inst)
85 if err != nil {
86 return nil, fmt.Errorf("failed to build network arguments: %w", err)
87 }
88
89 // File sharing commands
90 if *inst.Config.MountType == limatype.VIRTIOFS {
91 for _, mount := range inst.Config.Mounts {
92 if _, err := os.Stat(mount.Location); errors.Is(err, os.ErrNotExist) {
93 if err := os.MkdirAll(mount.Location, 0o750); err != nil {
94 return nil, err
95 }
96 }
97 tag := limayaml.MountTag(mount.Location, *mount.MountPoint)
98 mountArg := fmt.Sprintf("virtio-fs,sharedDir=%s,mountTag=%s", mount.Location, tag)
99 args = append(args, "--device", mountArg)
100 }
101 }
102
103 args = append(args, networkArgs...)
104
105 if inst.Config.NestedVirtualization != nil && *inst.Config.NestedVirtualization {
106 args = append(args, "--nested")
107 }
108
109 cmd := exec.CommandContext(context.Background(), vmType, args...)
110
111 return cmd, nil
112}
113
114func buildNetworkArgs(inst *limatype.Instance) ([]string, error) {
115 var args []string
116
117 // Configure default usernetwork with limayaml.MACAddress(inst.Dir) for eth0 interface
118 firstUsernetIndex := limayaml.FirstUsernetIndex(inst.Config)
119 if firstUsernetIndex == -1 {
120 // slirp network using gvisor netstack
121 krunkitSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.FDSock)
122 if err != nil {
123 return nil, err
124 }
125 client, err := vz.PassFDToUnix(krunkitSock)
126 if err != nil {
127 return nil, err
128 }
129
130 args = append(args, "--device", fmt.Sprintf("virtio-net,type=unixgram,fd=%d,mac=%s", client.Fd(), limayaml.MACAddress(inst.Dir)))
131 }
132
133 for _, nw := range inst.Networks {
134 var sock string
135 var mac string
136 if nw.Lima != "" {
137 nwCfg, err := networks.LoadConfig()
138 if err != nil {
139 return nil, err
140 }
141 switch nw.Lima {
142 case networks.ModeUserV2:
143 sock, err = usernet.Sock(nw.Lima, usernet.QEMUSock)
144 if err != nil {
145 return nil, err
146 }
147 mac = limayaml.MACAddress(inst.Dir)
148 case networks.ModeShared, networks.ModeBridged:
149 socketVMNetInstalled, err := nwCfg.IsDaemonInstalled(networks.SocketVMNet)
150 if err != nil {
151 return nil, err
152 }
153 if !socketVMNetInstalled {
154 return nil, errors.New("socket_vmnet is not installed")
155 }
156 sock, err = networks.Sock(nw.Lima)
157 if err != nil {
158 return nil, err
159 }
160 mac = nw.MACAddress
161 default:
162 return nil, fmt.Errorf("invalid network spec %+v", nw)
163 }
164 } else if nw.Socket != "" {
165 sock = nw.Socket
166 mac = nw.MACAddress
167 } else {
168 return nil, fmt.Errorf("invalid network spec %+v", nw)
169 }
170
171 device := fmt.Sprintf("virtio-net,type=unixstream,path=%s,mac=%s", sock, mac)
172 args = append(args, "--device", device)
173 }
174
175 if len(args) == 0 {
176 return args, errors.New("no socket_vmnet networks defined")
177 }
178
179 return args, nil
180}
181
182func startUsernet(ctx context.Context, inst *limatype.Instance) (*usernet.Client, context.CancelFunc, error) {
183 if firstUsernetIndex := limayaml.FirstUsernetIndex(inst.Config); firstUsernetIndex != -1 {
184 return usernet.NewClientByName(inst.Config.Networks[firstUsernetIndex].Lima), nil, nil
185 }
186 // Start a in-process gvisor-tap-vsock
187 endpointSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock)
188 if err != nil {
189 return nil, nil, err
190 }
191 krunkitSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.FDSock)
192 if err != nil {
193 return nil, nil, err
194 }
195 os.RemoveAll(endpointSock)
196 os.RemoveAll(krunkitSock)
197 ctx, cancel := context.WithCancel(ctx)
198 err = usernet.StartGVisorNetstack(ctx, &usernet.GVisorNetstackOpts{
199 MTU: 1500,
200 Endpoint: endpointSock,
201 FdSocket: krunkitSock,
202 Async: true,
203 DefaultLeases: map[string]string{
204 networks.SlirpIPAddress: limayaml.MACAddress(inst.Dir),
205 },
206 Subnet: networks.SlirpNetwork,
207 })
208 if err != nil {
209 defer cancel()
210 return nil, nil, err
211 }
212 subnetIP, _, err := net.ParseCIDR(networks.SlirpNetwork)
213 return usernet.NewClient(endpointSock, subnetIP), cancel, err
214}
215
216func startVsockForwarder(ctx context.Context, unixSockPath, hostAddress string) error {
217 // Test if the vsock port is open
218 var d net.Dialer
219 conn, err := d.DialContext(ctx, "unix", unixSockPath)
220 if err != nil {
221 return err
222 }
223 conn.Close()
224
225 var lc net.ListenConfig
226 l, err := lc.Listen(ctx, "tcp", hostAddress)
227 if err != nil {
228 return err
229 }
230 go func() {
231 <-ctx.Done()
232 l.Close()
233 }()
234 logrus.Infof("Started krunkit vsock forwarder: %s -> %s", hostAddress, unixSockPath)
235 go func() {
236 defer l.Close()
237 for {
238 conn, err := l.Accept()
239 if err != nil {
240 if errors.Is(err, net.ErrClosed) {
241 return
242 }
243 logrus.WithError(err).Errorf("krunkit vsock forwarder accept error: %v", err)
244 } else {
245 p := tcpproxy.DialProxy{
246 DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
247 return d.DialContext(ctx, "unix", unixSockPath)
248 },
249 }
250 go p.HandleConn(conn)
251 }
252 select {
253 case <-ctx.Done():
254 return
255 default:
256 continue
257 }
258 }
259 }()
260 return nil
261}