control.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package control
  2. import (
  3. "crypto/rand"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "fmt"
  7. "time"
  8. "google.golang.org/protobuf/proto"
  9. "google.golang.org/protobuf/types/known/durationpb"
  10. "google.golang.org/protobuf/types/known/timestamppb"
  11. hthv1 "hth/internal/gen/hth/api/v1"
  12. )
  13. // StaleSnapshotSlack is how many snapshot_seq increments may pass before a
  14. // based_on_snapshot_seq is considered too old. Seq advances on every poll, so
  15. // exact equality would reject any action that is not issued in the same
  16. // millisecond as GetSnapshot.
  17. const StaleSnapshotSlack uint64 = 32
  18. type Lease struct {
  19. ID string
  20. Epoch uint64
  21. DeviceID string
  22. Holder string
  23. Created time.Time
  24. Expires time.Time
  25. MaxTTL time.Duration
  26. }
  27. func (l *Lease) Active(now time.Time) bool {
  28. return l != nil && now.Before(l.Expires)
  29. }
  30. func (l *Lease) Proto() *hthv1.ControlLease {
  31. if l == nil {
  32. return nil
  33. }
  34. return &hthv1.ControlLease{
  35. LeaseId: l.ID,
  36. LeaseEpoch: l.Epoch,
  37. DeviceId: l.DeviceID,
  38. Holder: l.Holder,
  39. CreatedAt: timestamppb.New(l.Created),
  40. ExpiresAt: timestamppb.New(l.Expires),
  41. MaxTtl: durationpb.New(l.MaxTTL),
  42. Active: true,
  43. }
  44. }
  45. func (l *Lease) Summary(now time.Time) *hthv1.LeaseSummary {
  46. if l == nil {
  47. return &hthv1.LeaseSummary{}
  48. }
  49. return &hthv1.LeaseSummary{
  50. LeaseId: l.ID,
  51. LeaseEpoch: l.Epoch,
  52. Holder: l.Holder,
  53. ExpiresAt: timestamppb.New(l.Expires),
  54. Active: l.Active(now),
  55. }
  56. }
  57. type CacheEntry struct {
  58. CommandID string
  59. Payload []byte
  60. Result *hthv1.ActionResult
  61. }
  62. type Cache struct {
  63. max int
  64. order []string
  65. m map[string]CacheEntry
  66. }
  67. func NewCache(max int) *Cache {
  68. if max <= 0 {
  69. max = 256
  70. }
  71. return &Cache{max: max, m: map[string]CacheEntry{}}
  72. }
  73. func PayloadHash(batch *hthv1.ActionBatch) []byte {
  74. if batch == nil {
  75. return nil
  76. }
  77. cp := proto.Clone(batch).(*hthv1.ActionBatch)
  78. cp.LeaseId = ""
  79. cp.LeaseEpoch = 0
  80. cp.ValidUntil = nil
  81. cp.BasedOnSnapshotSeq = 0
  82. cp.ExpectedControlRevision = 0
  83. b, _ := proto.Marshal(cp)
  84. sum := sha256.Sum256(b)
  85. return sum[:]
  86. }
  87. func (c *Cache) Lookup(commandID string, payload []byte) (hit *hthv1.ActionResult, conflict bool) {
  88. e, ok := c.m[commandID]
  89. if !ok {
  90. return nil, false
  91. }
  92. if !bytesEq(e.Payload, payload) {
  93. return nil, true
  94. }
  95. return proto.Clone(e.Result).(*hthv1.ActionResult), false
  96. }
  97. func (c *Cache) Store(commandID string, payload []byte, result *hthv1.ActionResult) {
  98. if commandID == "" {
  99. return
  100. }
  101. if _, ok := c.m[commandID]; !ok {
  102. if len(c.order) >= c.max {
  103. old := c.order[0]
  104. c.order = c.order[1:]
  105. delete(c.m, old)
  106. }
  107. c.order = append(c.order, commandID)
  108. }
  109. c.m[commandID] = CacheEntry{
  110. CommandID: commandID,
  111. Payload: append([]byte(nil), payload...),
  112. Result: proto.Clone(result).(*hthv1.ActionResult),
  113. }
  114. }
  115. func (c *Cache) Clear() {
  116. c.order = nil
  117. c.m = map[string]CacheEntry{}
  118. }
  119. func bytesEq(a, b []byte) bool {
  120. if len(a) != len(b) {
  121. return false
  122. }
  123. for i := range a {
  124. if a[i] != b[i] {
  125. return false
  126. }
  127. }
  128. return true
  129. }
  130. type Manager struct {
  131. deviceID string
  132. minTTL time.Duration
  133. maxTTL time.Duration
  134. lease *Lease
  135. epoch uint64
  136. cache *Cache
  137. }
  138. func NewManager(deviceID string, minTTL, maxTTL time.Duration, cacheSize int) *Manager {
  139. return &Manager{
  140. deviceID: deviceID,
  141. minTTL: minTTL,
  142. maxTTL: maxTTL,
  143. cache: NewCache(cacheSize),
  144. }
  145. }
  146. func (m *Manager) Current() *Lease { return m.lease }
  147. func (m *Manager) Cache() *Cache { return m.cache }
  148. func RandomID() string {
  149. var b [16]byte
  150. if _, err := rand.Read(b[:]); err != nil {
  151. return fmt.Sprintf("%d", time.Now().UnixNano())
  152. }
  153. return hex.EncodeToString(b[:])
  154. }
  155. func (m *Manager) Acquire(now time.Time, holder string, ttl time.Duration) (*Lease, error) {
  156. if holder == "" {
  157. return nil, fmt.Errorf("holder required")
  158. }
  159. if m.lease != nil && m.lease.Active(now) {
  160. return nil, fmt.Errorf("lease already held by %s", m.lease.Holder)
  161. }
  162. ttl = m.clampTTL(ttl)
  163. m.epoch++
  164. m.cache.Clear()
  165. l := &Lease{
  166. ID: RandomID(),
  167. Epoch: m.epoch,
  168. DeviceID: m.deviceID,
  169. Holder: holder,
  170. Created: now,
  171. Expires: now.Add(ttl),
  172. MaxTTL: m.maxTTL,
  173. }
  174. m.lease = l
  175. return l, nil
  176. }
  177. func (m *Manager) Renew(now time.Time, id string, epoch uint64, ttl time.Duration) (*Lease, error) {
  178. if err := m.match(now, id, epoch); err != nil {
  179. return nil, err
  180. }
  181. ttl = m.clampTTL(ttl)
  182. m.lease.Expires = now.Add(ttl)
  183. return m.lease, nil
  184. }
  185. func (m *Manager) Release(now time.Time, id string, epoch uint64) error {
  186. if err := m.match(now, id, epoch); err != nil {
  187. return err
  188. }
  189. m.Invalidate()
  190. return nil
  191. }
  192. func (m *Manager) match(now time.Time, id string, epoch uint64) error {
  193. if m.lease == nil || !m.lease.Active(now) {
  194. return fmt.Errorf("lease expired or missing")
  195. }
  196. if m.lease.ID != id || m.lease.Epoch != epoch {
  197. return fmt.Errorf("lease mismatch")
  198. }
  199. return nil
  200. }
  201. func (m *Manager) CheckAction(now time.Time, batch *hthv1.ActionBatch, snapSeq, controlRev uint64) hthv1.RejectReason {
  202. if batch == nil || batch.CommandId == "" {
  203. return hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT
  204. }
  205. if m.lease == nil || !m.lease.Active(now) {
  206. if batch.LeaseId == "" {
  207. return hthv1.RejectReason_REJECT_REASON_LEASE_MISSING
  208. }
  209. return hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED
  210. }
  211. if batch.LeaseId != m.lease.ID {
  212. return hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH
  213. }
  214. if batch.LeaseEpoch != m.lease.Epoch {
  215. return hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH
  216. }
  217. if batch.ValidUntil != nil && !batch.ValidUntil.AsTime().After(now) {
  218. return hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE
  219. }
  220. if batch.BasedOnSnapshotSeq != 0 {
  221. if batch.BasedOnSnapshotSeq > snapSeq {
  222. return hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT
  223. }
  224. if snapSeq-batch.BasedOnSnapshotSeq > StaleSnapshotSlack {
  225. return hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT
  226. }
  227. }
  228. if batch.ExpectedControlRevision != 0 && batch.ExpectedControlRevision != controlRev {
  229. return hthv1.RejectReason_REJECT_REASON_STALE_CONTROL_REVISION
  230. }
  231. return hthv1.RejectReason_REJECT_REASON_UNSPECIFIED
  232. }
  233. func (m *Manager) ExpireIfNeeded(now time.Time) *Lease {
  234. if m.lease != nil && !m.lease.Active(now) {
  235. old := m.lease
  236. m.Invalidate()
  237. return old
  238. }
  239. return nil
  240. }
  241. func (m *Manager) Invalidate() {
  242. m.lease = nil
  243. m.cache.Clear()
  244. }
  245. func (m *Manager) InvalidateAndBump() {
  246. m.Invalidate()
  247. m.epoch++
  248. }
  249. func (m *Manager) clampTTL(ttl time.Duration) time.Duration {
  250. if ttl <= 0 {
  251. return m.maxTTL
  252. }
  253. if ttl < m.minTTL {
  254. return m.minTTL
  255. }
  256. if ttl > m.maxTTL {
  257. return m.maxTTL
  258. }
  259. return ttl
  260. }