| 1 | package limaembed |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net" |
| 9 | "os" |
| 10 | "sync" |
| 11 | |
| 12 | "github.com/lima-vm/lima/v2/pkg/hostagent/events" |
| 13 | |
| 14 | "github.com/sylvinus/agent-vm/internal/desktop" |
| 15 | ) |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | type eventWatch struct { |
| 22 | w io.Writer |
| 23 | vm string |
| 24 | notify func(title, msg string) |
| 25 | |
| 26 | mu sync.Mutex |
| 27 | partial []byte |
| 28 | } |
| 29 | |
| 30 | func newEventWatch(w io.Writer, vm string) *eventWatch { |
| 31 | n := desktop.Notify |
| 32 | if os.Getenv("AGENT_VM_NOTIFY") == "0" { |
| 33 | n = func(string, string) {} |
| 34 | } |
| 35 | return &eventWatch{w: w, vm: vm, notify: n} |
| 36 | } |
| 37 | |
| 38 | func (e *eventWatch) Write(p []byte) (int, error) { |
| 39 | e.mu.Lock() |
| 40 | e.partial = append(e.partial, p...) |
| 41 | for { |
| 42 | i := bytes.IndexByte(e.partial, '\n') |
| 43 | if i < 0 { |
| 44 | break |
| 45 | } |
| 46 | e.event(e.partial[:i]) |
| 47 | e.partial = e.partial[i+1:] |
| 48 | } |
| 49 | e.mu.Unlock() |
| 50 | return e.w.Write(p) |
| 51 | } |
| 52 | |
| 53 | |
| 54 | |
| 55 | func (e *eventWatch) Sync() error { |
| 56 | if s, ok := e.w.(syncer); ok { |
| 57 | return s.Sync() |
| 58 | } |
| 59 | return nil |
| 60 | } |
| 61 | |
| 62 | func (e *eventWatch) event(line []byte) { |
| 63 | var ev events.Event |
| 64 | if json.Unmarshal(line, &ev) != nil || ev.Status.PortForward == nil { |
| 65 | return |
| 66 | } |
| 67 | pf := ev.Status.PortForward |
| 68 | |
| 69 | if _, _, err := net.SplitHostPort(pf.HostAddr); err != nil { |
| 70 | return |
| 71 | } |
| 72 | switch pf.Type { |
| 73 | case events.PortForwardEventForwarding: |
| 74 | e.notify("agent-vm: "+e.vm, fmt.Sprintf("The VM now serves %s on this machine.", pf.HostAddr)) |
| 75 | case events.PortForwardEventFailed: |
| 76 | e.notify("agent-vm: "+e.vm, fmt.Sprintf("Not forwarded: %s is in use on this machine.", pf.HostAddr)) |
| 77 | } |
| 78 | } |