2015-08-15 03:48:14 -04:00
|
|
|
// Package idm manages reservation/release of numerical ids from a configured set of contiguous ids
|
2015-06-13 19:04:06 -04:00
|
|
|
package idm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/docker/libnetwork/bitseq"
|
2015-06-15 14:43:02 -04:00
|
|
|
"github.com/docker/libnetwork/datastore"
|
2015-06-13 19:04:06 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// Idm manages the reservation/release of numerical ids from a contiguos set
|
|
|
|
type Idm struct {
|
2015-10-08 23:04:13 -04:00
|
|
|
start uint64
|
|
|
|
end uint64
|
2015-06-13 19:04:06 -04:00
|
|
|
handle *bitseq.Handle
|
|
|
|
}
|
|
|
|
|
|
|
|
// New returns an instance of id manager for a set of [start-end] numerical ids
|
2015-10-08 23:04:13 -04:00
|
|
|
func New(ds datastore.DataStore, id string, start, end uint64) (*Idm, error) {
|
2015-06-13 19:04:06 -04:00
|
|
|
if id == "" {
|
|
|
|
return nil, fmt.Errorf("Invalid id")
|
|
|
|
}
|
|
|
|
if end <= start {
|
|
|
|
return nil, fmt.Errorf("Invalid set range: [%d, %d]", start, end)
|
|
|
|
}
|
2015-06-16 17:46:51 -04:00
|
|
|
|
2015-06-24 18:02:08 -04:00
|
|
|
h, err := bitseq.NewHandle("idm", ds, id, 1+end-start)
|
2015-06-16 17:46:51 -04:00
|
|
|
if err != nil {
|
2015-06-18 15:06:11 -04:00
|
|
|
return nil, fmt.Errorf("failed to initialize bit sequence handler: %s", err.Error())
|
2015-06-16 17:46:51 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return &Idm{start: start, end: end, handle: h}, nil
|
2015-06-13 19:04:06 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetID returns the first available id in the set
|
2015-10-08 23:04:13 -04:00
|
|
|
func (i *Idm) GetID() (uint64, error) {
|
2015-06-13 19:04:06 -04:00
|
|
|
if i.handle == nil {
|
|
|
|
return 0, fmt.Errorf("ID set is not initialized")
|
|
|
|
}
|
2015-06-24 18:02:08 -04:00
|
|
|
ordinal, err := i.handle.SetAny()
|
|
|
|
return i.start + ordinal, err
|
2015-06-13 19:04:06 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetSpecificID tries to reserve the specified id
|
2015-10-08 23:04:13 -04:00
|
|
|
func (i *Idm) GetSpecificID(id uint64) error {
|
2015-06-13 19:04:06 -04:00
|
|
|
if i.handle == nil {
|
|
|
|
return fmt.Errorf("ID set is not initialized")
|
|
|
|
}
|
|
|
|
|
|
|
|
if id < i.start || id > i.end {
|
|
|
|
return fmt.Errorf("Requested id does not belong to the set")
|
|
|
|
}
|
|
|
|
|
2015-06-24 18:02:08 -04:00
|
|
|
return i.handle.Set(id - i.start)
|
2015-06-13 19:04:06 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Release releases the specified id
|
2015-10-08 23:04:13 -04:00
|
|
|
func (i *Idm) Release(id uint64) {
|
2015-06-24 18:02:08 -04:00
|
|
|
i.handle.Unset(id - i.start)
|
2015-06-13 19:04:06 -04:00
|
|
|
}
|