-
Notifications
You must be signed in to change notification settings - Fork 9
/
lease.go
60 lines (47 loc) · 1.05 KB
/
lease.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package service
import (
"fmt"
"sync"
"time"
)
type leaser struct {
mu sync.Mutex
cond *sync.Cond
active map[string]struct{}
last map[string]time.Time
}
func newLeaser() *leaser {
l := &leaser{
active: make(map[string]struct{}),
last: make(map[string]time.Time),
}
l.cond = sync.NewCond(&l.mu)
return l
}
var errDeployPlanTooOld = fmt.Errorf("incoming deployment is too old")
func (l *leaser) acquireLease(id string, new time.Time) (func(), error) {
if l == nil {
return nil, nil
}
l.mu.Lock()
defer l.mu.Unlock()
for {
if last, ok := l.last[id]; ok && last.After(new) {
return nil, errDeployPlanTooOld
}
if _, ok := l.active[id]; !ok {
l.active[id] = struct{}{}
l.last[id] = new
return func() {
l.mu.Lock()
defer l.mu.Unlock()
delete(l.active, id)
l.cond.Broadcast()
}, nil
}
l.cond.Wait()
}
}