-
Notifications
You must be signed in to change notification settings - Fork 19
/
discoverer.go
53 lines (44 loc) · 1017 Bytes
/
discoverer.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
package ids
import (
"io/ioutil"
"os"
"path/filepath"
"strconv"
"code.cloudfoundry.org/lager"
"github.com/pkg/errors"
)
func NewDiscoverer(idsPath string) *Discoverer {
return &Discoverer{
idsPath: idsPath,
}
}
type Discoverer struct {
idsPath string
}
func (i *Discoverer) Alloc(logger lager.Logger) (projId uint32, err error) {
logger = logger.Session("project-id-allocation")
logger.Debug("starting")
defer func() {
logger.Debug("ending", lager.Data{"projectID": projId})
}()
contents, err := ioutil.ReadDir(i.idsPath)
if err != nil {
return 0, errors.Wrap(err, "reading directory")
}
nextId := len(contents) + 1
return i.untilSucceeds(nextId)
}
func (i *Discoverer) untilSucceeds(startId int) (uint32, error) {
for {
if err := os.Mkdir(filepath.Join(i.idsPath, strconv.Itoa(startId)), 0755); err != nil {
if os.IsExist(err) {
startId++
} else {
return 0, errors.Wrap(err, "failed to create id file")
}
} else {
break
}
}
return uint32(startId), nil
}