|
25 | 25 | package uid |
26 | 26 |
|
27 | 27 | import ( |
| 28 | + "encoding/binary" |
28 | 29 | "time" |
29 | 30 |
|
30 | 31 | "github.com/AliceO2Group/Control/common/logger" |
| 32 | + "github.com/denisbrodbeck/machineid" |
31 | 33 | "github.com/osamingo/indigo" |
| 34 | + "github.com/pborman/uuid" |
32 | 35 | "github.com/rs/xid" |
33 | 36 | "github.com/sirupsen/logrus" |
34 | 37 | ) |
35 | 38 |
|
| 39 | +type ID string |
36 | 40 | var ( |
37 | 41 | log = logger.New(logrus.StandardLogger(),"utils") |
38 | | - uidGen = indigo.New(nil, indigo.StartTime( |
39 | | - time.Unix(1257894000, 0)), |
40 | | - indigo.MachineID(func() (uint16, error){return 42, nil})) |
| 42 | + uidGen *indigo.Generator |
41 | 43 | ) |
42 | 44 |
|
43 | | -type ID string |
| 45 | + |
| 46 | +func init() { |
| 47 | + // In order to correctly seed ID generation and ensure that all generated IDs |
| 48 | + // are reasonably unique to a given machine, we need to provide a uint16 |
| 49 | + // that represents the current machine. |
| 50 | + // By default, Sonyflake/Indigo attempt to acquire such an ID from the machine's |
| 51 | + // private IP address, but this doesn't always work (e.g. on some Docker |
| 52 | + // instances). |
| 53 | + // So we use denisbrodbeck/machineid to read in the standard machine-id in a |
| 54 | + // cross-platform way. On CentOS and similar Linuxes, this means that we read |
| 55 | + // the file /etc/machine-id. |
| 56 | + // This file contains a standard UUID as string, so we need to parse it into |
| 57 | + // a []byte, and fetch 2 of these bytes to generate the uint16 ID. If this |
| 58 | + // fails, the uint16 ID defaults to 42. |
| 59 | + var machineId uint16 = 42 |
| 60 | + |
| 61 | + id, err := machineid.ID() |
| 62 | + if err == nil { |
| 63 | + parsed := uuid.Parse(id) |
| 64 | + if parsed != nil { |
| 65 | + // The NodeID consists of the last 6 bytes of the full UUID. |
| 66 | + // We use the first 2 bytes of this 6-byte block instead of the full |
| 67 | + // uuid.Array because the first 10 bits are clock-dependent. |
| 68 | + array := parsed.NodeID() |
| 69 | + machineId = binary.BigEndian.Uint16(array[0:2]) |
| 70 | + } |
| 71 | + } else { |
| 72 | + id = "<not available>" |
| 73 | + } |
| 74 | + log.Infof("machine UUID: %s generator machine ID: %d", id, machineId) |
| 75 | + |
| 76 | + uidGen = indigo.New( |
| 77 | + nil, |
| 78 | + indigo.StartTime(time.Unix(1257894000, 0)), // Go epoch |
| 79 | + indigo.MachineID(func() (uint16, error){return machineId, nil}), |
| 80 | + ) |
| 81 | +} |
44 | 82 |
|
45 | 83 | func (u ID) String() string { |
46 | 84 | return string(u) |
|
0 commit comments