-
Notifications
You must be signed in to change notification settings - Fork 4
/
orgs_fetcher.go
93 lines (78 loc) · 1.82 KB
/
orgs_fetcher.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package orgs_fetcher
import (
"context"
"fmt"
"sync"
"time"
"code.cloudfoundry.org/lager"
cfclient "github.com/cloudfoundry-community/go-cfclient"
)
type OrgsStore interface {
GetOrgs() []cfclient.Org
}
type OrgsFetcher struct {
Orgs []cfclient.Org
schedule time.Duration
logger lager.Logger
cfClient cfclient.CloudFoundryClient
mu sync.Mutex
}
func NewOrgsFetcher(
schedule time.Duration,
logger lager.Logger,
cfClient cfclient.CloudFoundryClient,
) *OrgsFetcher {
logger = logger.Session("orgs-fetcher")
return &OrgsFetcher{
schedule: schedule,
logger: logger,
cfClient: cfClient,
}
}
func (fetcher *OrgsFetcher) GetOrgs() []cfclient.Org {
fetcher.mu.Lock()
defer fetcher.mu.Unlock()
return fetcher.Orgs
}
func (fetcher *OrgsFetcher) Run(ctx context.Context) error {
loggerSession := fetcher.logger.Session("run")
loggerSession.Info("start")
defer loggerSession.Info("end")
err := fetcher.updateOrgs()
if err != nil {
return fmt.Errorf("error initialising list of orgs: %v", err)
}
for {
select {
case <-ctx.Done():
loggerSession.Info("done")
return nil
case <-time.After(fetcher.schedule):
err = fetcher.updateOrgs()
if err != nil {
return fmt.Errorf("error updating list of orgs: %v", err)
}
}
}
}
func (fetcher *OrgsFetcher) updateOrgs() error {
// FIXME: Relax this locking so it is short-lived
fetcher.mu.Lock()
defer fetcher.mu.Unlock()
orgs, err := fetcher.cfClient.ListOrgs()
if err != nil {
return fmt.Errorf("error fetching orgs: %v", err)
}
if orgs == nil {
return fmt.Errorf("list of orgs was nil")
}
fetcher.logger.Info("updated-orgs", lager.Data{
"number-of-orgs": len(orgs),
})
fetcher.logger.Debug("updated-orgs-list", lager.Data{
"orgs": orgs,
})
fetcher.Orgs = orgs
return nil
}
var _ OrgsStore = (*OrgsFetcher)(nil)