nodeid.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Copyright 2019 Yunion
  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. package nodeid
  15. import (
  16. "bufio"
  17. "bytes"
  18. "crypto/md5"
  19. "encoding/hex"
  20. "fmt"
  21. "io/ioutil"
  22. "os"
  23. "os/exec"
  24. "reflect"
  25. "regexp"
  26. "runtime"
  27. "sort"
  28. "strconv"
  29. "strings"
  30. "yunion.io/x/log"
  31. )
  32. func execCmd(cmd *exec.Cmd) (string, error) {
  33. var out bytes.Buffer
  34. cmd.Stdout = &out
  35. err := cmd.Run()
  36. if err != nil {
  37. return "", err
  38. }
  39. return out.String(), nil
  40. }
  41. func stringToLines(s string) (lines []string, err error) {
  42. scanner := bufio.NewScanner(strings.NewReader(s))
  43. for scanner.Scan() {
  44. lines = append(lines, scanner.Text())
  45. }
  46. err = scanner.Err()
  47. return
  48. }
  49. func getLinuxMacAddress() (string, error) {
  50. path := "/sys/class/net/"
  51. fs, e := ioutil.ReadDir(path)
  52. if e != nil {
  53. return "", e
  54. }
  55. macs := []string{}
  56. for _, f := range fs {
  57. link, e := os.Readlink(path + f.Name())
  58. // 过滤掉虚拟网卡
  59. if e != nil || !strings.Contains(link, "/pci") {
  60. continue
  61. }
  62. u, e := ioutil.ReadFile(path + f.Name() + "/address")
  63. if e == nil {
  64. us := strings.TrimSpace(string(u))
  65. isNew := true
  66. for _, mac := range macs {
  67. if us == "00:00:00:00:00:00" || us == mac {
  68. isNew = false
  69. }
  70. }
  71. if isNew {
  72. macs = append(macs, us)
  73. }
  74. }
  75. }
  76. sort.SliceStable(macs, func(i, j int) bool {
  77. return macs[i] < macs[j]
  78. })
  79. if len(macs) < 1 {
  80. return "", fmt.Errorf("no available mac")
  81. }
  82. log.Debugf("macs info %s", macs)
  83. mac := strings.Replace(macs[0], ":", "", -1)
  84. if len(mac) != 12 {
  85. return "", fmt.Errorf("mac length error")
  86. }
  87. return mac, nil
  88. }
  89. func getLinuxCpuInfo() (string, error) {
  90. u, e := ioutil.ReadFile("/proc/cpuinfo")
  91. if e != nil {
  92. return "", e
  93. }
  94. lines, e := stringToLines(string(u))
  95. filted := []string{}
  96. for _, line := range lines {
  97. l := strings.TrimSpace(line)
  98. if strings.Contains(l, "cache size") || strings.Contains(l, "processor") {
  99. v := strings.Split(l, ":")[1]
  100. vn := strings.Replace(v, " ", "", -1)
  101. isNew := true
  102. for _, fl := range filted {
  103. if fl == vn {
  104. isNew = false
  105. }
  106. }
  107. if isNew {
  108. filted = append(filted, vn)
  109. }
  110. }
  111. }
  112. re := regexp.MustCompile(`([0-9]+)?.*`)
  113. sort.SliceStable(filted, func(i, j int) bool {
  114. a := re.FindStringSubmatch(filted[i])[1]
  115. b := re.FindStringSubmatch(filted[j])[1]
  116. if a == "" {
  117. if b == "" {
  118. return filted[i] < filted[j]
  119. } else if strings.HasPrefix(b, "0") {
  120. return false
  121. } else {
  122. return true
  123. }
  124. } else {
  125. if b == "" {
  126. if strings.HasPrefix(a, "0") {
  127. return true
  128. } else {
  129. return false
  130. }
  131. } else {
  132. if a == b {
  133. return len(filted[i]) < len(filted[j])
  134. } else {
  135. ia, _ := strconv.Atoi(a)
  136. ib, _ := strconv.Atoi(b)
  137. return ia < ib
  138. }
  139. }
  140. }
  141. })
  142. if len(filted) == 0 {
  143. return "", fmt.Errorf("no available cpu info")
  144. }
  145. log.Debugf("cpu info %s", filted)
  146. h := md5.New()
  147. h.Write([]byte(strings.Join(filted, "\n") + "\n"))
  148. cpumd5 := hex.EncodeToString(h.Sum(nil))
  149. return cpumd5, nil
  150. }
  151. func getLinux() ([]string, error) {
  152. ret := []string{}
  153. funcs := make([]interface{}, 0)
  154. funcs = append(funcs, getLinuxMacAddress)
  155. funcs = append(funcs, getLinuxCpuInfo)
  156. for _, f := range funcs {
  157. fi := reflect.ValueOf(f)
  158. s := fi.Call(nil)
  159. if e := s[1].Interface(); e == nil {
  160. ret = append(ret, s[0].Interface().(string))
  161. }
  162. }
  163. return ret, nil
  164. }
  165. func GetNodeId() ([]byte, error) {
  166. var f func() ([]string, error)
  167. if runtime.GOOS == "linux" {
  168. f = getLinux
  169. } else {
  170. return nil, fmt.Errorf("Unsupported OS")
  171. }
  172. ret, e := f()
  173. if e != nil || len(ret) < 2 {
  174. log.Debugf("service info %s", ret)
  175. return nil, fmt.Errorf("Fail to generate Node ID")
  176. }
  177. sn := md5.Sum([]byte(ret[0] + ret[1]))
  178. return sn[0:], nil
  179. }