2015-04-22 19:53:05 +02:00
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"fmt"
|
2016-11-16 03:09:32 +01:00
|
|
|
"math/big"
|
|
|
|
"sync"
|
2015-04-22 19:53:05 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const UniqueIdPrefix = `terraform-`
|
|
|
|
|
2016-11-16 03:09:32 +01:00
|
|
|
// idCounter is a randomly seeded monotonic counter for generating ordered
|
|
|
|
// unique ids. It uses a big.Int so we can easily increment a long numeric
|
|
|
|
// string. The max possible hex value here with 12 random bytes is
|
|
|
|
// "01000000000000000000000000", so there's no chance of rollover during
|
|
|
|
// operation.
|
|
|
|
var idMutex sync.Mutex
|
|
|
|
var idCounter = big.NewInt(0).SetBytes(randomBytes(12))
|
|
|
|
|
2015-06-30 13:54:32 +02:00
|
|
|
// Helper for a resource to generate a unique identifier w/ default prefix
|
|
|
|
func UniqueId() string {
|
|
|
|
return PrefixedUniqueId(UniqueIdPrefix)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Helper for a resource to generate a unique identifier w/ given prefix
|
2015-04-22 19:53:05 +02:00
|
|
|
//
|
2016-11-16 03:09:32 +01:00
|
|
|
// After the prefix, the ID consists of an incrementing 26 digit value (to match
|
|
|
|
// previous timestamp output).
|
2015-06-30 13:54:32 +02:00
|
|
|
func PrefixedUniqueId(prefix string) string {
|
2016-11-16 03:09:32 +01:00
|
|
|
idMutex.Lock()
|
|
|
|
defer idMutex.Unlock()
|
|
|
|
return fmt.Sprintf("%s%026x", prefix, idCounter.Add(idCounter, big.NewInt(1)))
|
2016-08-17 04:40:05 +02:00
|
|
|
}
|
2015-04-22 20:16:44 +02:00
|
|
|
|
2016-08-17 04:40:05 +02:00
|
|
|
func randomBytes(n int) []byte {
|
|
|
|
b := make([]byte, n)
|
|
|
|
rand.Read(b)
|
|
|
|
return b
|
2015-04-22 20:16:44 +02:00
|
|
|
}
|