github.com/matrixorigin/matrixone@v1.2.0/pkg/util/uuidutil.go (about) 1 // Copyright 2022 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package util 16 17 import ( 18 "bytes" 19 "context" 20 "encoding/binary" 21 "hash/fnv" 22 "net" 23 24 "github.com/google/uuid" 25 "github.com/matrixorigin/matrixone/pkg/common/moerr" 26 ) 27 28 // getDefaultHardwareAddr returns hardware address(like mac addr), like the first valid val. 29 var getDefaultHardwareAddr = func(ctx context.Context) (net.HardwareAddr, error) { 30 ifaces, err := net.Interfaces() 31 if err != nil { 32 return []byte{}, err 33 } 34 for _, iface := range ifaces { 35 if len(iface.HardwareAddr) >= 6 { 36 return iface.HardwareAddr, nil 37 } 38 } 39 return []byte{}, moerr.NewInternalError(ctx, "uuid: no Hardware address found") 40 } 41 42 // docker mac addr range: [02:42:ac:11:00:00, 02:42:ac:11:ff:ff] 43 var dockerMacPrefix = []byte{0x02, 0x42, 0xac} 44 45 // SetUUIDNodeID set all uuid generator's node_id 46 func SetUUIDNodeID(ctx context.Context, nodeUuid []byte) error { 47 var err error 48 var hwAddr []byte 49 // situation 1: set by mac addr 50 hwAddr, err = getDefaultHardwareAddr(ctx) 51 if err == nil && !bytes.Equal(hwAddr[:len(dockerMacPrefix)], dockerMacPrefix) && uuid.SetNodeID(hwAddr) { 52 return nil 53 } 54 // case 2: set by nodeUuid prefix 55 if len(nodeUuid) > 6 && uuid.SetNodeID(nodeUuid) { 56 return nil 57 } 58 // case 3: set by md5sum{hwAddr + nodeUuid, randomUint64} 59 var num [8]byte 60 binary.BigEndian.PutUint64(num[:], Fastrand64()) 61 hasher := fnv.New128() 62 if _, err = hasher.Write(hwAddr); err != nil { 63 return err 64 } else if _, err := hasher.Write(nodeUuid); err != nil { 65 return err 66 } else if _, err := hasher.Write(num[:]); err != nil { 67 return err 68 } 69 var hash = make([]byte, 0, 16) 70 hash = hasher.Sum(hash[:]) 71 if !uuid.SetNodeID(hash[:]) { 72 return moerr.NewInternalError(ctx, "uuid: nodeID too short") 73 } 74 return nil 75 }