orchestr.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // Package orchestr — motor de plan/apply para Fase 10 (escritura/orquestación).
  2. // Genera planes (diff desired vs current → Ops), los persiste en SQLite,
  3. // los envía al agente vía SSE y registra el resultado en auditoría.
  4. package orchestr
  5. import (
  6. "crypto/rand"
  7. "database/sql"
  8. "encoding/hex"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "time"
  13. "github.com/gnacho/netpulse/agent/executor"
  14. "github.com/gnacho/netpulse/server-go/internal/db"
  15. )
  16. // Errores del ciclo de vida del plan.
  17. var (
  18. // ErrPlanNotFound: no hay ningún plan con ese id (p. ej. el agente
  19. // reporta un plan de una base de datos que se recreó).
  20. ErrPlanNotFound = errors.New("plan_not_found")
  21. // ErrInvalidTransition: el plan no está en el estado del que parte la
  22. // transición pedida. No se hacen UPDATE a ciegas.
  23. ErrInvalidTransition = errors.New("invalid_plan_transition")
  24. )
  25. // Plan es un plan de orquestación: desired state → diff (Ops) → apply.
  26. type Plan struct {
  27. ID string `json:"id"`
  28. RouterID string `json:"routerId"`
  29. Resource string `json:"resource"`
  30. Desired json.RawMessage `json:"desired"`
  31. Diff []executor.Op `json:"diff"`
  32. Status string `json:"status"` // pending|applying|applied|failed|rolled_back
  33. CreatedBy string `json:"createdBy"`
  34. CreatedAt int64 `json:"createdAt"`
  35. AppliedAt *int64 `json:"appliedAt,omitempty"`
  36. Result *ApplyResult `json:"result,omitempty"`
  37. // Method NO se persiste: es metadato de la respuesta del POST /api/plans
  38. // que indica el escenario detectado (apk|opkg|none|binary) para que el
  39. // frontend lo muestre. Vacío en GET /api/plans/{id}.
  40. Method string `json:"method,omitempty"`
  41. }
  42. // ApplyResult es lo que el agente reporta tras ejecutar el plan.
  43. type ApplyResult = executor.ApplyResult
  44. // Manager gestiona el ciclo de vida de los planes.
  45. type Manager struct {
  46. db *db.DB
  47. }
  48. // New crea el manager.
  49. func New(d *db.DB) *Manager {
  50. return &Manager{db: d}
  51. }
  52. // CreatePlan genera y persiste un plan a partir del estado deseado.
  53. // diffFn es la función específica del módulo (AdGuard, WireGuard, ...)
  54. // que compara desired vs current y devuelve la lista de Ops.
  55. func (m *Manager) CreatePlan(routerID, resource string, desired json.RawMessage, diff []executor.Op, createdBy string) (*Plan, error) {
  56. id := newID()
  57. diffJSON, _ := json.Marshal(diff)
  58. now := time.Now().Unix()
  59. if _, err := m.db.Exec(
  60. `INSERT INTO orchestr_plans (id, router_id, resource, desired, diff, status, created_by, created_at)
  61. VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)`,
  62. id, routerID, resource, string(desired), string(diffJSON), createdBy, now); err != nil {
  63. return nil, fmt.Errorf("insert plan: %w", err)
  64. }
  65. m.audit(id, "plan", createdBy, fmt.Sprintf("resource=%s ops=%d", resource, len(diff)))
  66. return m.GetPlan(id)
  67. }
  68. // GetPlan carga un plan por ID.
  69. func (m *Manager) GetPlan(id string) (*Plan, error) {
  70. var p Plan
  71. var desired, diffJSON, status string
  72. var createdBy string
  73. var createdAt int64
  74. var appliedAt *int64
  75. var resultJSON *string
  76. err := m.db.QueryRow(
  77. `SELECT id, router_id, resource, desired, diff, status, created_by, created_at, applied_at, result
  78. FROM orchestr_plans WHERE id = ?`, id).Scan(
  79. &p.ID, &p.RouterID, &p.Resource, &desired, &diffJSON, &status,
  80. &createdBy, &createdAt, &appliedAt, &resultJSON)
  81. if err != nil {
  82. return nil, err
  83. }
  84. // desired vacío en BD → nil (json.RawMessage("") revienta al serializar
  85. // con toolchains recientes: MarshalJSON de un documento vacío es error y
  86. // el POST /api/plans respondía 201 sin body).
  87. if desired != "" {
  88. p.Desired = json.RawMessage(desired)
  89. }
  90. json.Unmarshal([]byte(diffJSON), &p.Diff)
  91. p.Status = status
  92. p.CreatedBy = createdBy
  93. p.CreatedAt = createdAt
  94. p.AppliedAt = appliedAt
  95. if resultJSON != nil {
  96. var r ApplyResult
  97. json.Unmarshal([]byte(*resultJSON), &r)
  98. p.Result = &r
  99. }
  100. return &p, nil
  101. }
  102. // SetApplying marca el plan como en ejecución (pending → applying).
  103. // Devuelve ErrInvalidTransition si el plan ya no está pendiente, de modo que
  104. // un apply repetido o fuera de orden no puede mover el estado a ciegas.
  105. func (m *Manager) SetApplying(id, actor string) error {
  106. return m.transition(id, "pending", "applying", "applying", actor, "apply requested")
  107. }
  108. // SetRollingBack marca el plan como revertido en curso (applied →
  109. // rolling_back) porque un admin disparó POST /api/plans/{id}/rollback.
  110. // Solo se acepta desde applied: revertir algo que no se aplicó no tiene
  111. // sentido y dejaría el plan colgado. Registra auditoría.
  112. func (m *Manager) SetRollingBack(id, actor string) error {
  113. return m.transition(id, "applied", "rolling_back", "rollback", actor, "manual rollback triggered")
  114. }
  115. // RestoreTransition deshace una transición transitoria cuando el envío al
  116. // agente no llegó a entregarse (p. ej. applying → pending si el SSE falló).
  117. // El UPDATE va condicionado al estado de partida, así que nunca pisa un
  118. // resultado que el agente ya haya reportado. Registra auditoría "restore".
  119. func (m *Manager) RestoreTransition(id, from, to, actor, reason string) error {
  120. switch {
  121. case from != "applying" && from != "rolling_back":
  122. return fmt.Errorf("%w: cannot restore from %q", ErrInvalidTransition, from)
  123. case to != "pending" && to != "applied":
  124. return fmt.Errorf("%w: cannot restore to %q", ErrInvalidTransition, to)
  125. }
  126. detail := from + " -> " + to
  127. if reason != "" {
  128. detail += ": " + reason
  129. }
  130. return m.transition(id, from, to, "restore", actor, detail)
  131. }
  132. // transition mueve el plan de `from` a `to` solo si sigue en `from`
  133. // (UPDATE condicional, nunca a ciegas) y deja una línea de auditoría.
  134. func (m *Manager) transition(id, from, to, action, actor, detail string) error {
  135. res, err := m.db.Exec(`UPDATE orchestr_plans SET status = ? WHERE id = ? AND status = ?`, to, id, from)
  136. if err != nil {
  137. return err
  138. }
  139. n, err := res.RowsAffected()
  140. if err != nil {
  141. return err
  142. }
  143. if n == 0 {
  144. var cur string
  145. switch err := m.db.QueryRow(`SELECT status FROM orchestr_plans WHERE id = ?`, id).Scan(&cur); {
  146. case errors.Is(err, sql.ErrNoRows):
  147. return ErrPlanNotFound
  148. case err != nil:
  149. return err
  150. }
  151. return fmt.Errorf("%w: estado %q, se esperaba %q", ErrInvalidTransition, cur, from)
  152. }
  153. m.audit(id, action, actor, detail)
  154. return nil
  155. }
  156. // SetResult actualiza el plan con el resultado del agente y registra auditoría.
  157. // El estado final depende del estado de partida: si el plan estaba en
  158. // 'rolling_back', el apply con las ops inversas se traduce a rolled_back;
  159. // si el rollback en sí falló, queda failed. Nunca deja rolling_back.
  160. func (m *Manager) SetResult(id string, res ApplyResult) error {
  161. var prev string
  162. if err := m.db.QueryRow(`SELECT status FROM orchestr_plans WHERE id = ?`, id).Scan(&prev); err != nil {
  163. if errors.Is(err, sql.ErrNoRows) {
  164. return ErrPlanNotFound
  165. }
  166. return err
  167. }
  168. if res.Status == "" {
  169. res.Status = "failed"
  170. if res.Error == "" {
  171. res.Error = "el agente no reportó estado"
  172. }
  173. }
  174. final := res.Status
  175. switch prev {
  176. case "rolled_back":
  177. // rolled_back es terminal: un apply-result duplicado o tardío no
  178. // puede resucitar un plan que ya se revirtió.
  179. final = "rolled_back"
  180. case "rolling_back":
  181. switch res.Status {
  182. case "applied", "rolled_back":
  183. final = "rolled_back"
  184. case "failed":
  185. final = "failed" // el propio rollback no pudo revertir
  186. }
  187. case "applying":
  188. if res.Status == "rolled_back" {
  189. final = "rolled_back"
  190. }
  191. }
  192. resJSON, _ := json.Marshal(res)
  193. now := time.Now().Unix()
  194. _, err := m.db.Exec(
  195. `UPDATE orchestr_plans SET status = ?, applied_at = ?, result = ? WHERE id = ?`,
  196. final, now, string(resJSON), id)
  197. if err != nil {
  198. return err
  199. }
  200. m.audit(id, final, "agent", res.Error)
  201. return nil
  202. }
  203. // RecentAudit devuelve los últimos N eventos de auditoría.
  204. func (m *Manager) RecentAudit(limit int) ([]AuditEntry, error) {
  205. if limit <= 0 || limit > 200 {
  206. limit = 50
  207. }
  208. rows, err := m.db.Query(
  209. `SELECT plan_id, action, actor, detail, ts FROM orchestr_audit ORDER BY id DESC LIMIT ?`, limit)
  210. if err != nil {
  211. return nil, err
  212. }
  213. defer rows.Close()
  214. var out []AuditEntry
  215. for rows.Next() {
  216. var e AuditEntry
  217. if err := rows.Scan(&e.PlanID, &e.Action, &e.Actor, &e.Detail, &e.Ts); err != nil {
  218. return nil, err
  219. }
  220. out = append(out, e)
  221. }
  222. return out, nil
  223. }
  224. // AuditEntry es una línea del log de auditoría (append-only).
  225. type AuditEntry struct {
  226. PlanID string `json:"planId"`
  227. Action string `json:"action"`
  228. Actor string `json:"actor"`
  229. Detail string `json:"detail"`
  230. Ts int64 `json:"ts"`
  231. }
  232. func (m *Manager) audit(planID, action, actor, detail string) {
  233. m.db.Exec(
  234. `INSERT INTO orchestr_audit (plan_id, action, actor, detail, ts) VALUES (?, ?, ?, ?, ?)`,
  235. planID, action, actor, detail, time.Now().Unix())
  236. }
  237. func newID() string {
  238. b := make([]byte, 8)
  239. rand.Read(b)
  240. return hex.EncodeToString(b)
  241. }