2015-04-22 19:53:05 +02:00
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2017-06-13 22:58:31 +02:00
|
|
|
"strings"
|
2016-11-16 03:09:32 +01:00
|
|
|
"sync"
|
2017-06-13 22:58:31 +02:00
|
|
|
"time"
|
2015-04-22 19:53:05 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const UniqueIdPrefix = `terraform-`
|
|
|
|
|
2017-06-13 22:58:31 +02:00
|
|
|
// idCounter is a monotonic counter for generating ordered unique ids.
|
2016-11-16 03:09:32 +01:00
|
|
|
var idMutex sync.Mutex
|
2017-06-13 22:58:31 +02:00
|
|
|
var idCounter uint32
|
2016-11-16 03:09:32 +01:00
|
|
|
|
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
|
2017-06-13 22:58:31 +02:00
|
|
|
// previous timestamp output). After the prefix, the ID consists of a timestamp
|
|
|
|
// and an incrementing 8 hex digit value The timestamp means that multiple IDs
|
|
|
|
// created with the same prefix will sort in the order of their creation, even
|
|
|
|
// across multiple terraform executions, as long as the clock is not turned back
|
|
|
|
// between calls, and as long as any given terraform execution generates fewer
|
|
|
|
// than 4 billion IDs.
|
2015-06-30 13:54:32 +02:00
|
|
|
func PrefixedUniqueId(prefix string) string {
|
2017-06-13 22:58:31 +02:00
|
|
|
// Be precise to 4 digits of fractional seconds, but remove the dot before the
|
|
|
|
// fractional seconds.
|
|
|
|
timestamp := strings.Replace(
|
|
|
|
time.Now().UTC().Format("20060102150405.0000"), ".", "", 1)
|
|
|
|
|
2016-11-16 03:09:32 +01:00
|
|
|
idMutex.Lock()
|
|
|
|
defer idMutex.Unlock()
|
2017-06-13 22:58:31 +02:00
|
|
|
idCounter++
|
|
|
|
return fmt.Sprintf("%s%s%08x", prefix, timestamp, idCounter)
|
2015-04-22 20:16:44 +02:00
|
|
|
}
|