This repository has been archived by the owner on May 9, 2020. It is now read-only.
forked from bakanis/uuid
-
Notifications
You must be signed in to change notification settings - Fork 13
/
generator.go
381 lines (322 loc) · 10.4 KB
/
generator.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package uuid
import (
"bytes"
"crypto/rand"
"encoding/binary"
"log"
"net"
"os"
"sync"
)
var (
once *sync.Once = new(sync.Once)
generator *Generator = newGenerator(GeneratorConfig{})
)
// Random provides a CPRNG which reads into the given []byte, the package
// uses crypto/rand.Read by default. You can supply your own CPRNG. The
// function is used by V4 UUIDs and for setting up V1 and V2 UUIDs via the
// Generator Init or Register* functions.
type Random func([]byte) (int, error)
// Next provides the next Timestamp value to be used by the next V1 or V2 UUID.
// The default uses the uuid.spinner which spins at a resolution of
// 100ns ticks and provides a spin resolution redundancy of 1024
// cycles. This ensures that the system is not too quick when
// generating V1 or V2 UUIDs. Each system requires a tuned Resolution to
// enhance performance.
type Next func() Timestamp
// Id provides the Node to be used during the life of a uuid.Generator. If
// it cannot be determined nil should be returned, the package will
// then provide a crypto-random node id. The default generator gets a MAC
// address from the first interface that is up checking net.FlagUp.
type Id func() Node
// HandleError provides the user the ability to manage any serious
// error that may be caused by accessing the standard crypto/rand
// library. Due to the rarity of this occurrence the error is swallowed
// by NewV4 functions, which rely on random numbers, the package will then
// panic. You can change this behaviour by passing in your own HandleError
// function. With this function you can attempt to fix your CPRNG and then
// return true to try again. If another error occurs the function will return
// nil and you can then handle the error by calling uuid.Error or calling Error
// from your standalone Generator.
type HandleError func(error) bool
// Generator is used to create and monitor the running of V1 and V2, and V4
// UUIDs. It can be setup to take different implementations for Timestamp, Node
// and CPRNG retrieval. This is also where the Saver implementation can be
// given and your error policy for V4 Uuids can be setup.
type Generator struct {
// Access to the store needs to be maintained
sync.Mutex
// Once ensures that the generator is only setup and initialised once.
// This will occur either when you explicitly call the
// uuid.Generator.Init function or when a V1 or V2 id is generated.
sync.Once
err error
// Store contains the current values being used by the Generator.
*Store
// Id as per the type Id func() Node
Id
// HandleError as per the type HandleError func(error) bool
HandleError HandleError
// Next as per the type Next func() Timestamp
Next Next
// Random as per the type Random func([]byte) (int, error)
Random
// Intended to provide a non-volatile store to save the state of the
// generator, the default is nil and to therefore generate a timestamp
// clock sequence with random data. You can register your own save by
// using the uuid.RegisterSaver function or by creating your own
// uuid.Generator instance from which to generate your V1, V2 or V4
// UUIDs.
Saver
}
// GeneratorConfig allows you to setup a new uuid.Generator using
// uuid.NewGenerator or RegisterGenerator. You can supply your own
// implementations for CPRNG, Node Id and Timestamp retrieval. You can also
// adjust the resolution of the default Timestamp spinner and supply your own
// error handler CPRNG failures.
type GeneratorConfig struct {
Saver
Next
Resolution uint
Id
Random
HandleError
}
// NewGenerator will create a new uuid.Generator with the given functions.
func NewGenerator(pConfig GeneratorConfig) (gen *Generator) {
gen = newGenerator(pConfig)
generator.Do(generator.init)
return
}
func newGenerator(pConfig GeneratorConfig) (gen *Generator) {
gen = new(Generator)
if pConfig.Next == nil {
if pConfig.Resolution == 0 {
pConfig.Resolution = defaultSpinResolution
}
gen.Next = (&spinner{
Resolution: pConfig.Resolution,
Count: 0,
Timestamp: Now(),
}).next
} else {
gen.Next = pConfig.Next
}
if pConfig.Id == nil {
gen.Id = findFirstHardwareAddress
} else {
gen.Id = pConfig.Id
}
if pConfig.Random == nil {
gen.Random = rand.Read
} else {
gen.Random = pConfig.Random
}
if pConfig.HandleError == nil {
gen.HandleError = runHandleError
} else {
gen.HandleError = pConfig.HandleError
}
gen.Saver = pConfig.Saver
gen.Store = new(Store)
return
}
// Init will initialise the default generator with default settings
func Init() error {
return RegisterGenerator(GeneratorConfig{})
}
// RegisterGenerator will set the default generator to the given generator
// Like uuid.Init this can only be called once. Any subsequent calls will have no
// effect. If you call this you do not need to call uuid.Init
func RegisterGenerator(pConfig GeneratorConfig) (err error) {
gen := newGenerator(pConfig)
notOnce := true
once.Do(func() {
generator = gen
generator.Do(generator.init)
err = generator.Error()
notOnce = false
return
})
if notOnce {
log.Panicf("A uuid.Register* method cannot be called more than once.")
}
return
}
// Error will return any error from the uuid.Generator if a UUID returns as Nil
// or nil
func (o *Generator) Error() (err error) {
err = o.err
o.err = nil
return
}
func (o *Generator) read() {
// Save the state (current timestamp, clock sequence, and node ID)
// back to the stable store
if o.Saver != nil {
defer o.save()
}
// Obtain a lock
o.Lock()
defer o.Unlock()
// Get the current time as a 60-bit count of 100-nanosecond intervals
// since 00:00:00.00, 15 October 1582.
now := o.Next()
// If the last timestamp is later than
// the current timestamp, increment the clock sequence value.
if now <= o.Timestamp {
o.Sequence++
}
// Update the timestamp
o.Timestamp = now
}
func (o *Generator) init() {
// From a system-wide shared stable store (e.g., a file), read the
// UUID generator state: the values of the timestamp, clock sequence,
// and node ID used to generate the last UUID.
var (
storage Store
err error
)
o.Lock()
defer o.Unlock()
if o.Saver != nil {
err, storage = o.Read()
if err != nil {
o.Saver = nil
}
}
// Get the current time as a 60-bit count of 100-nanosecond intervals
// since 00:00:00.00, 15 October 1582.
now := o.Next()
// Get the current node id
node := o.Id()
if node == nil {
log.Println("uuid.Generator.init: address error: will generate random node id instead")
node = make([]byte, 6)
n, err := o.Random(node)
if err != nil {
log.Printf("uuid.Generator.init: could not read random bytes into node - read [%d] %s", n, err)
o.err = err
return
}
// Mark as randomly generated
node[0] |= 0x01
}
// If the state was unavailable (e.g., non-existent or corrupted), or
// the saved node ID is different than the current node ID, generate
// a random clock sequence value.
if o.Saver == nil || !bytes.Equal(storage.Node, node) {
// 4.1.5. Clock Sequence https://www.ietf.org/rfc/rfc4122.txt
//
// For UUID version 1, the clock sequence is used to help avoid
// duplicates that could arise when the clock is set backwards in time
// or if the node ID changes.
//
// If the clock is set backwards, or might have been set backwards
// (e.g., while the system was powered off), and the UUID generator can
// not be sure that no UUIDs were generated with timestamps larger than
// the value to which the clock was set, then the clock sequence has to
// be changed. If the previous value of the clock sequence is known, it
// can just be incremented; otherwise it should be set to a random or
// high-quality pseudo-random value.
// The clock sequence MUST be originally (i.e., once in the lifetime of
// a system) initialized to a random number to minimize the correlation
// across systems. This provides maximum protection against node
// identifiers that may move or switch from system to system rapidly.
// The initial value MUST NOT be correlated to the node identifier.
b := make([]byte, 2)
n, err := o.Random(b)
if err == nil {
storage.Sequence = Sequence(binary.BigEndian.Uint16(b))
log.Printf("uuid.Generator.init initialised random sequence: [%d]", storage.Sequence)
} else {
log.Printf("uuid.Generator.init: could not read random bytes into sequence - read [%d] %s", n, err)
o.err = err
return
}
} else if now < storage.Timestamp {
// If the state was available, but the saved timestamp is later than
// the current timestamp, increment the clock sequence value.
storage.Sequence++
}
storage.Timestamp = now
storage.Node = node
o.Store = &storage
}
func (o *Generator) save() {
func(pState *Generator) {
if pState.Saver != nil {
pState.Lock()
defer pState.Unlock()
pState.Save(*pState.Store)
}
}(o)
}
// NewV1 generates a new RFC4122 version 1 UUID based on a 60 bit timestamp and
// node id
func (o *Generator) NewV1() Uuid {
o.read()
id := array{}
makeUuid(&id,
uint32(o.Timestamp),
uint16(o.Timestamp>>32),
uint16(o.Timestamp>>48),
uint16(o.Sequence),
o.Node)
id.setRFC4122Version(1)
return id[:]
}
// NewV2 generates a new DCE version 2 UUID based on a 60 bit timestamp, node id
// and POSIX UID or GID
func (o *Generator) NewV2(pDomain Domain) Uuid {
o.read()
id := array{}
var domain uint32
switch pDomain {
case DomainUser:
domain = uint32(os.Getuid())
case DomainGroup:
domain = uint32(os.Getgid())
}
makeUuid(&id,
domain,
uint16(o.Timestamp>>32),
uint16(o.Timestamp>>48),
uint16(o.Sequence),
o.Node)
id[9] = byte(pDomain)
id.setRFC4122Version(2)
return id[:]
}
func makeUuid(pId *array, pLow uint32, pMid, pHiAndV, seq uint16, pNode Node) {
pId[0] = byte(pLow >> 24)
pId[1] = byte(pLow >> 16)
pId[2] = byte(pLow >> 8)
pId[3] = byte(pLow)
pId[4] = byte(pMid >> 8)
pId[5] = byte(pMid)
pId[6] = byte(pHiAndV >> 8)
pId[7] = byte(pHiAndV)
pId[8] = byte(seq >> 8)
pId[9] = byte(seq)
copy(pId[10:], pNode)
}
func findFirstHardwareAddress() (node Node) {
interfaces, err := net.Interfaces()
if err == nil {
for _, i := range interfaces {
if i.Flags&net.FlagUp != 0 && bytes.Compare(i.HardwareAddr, nil) != 0 {
// Don't use random as we have a real address
node = Node(i.HardwareAddr)
log.Println("uuid.findFirstHardwareAddress:", node)
break
}
}
}
return
}
func runHandleError(pErr error) bool {
log.Panicln("uuid.Generator ran into a serious problem with the random generator", pErr)
return false
}