|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + "patchmon-agent/internal/client" |
| 11 | + |
| 12 | + "github.com/gorilla/websocket" |
| 13 | + "github.com/spf13/cobra" |
| 14 | +) |
| 15 | + |
| 16 | +// serveCmd runs the agent as a long-lived service |
| 17 | +var serveCmd = &cobra.Command{ |
| 18 | + Use: "serve", |
| 19 | + Short: "Run the agent as a service with async updates", |
| 20 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 21 | + if err := checkRoot(); err != nil { |
| 22 | + return err |
| 23 | + } |
| 24 | + return runService() |
| 25 | + }, |
| 26 | +} |
| 27 | + |
| 28 | +func init() { |
| 29 | + rootCmd.AddCommand(serveCmd) |
| 30 | +} |
| 31 | + |
| 32 | +func runService() error { |
| 33 | + if err := cfgManager.LoadCredentials(); err != nil { |
| 34 | + return err |
| 35 | + } |
| 36 | + |
| 37 | + httpClient := client.New(cfgManager, logger) |
| 38 | + ctx := context.Background() |
| 39 | + |
| 40 | + // obtain initial interval |
| 41 | + intervalMinutes := 60 |
| 42 | + if resp, err := httpClient.GetUpdateInterval(ctx); err == nil && resp.UpdateInterval > 0 { |
| 43 | + intervalMinutes = resp.UpdateInterval |
| 44 | + } |
| 45 | + |
| 46 | + ticker := time.NewTicker(time.Duration(intervalMinutes) * time.Minute) |
| 47 | + defer ticker.Stop() |
| 48 | + |
| 49 | + // initial report on boot |
| 50 | + if err := sendReport(); err != nil { |
| 51 | + logger.WithError(err).Warn("initial report failed") |
| 52 | + } |
| 53 | + |
| 54 | + // start websocket loop |
| 55 | + messages := make(chan wsMsg, 10) |
| 56 | + go wsLoop(messages) |
| 57 | + |
| 58 | + for { |
| 59 | + select { |
| 60 | + case <-ticker.C: |
| 61 | + if err := sendReport(); err != nil { |
| 62 | + logger.WithError(err).Warn("periodic report failed") |
| 63 | + } |
| 64 | + case m := <-messages: |
| 65 | + switch m.kind { |
| 66 | + case "settings_update": |
| 67 | + if m.interval > 0 { |
| 68 | + ticker.Stop() |
| 69 | + ticker = time.NewTicker(time.Duration(m.interval) * time.Minute) |
| 70 | + logger.WithField("new_interval", m.interval).Info("interval updated, no report sent") |
| 71 | + } |
| 72 | + case "report_now": |
| 73 | + if err := sendReport(); err != nil { |
| 74 | + logger.WithError(err).Warn("report_now failed") |
| 75 | + } |
| 76 | + case "update_agent": |
| 77 | + if err := updateAgent(); err != nil { |
| 78 | + logger.WithError(err).Warn("update_agent failed") |
| 79 | + } |
| 80 | + case "update_notification": |
| 81 | + logger.WithField("version", m.version).Info("Update notification received from server") |
| 82 | + if m.force { |
| 83 | + logger.Info("Force update requested, updating agent now") |
| 84 | + if err := updateAgent(); err != nil { |
| 85 | + logger.WithError(err).Warn("forced update failed") |
| 86 | + } |
| 87 | + } else { |
| 88 | + logger.Info("Update available, run 'patchmon-agent update-agent' to update") |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +type wsMsg struct { |
| 96 | + kind string |
| 97 | + interval int |
| 98 | + version string |
| 99 | + force bool |
| 100 | +} |
| 101 | + |
| 102 | +func wsLoop(out chan<- wsMsg) { |
| 103 | + backoff := time.Second |
| 104 | + for { |
| 105 | + if err := connectOnce(out); err != nil { |
| 106 | + logger.WithError(err).Warn("ws disconnected; retrying") |
| 107 | + } |
| 108 | + time.Sleep(backoff) |
| 109 | + if backoff < 30*time.Second { |
| 110 | + backoff *= 2 |
| 111 | + } |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +func connectOnce(out chan<- wsMsg) error { |
| 116 | + server := cfgManager.GetConfig().PatchmonServer |
| 117 | + if server == "" { |
| 118 | + return nil |
| 119 | + } |
| 120 | + apiID := cfgManager.GetCredentials().APIID |
| 121 | + apiKey := cfgManager.GetCredentials().APIKey |
| 122 | + |
| 123 | + // Convert http(s) -> ws(s) |
| 124 | + wsURL := server |
| 125 | + if strings.HasPrefix(wsURL, "https://") { |
| 126 | + wsURL = "wss://" + strings.TrimPrefix(wsURL, "https://") |
| 127 | + } else if strings.HasPrefix(wsURL, "http://") { |
| 128 | + wsURL = "ws://" + strings.TrimPrefix(wsURL, "http://") |
| 129 | + } |
| 130 | + if strings.HasSuffix(wsURL, "/") { |
| 131 | + wsURL = strings.TrimRight(wsURL, "/") |
| 132 | + } |
| 133 | + wsURL = wsURL + "/api/" + cfgManager.GetConfig().APIVersion + "/agents/ws" |
| 134 | + header := http.Header{} |
| 135 | + header.Set("X-API-ID", apiID) |
| 136 | + header.Set("X-API-KEY", apiKey) |
| 137 | + |
| 138 | + conn, _, err := websocket.DefaultDialer.Dial(wsURL, header) |
| 139 | + if err != nil { |
| 140 | + return err |
| 141 | + } |
| 142 | + defer func() { _ = conn.Close() }() |
| 143 | + |
| 144 | + // ping loop |
| 145 | + go func() { |
| 146 | + t := time.NewTicker(30 * time.Second) |
| 147 | + defer t.Stop() |
| 148 | + for range t.C { |
| 149 | + _ = conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second)) |
| 150 | + } |
| 151 | + }() |
| 152 | + |
| 153 | + // Set read deadlines and extend them on pong frames to avoid idle timeouts |
| 154 | + _ = conn.SetReadDeadline(time.Now().Add(90 * time.Second)) |
| 155 | + conn.SetPongHandler(func(string) error { |
| 156 | + return conn.SetReadDeadline(time.Now().Add(90 * time.Second)) |
| 157 | + }) |
| 158 | + |
| 159 | + logger.WithField("url", wsURL).Info("WebSocket connected") |
| 160 | + for { |
| 161 | + _, data, err := conn.ReadMessage() |
| 162 | + if err != nil { |
| 163 | + return err |
| 164 | + } |
| 165 | + var payload struct { |
| 166 | + Type string `json:"type"` |
| 167 | + UpdateInterval int `json:"update_interval"` |
| 168 | + Version string `json:"version"` |
| 169 | + Force bool `json:"force"` |
| 170 | + Message string `json:"message"` |
| 171 | + } |
| 172 | + if json.Unmarshal(data, &payload) == nil { |
| 173 | + switch payload.Type { |
| 174 | + case "settings_update": |
| 175 | + logger.WithField("interval", payload.UpdateInterval).Info("settings_update received") |
| 176 | + out <- wsMsg{kind: "settings_update", interval: payload.UpdateInterval} |
| 177 | + case "report_now": |
| 178 | + logger.Info("report_now received") |
| 179 | + out <- wsMsg{kind: "report_now"} |
| 180 | + case "update_agent": |
| 181 | + logger.Info("update_agent received") |
| 182 | + out <- wsMsg{kind: "update_agent"} |
| 183 | + case "update_notification": |
| 184 | + logger.WithFields(map[string]interface{}{ |
| 185 | + "version": payload.Version, |
| 186 | + "force": payload.Force, |
| 187 | + "message": payload.Message, |
| 188 | + }).Info("update_notification received") |
| 189 | + out <- wsMsg{ |
| 190 | + kind: "update_notification", |
| 191 | + version: payload.Version, |
| 192 | + force: payload.Force, |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | +} |
0 commit comments