catalog.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // catalog.go - vendor catalog discovery (#1697). The list of supported
  2. // integrations is no longer compiled into the binary: it is fetched from
  3. // vendors.json in gnacho/netpulse-integrations (the same repository that
  4. // publishes the releases), cached in the kv table with a TTL, and served with
  5. // an embedded seed so a fresh offline install still has something to show.
  6. // A failed fetch or a malformed catalog never empties the vendor list: the
  7. // previous cache (or the seed) keeps being served.
  8. package rintegration
  9. import (
  10. "context"
  11. "database/sql"
  12. _ "embed"
  13. "encoding/json"
  14. "fmt"
  15. "io"
  16. "log"
  17. "net/http"
  18. "regexp"
  19. "sync"
  20. "time"
  21. )
  22. const (
  23. // CatalogRepo is the GitHub repository that publishes the vendor catalog
  24. // and every integration release.
  25. CatalogRepo = "gnacho/netpulse-integrations"
  26. // rawCatalogURL is the raw URL of the catalog on the main branch.
  27. rawCatalogURL = "https://raw.githubusercontent.com/" + CatalogRepo + "/main/vendors.json"
  28. // catalogTTL is how long a fetched catalog is considered fresh. The
  29. // issue leaves the value open; 24h keeps GitHub raw traffic negligible
  30. // while new vendors still show up the same day they are published.
  31. catalogTTL = 24 * time.Hour
  32. // catalogFetchTimeout bounds every catalog fetch attempt.
  33. catalogFetchTimeout = 10 * time.Second
  34. // catalogRetryCooldown is the minimum wait between fetch attempts after
  35. // a failure, so an offline instance does not hammer GitHub raw on every
  36. // page view.
  37. catalogRetryCooldown = 10 * time.Minute
  38. // catalogMaxBytes caps the catalog body (it is a small JSON file).
  39. catalogMaxBytes = 1 << 20
  40. // kvCatalogKey persists the last fetched catalog plus its timestamp.
  41. kvCatalogKey = "integrations.vendor_catalog"
  42. )
  43. //go:embed vendors_seed.json
  44. var seedJSON []byte
  45. // seedCatalog is the embedded copy of the current vendors.json, generated
  46. // from netpulse-integrations main. Regenerate it from that file when the
  47. // upstream catalog gains the first vendor that must work out of the box.
  48. var seedCatalog = parseSeed()
  49. func parseSeed() []Vendor {
  50. var f catalogFile
  51. if err := json.Unmarshal(seedJSON, &f); err != nil {
  52. log.Printf("[netpulse] warning: could not parse vendor catalog seed: %v", err)
  53. return nil
  54. }
  55. return validVendors(f.Vendors)
  56. }
  57. // catalogEntry mirrors the vendors.json schema (netpulse-integrations PR #24):
  58. // id, mode, arches, tagPrefix, binary, target, description.
  59. type catalogEntry struct {
  60. ID string `json:"id"`
  61. Mode string `json:"mode"`
  62. Arches []string `json:"arches"`
  63. TagPrefix string `json:"tagPrefix"`
  64. Binary string `json:"binary"`
  65. Target string `json:"target"`
  66. Description string `json:"description"`
  67. }
  68. type catalogFile struct {
  69. Vendors []catalogEntry `json:"vendors"`
  70. }
  71. // assetPrefixes holds execution knowledge the catalog schema does not carry:
  72. // vendor ids whose release asset name prefix differs from the vendor id. The
  73. // integrations release workflow names assets "<name>_<version>_linux_<arch>.
  74. // tar.gz"; bbox ships the shared integrations-supervisor binary instead of a
  75. // per-vendor one. A vendor following the default convention needs no entry.
  76. var assetPrefixes = map[string]string{
  77. "bbox": "integrations-supervisor",
  78. }
  79. // initSystems holds the on-router layout of ssh vendors (how to install, not
  80. // who exists). Empty means procd (OpenWrt); asuswrt ships a Merlin layout
  81. // (#1681).
  82. var initSystems = map[string]string{
  83. "asuswrt": "merlin",
  84. }
  85. var catalogIDRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
  86. // validVendors validates catalog entries and converts them to Vendors.
  87. // Invalid entries are dropped individually (a bad vendor must never break the
  88. // rest of the catalog); an empty result means the whole catalog is unusable.
  89. func validVendors(entries []catalogEntry) []Vendor {
  90. seen := map[string]bool{}
  91. out := make([]Vendor, 0, len(entries))
  92. for _, e := range entries {
  93. v, ok := vendorFromEntry(e, seen)
  94. if !ok {
  95. log.Printf("[netpulse] warning: vendor catalog entry discarded as invalid: id=%q mode=%q", e.ID, e.Mode)
  96. continue
  97. }
  98. out = append(out, v)
  99. }
  100. return out
  101. }
  102. func vendorFromEntry(e catalogEntry, seen map[string]bool) (Vendor, bool) {
  103. if !catalogIDRe.MatchString(e.ID) || seen[e.ID] {
  104. return Vendor{}, false
  105. }
  106. if e.Mode != "local" && e.Mode != "ssh" {
  107. return Vendor{}, false
  108. }
  109. if e.TagPrefix == "" || e.Binary == "" || len(e.Arches) == 0 {
  110. return Vendor{}, false
  111. }
  112. for _, a := range e.Arches {
  113. if a == "" {
  114. return Vendor{}, false
  115. }
  116. }
  117. seen[e.ID] = true
  118. prefix := e.ID
  119. if p := assetPrefixes[e.ID]; p != "" {
  120. prefix = p
  121. }
  122. return Vendor{
  123. ID: e.ID,
  124. Mode: e.Mode,
  125. Repo: CatalogRepo,
  126. TagPrefix: e.TagPrefix,
  127. AssetTmpl: prefix + "_{version}_linux_{arch}.tar.gz",
  128. Arches: append([]string(nil), e.Arches...),
  129. Binary: e.Binary,
  130. Init: initSystems[e.ID],
  131. Description: e.Description,
  132. }, true
  133. }
  134. // kvCatalog is the persisted form of the last fetched catalog: the raw body
  135. // (so future schema evolution re-validates from the source format) plus the
  136. // timestamp of the successful fetch.
  137. type kvCatalog struct {
  138. FetchedAtMs int64 `json:"fetchedAtMs"`
  139. Body string `json:"body"`
  140. }
  141. // Catalog discovers and serves the vendor catalog. The zero-value knobs
  142. // (Client, RawURL, Now, FetchOverride) mirror the Fetcher style: unset fields
  143. // get production defaults; tests set them to stay offline. A Catalog built
  144. // without a db (demo, nil fallback in tests) never fetches: it serves the
  145. // embedded seed only.
  146. type Catalog struct {
  147. Client *http.Client // default: 10s timeout
  148. RawURL string // default: rawCatalogURL
  149. Now func() time.Time
  150. FetchOverride func(url string) ([]byte, error) // test injection; nil = real fetch
  151. db *sql.DB
  152. mu sync.Mutex
  153. loaded bool
  154. vendors []Vendor
  155. fetchedAt time.Time // zero = never fetched from the network
  156. retryAfter time.Time // cooldown after a failed fetch
  157. lastErr string
  158. }
  159. // NewCatalog builds a catalog. A nil db keeps it in memory (seed only, no
  160. // network); a real db enables the kv cache and the TTL auto-fetch.
  161. func NewCatalog(db *sql.DB) *Catalog {
  162. return &Catalog{db: db}
  163. }
  164. func (c *Catalog) client() *http.Client {
  165. if c.Client != nil {
  166. return c.Client
  167. }
  168. return &http.Client{Timeout: catalogFetchTimeout}
  169. }
  170. func (c *Catalog) url() string {
  171. if c.RawURL != "" {
  172. return c.RawURL
  173. }
  174. return rawCatalogURL
  175. }
  176. func (c *Catalog) now() time.Time {
  177. if c.Now != nil {
  178. return c.Now()
  179. }
  180. return time.Now()
  181. }
  182. // Current returns the last known catalog (cache or seed) without any network
  183. // access. Use it when freshness is not worth a fetch.
  184. func (c *Catalog) Current() []Vendor {
  185. c.mu.Lock()
  186. defer c.mu.Unlock()
  187. c.ensureLoadedLocked()
  188. return append([]Vendor(nil), c.vendors...)
  189. }
  190. // Lookup resolves one vendor from the last known catalog (cache or seed),
  191. // with no network access, so create/edit/start/stop/update/check keep working
  192. // offline exactly as they did against the compiled manifest.
  193. func (c *Catalog) Lookup(id string) (Vendor, bool) {
  194. for _, v := range c.Current() {
  195. if v.ID == id {
  196. return v, true
  197. }
  198. }
  199. return Vendor{}, false
  200. }
  201. // LastRefreshedAt reports the last successful fetch from the network (zero
  202. // when only the seed has ever been served).
  203. func (c *Catalog) LastRefreshedAt() time.Time {
  204. c.mu.Lock()
  205. defer c.mu.Unlock()
  206. c.ensureLoadedLocked()
  207. return c.fetchedAt
  208. }
  209. // LastRefreshedAtMs is LastRefreshedAt as unix milliseconds, 0 when the seed
  210. // has never been replaced by a successful fetch. It is the shape the API and
  211. // the UI use for timestamps.
  212. func (c *Catalog) LastRefreshedAtMs() int64 {
  213. t := c.LastRefreshedAt()
  214. if t.IsZero() {
  215. return 0
  216. }
  217. return t.UnixMilli()
  218. }
  219. // LastError reports the last fetch or validation error, for diagnostics.
  220. func (c *Catalog) LastError() string {
  221. c.mu.Lock()
  222. defer c.mu.Unlock()
  223. return c.lastErr
  224. }
  225. // Vendors serves the current catalog, refreshing it first when the TTL has
  226. // expired (or nothing was ever fetched). The fetch is best effort: on failure
  227. // the previously known catalog (or the seed) is served, never an empty list.
  228. func (c *Catalog) Vendors(ctx context.Context) []Vendor {
  229. c.mu.Lock()
  230. c.ensureLoadedLocked()
  231. stale := c.db != nil && (c.fetchedAt.IsZero() || c.now().Sub(c.fetchedAt) >= catalogTTL)
  232. cooldown := c.now().Before(c.retryAfter)
  233. c.mu.Unlock()
  234. if stale && !cooldown {
  235. // Best effort: Refresh keeps the old catalog on failure.
  236. _ = c.Refresh(ctx)
  237. }
  238. return c.Current()
  239. }
  240. // Refresh forces a fetch from the network regardless of the TTL, validates
  241. // the catalog and persists it. On failure the previous catalog stays in
  242. // place, a cooldown is stamped and the error is returned.
  243. func (c *Catalog) Refresh(ctx context.Context) error {
  244. body, err := c.fetchRaw(ctx)
  245. if err == nil {
  246. var f catalogFile
  247. if err = json.Unmarshal(body, &f); err == nil {
  248. vs := validVendors(f.Vendors)
  249. if len(vs) == 0 {
  250. err = fmt.Errorf("vendor catalog: no valid entries")
  251. } else {
  252. now := c.now()
  253. c.mu.Lock()
  254. c.vendors = vs
  255. c.fetchedAt = now
  256. c.lastErr = ""
  257. c.mu.Unlock()
  258. c.persist(now, body)
  259. return nil
  260. }
  261. }
  262. }
  263. c.mu.Lock()
  264. c.retryAfter = c.now().Add(catalogRetryCooldown)
  265. c.lastErr = err.Error()
  266. c.mu.Unlock()
  267. log.Printf("[netpulse] warning: could not refresh vendor catalog (%v), serving the last known one", err)
  268. return err
  269. }
  270. func (c *Catalog) fetchRaw(ctx context.Context) ([]byte, error) {
  271. if c.FetchOverride != nil {
  272. return c.FetchOverride(c.url())
  273. }
  274. req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url(), nil)
  275. if err != nil {
  276. return nil, err
  277. }
  278. req.Header.Set("User-Agent", userAgent)
  279. resp, err := c.client().Do(req)
  280. if err != nil {
  281. return nil, err
  282. }
  283. defer resp.Body.Close()
  284. if resp.StatusCode != http.StatusOK {
  285. return nil, fmt.Errorf("vendor catalog: %s", resp.Status)
  286. }
  287. body, err := io.ReadAll(io.LimitReader(resp.Body, catalogMaxBytes))
  288. if err != nil {
  289. return nil, err
  290. }
  291. return body, nil
  292. }
  293. // persist stores the raw catalog and its timestamp in kv. Failures are logged
  294. // and swallowed: the in-memory catalog already serves this process, and the
  295. // next successful fetch will persist again.
  296. func (c *Catalog) persist(fetchedAt time.Time, body []byte) {
  297. if c.db == nil {
  298. return
  299. }
  300. raw, err := json.Marshal(kvCatalog{FetchedAtMs: fetchedAt.UnixMilli(), Body: string(body)})
  301. if err != nil {
  302. log.Printf("[netpulse] warning: could not serialize vendor catalog: %v", err)
  303. return
  304. }
  305. if err := kvSet(c.db, kvCatalogKey, string(raw)); err != nil {
  306. log.Printf("[netpulse] warning: could not persist vendor catalog: %v", err)
  307. }
  308. }
  309. // ensureLoadedLocked loads the kv cache on first use, falling back to the
  310. // embedded seed. Any corrupt or empty cache silently degrades to the seed.
  311. func (c *Catalog) ensureLoadedLocked() {
  312. if c.loaded {
  313. return
  314. }
  315. c.loaded = true
  316. c.vendors = seedCatalog
  317. if c.db == nil {
  318. return
  319. }
  320. raw, ok := kvGet(c.db, kvCatalogKey)
  321. if !ok {
  322. return
  323. }
  324. var w kvCatalog
  325. if err := json.Unmarshal([]byte(raw), &w); err != nil || w.Body == "" {
  326. log.Printf("[netpulse] warning: vendor catalog cache corrupt, using seed")
  327. return
  328. }
  329. var f catalogFile
  330. if err := json.Unmarshal([]byte(w.Body), &f); err != nil {
  331. log.Printf("[netpulse] warning: could not parse vendor catalog cache, using seed")
  332. return
  333. }
  334. vs := validVendors(f.Vendors)
  335. if len(vs) == 0 {
  336. return
  337. }
  338. c.vendors = vs
  339. if w.FetchedAtMs > 0 {
  340. c.fetchedAt = time.UnixMilli(w.FetchedAtMs)
  341. }
  342. }
  343. func kvGet(d *sql.DB, key string) (string, bool) {
  344. var val string
  345. err := d.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&val)
  346. if err != nil {
  347. return "", false
  348. }
  349. return val, true
  350. }
  351. func kvSet(d *sql.DB, key, val string) error {
  352. _, err := d.Exec("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", key, val)
  353. return err
  354. }