apm_host_info.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package node
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "github.com/coroot/coroot-node-agent/flags"
  6. "github.com/coroot/coroot-node-agent/utils"
  7. . "github.com/coroot/coroot-node-agent/utils/modelse"
  8. klog "github.com/sirupsen/logrus"
  9. "gopkg.in/ini.v1"
  10. "strconv"
  11. "strings"
  12. )
  13. func NewNodeInfo(name, kv string) (*NodeInfoT, error) {
  14. ni, err := newNodeInfoFromCommonIni(name, kv)
  15. if err != nil {
  16. klog.Errorf("Failed to create node info from common ini: %v", err)
  17. } else {
  18. klog.Infof("run in omniagent.")
  19. *flags.RunInOmniagent = true
  20. return ni, err
  21. }
  22. ip, err := utils.GetRealIp()
  23. if err != nil {
  24. return nil, err
  25. }
  26. n := &NodeInfoT{
  27. Hostname: name,
  28. HostIp: ip,
  29. KernelVersion: kv,
  30. SystemUUID: utils.SystemUUID(),
  31. HostID: utils.GetHostID(),
  32. AccountID: utils.GetAccountID(),
  33. LicenseKey: *flags.LicenseKey,
  34. }
  35. utils.SaveNodeInfo(n)
  36. klog.Infof("run standalone.")
  37. return n, nil
  38. }
  39. func newNodeInfoFromCommonIni(name, kv string) (*NodeInfoT, error) {
  40. if *flags.CommonIni != "" {
  41. iniData, err := ini.Load(*flags.CommonIni)
  42. if err != nil {
  43. return nil, err
  44. }
  45. if iniData == nil {
  46. return nil, fmt.Errorf("no ini data")
  47. }
  48. ip := iniData.Section("common").Key("ip").String()
  49. uuid := iniData.Section("common").Key("system_uuid").String()
  50. host_id, err := iniData.Section("common").Key("host_id").Int64()
  51. if err != nil {
  52. return nil, err
  53. }
  54. token := iniData.Section("common").Key("token").String()
  55. account_and_user_byte, err := base64.StdEncoding.DecodeString(token)
  56. if err != nil {
  57. return nil, err
  58. }
  59. account_and_user_string := strings.Split(string(account_and_user_byte), "@")
  60. if len(account_and_user_string) > 0 {
  61. accountId, err := strconv.Atoi(account_and_user_string[0])
  62. if err == nil {
  63. n := &NodeInfoT{
  64. Hostname: name,
  65. HostIp: ip,
  66. KernelVersion: kv,
  67. SystemUUID: uuid,
  68. HostID: host_id,
  69. AccountID: accountId,
  70. LicenseKey: *flags.LicenseKey,
  71. }
  72. utils.SaveNodeInfo(n)
  73. return n, nil
  74. }
  75. }
  76. }
  77. return nil, nil
  78. }