@@ -5,15 +5,82 @@ package memory
55
66import (
77 "context"
8+ "fmt"
9+ "os/exec"
810 "path/filepath"
11+ "strconv"
12+ "strings"
913 "time"
1014
1115 hostagentclient "github.com/lima-vm/lima/v2/pkg/hostagent/api/client"
1216 "github.com/lima-vm/lima/v2/pkg/limatype"
1317 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
18+ "github.com/lima-vm/lima/v2/pkg/sshutil"
1419 "github.com/lima-vm/lima/v2/pkg/store"
1520)
1621
22+ func GetCurrent (ctx context.Context , inst * limatype.Instance ) (int64 , error ) {
23+ var memory int64
24+ hostAgentPID , err := store .ReadPIDFile (filepath .Join (inst .Dir , filenames .HostAgentPID ))
25+ if err != nil {
26+ return 0 , err
27+ }
28+ if hostAgentPID != 0 {
29+ haSock := filepath .Join (inst .Dir , filenames .HostAgentSock )
30+ haClient , err := hostagentclient .NewHostAgentClient (haSock )
31+ if err != nil {
32+ return 0 , err
33+ }
34+ ctx , cancel := context .WithTimeout (ctx , 3 * time .Second )
35+ defer cancel ()
36+ memory , err = haClient .GetCurrentMemory (ctx )
37+ if err != nil {
38+ return 0 , err
39+ }
40+ }
41+
42+ sshExe , err := sshutil .NewSSHExe ()
43+ if err != nil {
44+ return 0 , err
45+ }
46+ sshOpts , err := sshutil .CommonOpts (ctx , sshExe , false )
47+ if err != nil {
48+ return 0 , err
49+ }
50+ sshArgs := append (sshutil .SSHArgsFromOpts (sshOpts ),
51+ "-p" , fmt .Sprintf ("%d" , inst .SSHLocalPort ),
52+ fmt .Sprintf ("%s@%s" , * inst .Config .User .Name , inst .SSHAddress ),
53+ )
54+
55+ args := []string {"cat" , "/proc/meminfo" }
56+ sshCmd := exec .CommandContext (ctx , sshExe .Exe , append (sshArgs , args ... )... )
57+ out , err := sshCmd .Output ()
58+ if err != nil {
59+ return 0 , err
60+ }
61+
62+ var available int64
63+ for _ , line := range strings .Split (string (out ), "\n " ) {
64+ if ! strings .HasPrefix (line , "MemAvailable: " ) {
65+ continue
66+ }
67+ fields := strings .Fields (line )
68+ if len (fields ) < 3 {
69+ return 0 , fmt .Errorf ("unexpected line: %s" , line )
70+ }
71+ num , err := strconv .ParseInt (fields [1 ], 10 , 64 )
72+ if err != nil {
73+ return 0 , err
74+ }
75+ if fields [2 ] == "kB" {
76+ num *= 1024
77+ }
78+ available = num
79+ }
80+
81+ return memory - available , nil
82+ }
83+
1784func SetTarget (ctx context.Context , inst * limatype.Instance , memory int64 ) error {
1885 hostAgentPID , err := store .ReadPIDFile (filepath .Join (inst .Dir , filenames .HostAgentPID ))
1986 if err != nil {
0 commit comments