instances.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // instances.go - configuración multi-instancia de Proxmox VE (#764).
  2. //
  3. // Sustituye a la config plana single-endpoint (proxmox_url/token_id/
  4. // token_secret) manteniéndola como origen de migración: la primera lectura
  5. // con kv legacy la convierte en una lista de una instancia. La lista vive en
  6. // la clave "proxmox_instances" como JSON; los secretos NUNCA salen del
  7. // server (la API expone tokenSet).
  8. package pve
  9. import (
  10. "database/sql"
  11. "encoding/json"
  12. "fmt"
  13. "log"
  14. "regexp"
  15. "strings"
  16. )
  17. // Instance es un endpoint Proxmox configurado (cluster o nodo suelto).
  18. // Un endpoint de cluster ya devuelve todos sus nodos vía /cluster/resources.
  19. type Instance struct {
  20. // ID: slug estable para la API ("casa", "ofi").
  21. ID string `json:"id"`
  22. // Name: nombre visible para la UI.
  23. Name string `json:"name"`
  24. Config
  25. }
  26. const kvInstances = "proxmox_instances"
  27. // instanceIDRe: slug simple para identificar instancias en URLs.
  28. var instanceIDRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)
  29. // ValidInstanceID informa de si el id es un slug válido.
  30. func ValidInstanceID(id string) bool {
  31. return instanceIDRe.MatchString(id)
  32. }
  33. // LoadInstances devuelve las instancias configuradas. Si no existe la lista
  34. // pero sí la config legacy (proxmox_url), migra automáticamente: escribe la
  35. // lista y limpia las claves viejas (id "default", nombre "Proxmox").
  36. func LoadInstances(db *sql.DB) []Instance {
  37. if db == nil {
  38. return nil
  39. }
  40. var raw string
  41. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", kvInstances).Scan(&raw); err == nil && strings.TrimSpace(raw) != "" {
  42. var list []Instance
  43. if err := json.Unmarshal([]byte(raw), &list); err != nil {
  44. log.Printf("[netpulse:pve] corrupt instances, regenerating: %v", err)
  45. } else {
  46. return list
  47. }
  48. }
  49. // Migración legacy single-endpoint (#561) → lista de una instancia.
  50. var url, tokenID, secret string
  51. _ = db.QueryRow("SELECT value FROM kv WHERE key='proxmox_url'").Scan(&url)
  52. _ = db.QueryRow("SELECT value FROM kv WHERE key='proxmox_token_id'").Scan(&tokenID)
  53. _ = db.QueryRow("SELECT value FROM kv WHERE key='proxmox_token_secret'").Scan(&secret)
  54. if url == "" || tokenID == "" || secret == "" {
  55. return nil
  56. }
  57. list := []Instance{{ID: "default", Name: "Proxmox", Config: Config{URL: url, TokenID: tokenID, Secret: secret}}}
  58. if err := SaveInstances(db, list); err != nil {
  59. log.Printf("[netpulse:pve] legacy migration: %v", err)
  60. return list // devolverla igual: funciona aunque no persista
  61. }
  62. for _, k := range []string{"proxmox_url", "proxmox_token_id", "proxmox_token_secret"} {
  63. _, _ = db.Exec("DELETE FROM kv WHERE key = ?", k)
  64. }
  65. return list
  66. }
  67. // SaveInstances persiste la lista completa (UPSERT).
  68. func SaveInstances(db *sql.DB, list []Instance) error {
  69. if db == nil {
  70. return fmt.Errorf("pve: no database")
  71. }
  72. raw, err := json.Marshal(list)
  73. if err != nil {
  74. return err
  75. }
  76. _, err = db.Exec(
  77. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  78. kvInstances, string(raw))
  79. return err
  80. }
  81. // UpsertInstance añade o actualiza una instancia por ID. Secret vacío =
  82. // conservar el existente (la UI no reenvía secretos). ID no editable.
  83. func UpsertInstance(db *sql.DB, in Instance) error {
  84. if !ValidInstanceID(in.ID) {
  85. return fmt.Errorf("invalid id (lowercase slug, hyphens, max 32)")
  86. }
  87. if in.URL == "" || in.TokenID == "" {
  88. return fmt.Errorf("url y tokenId son requeridos")
  89. }
  90. list := LoadInstances(db)
  91. for i := range list {
  92. if list[i].ID == in.ID {
  93. if in.Secret == "" {
  94. in.Secret = list[i].Secret
  95. }
  96. list[i] = in
  97. return SaveInstances(db, list)
  98. }
  99. }
  100. if in.Secret == "" {
  101. return fmt.Errorf("secret required for a new instance")
  102. }
  103. return SaveInstances(db, append(list, in))
  104. }
  105. // DeleteInstance elimina una instancia por ID (no-op si no existe).
  106. func DeleteInstance(db *sql.DB, id string) error {
  107. list := LoadInstances(db)
  108. out := list[:0]
  109. for _, in := range list {
  110. if in.ID != id {
  111. out = append(out, in)
  112. }
  113. }
  114. return SaveInstances(db, out)
  115. }