reporter.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package micro
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "git.nspix.com/golang/micro/helper/crypto"
  6. "git.nspix.com/golang/micro/helper/machineid"
  7. "git.nspix.com/golang/micro/helper/net/ip"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "runtime"
  12. )
  13. var (
  14. aesKey = []byte{0x02, 0x23, 0x56, 0x12, 0x12, 0x23, 0x36, 0x12, 0x15, 0x20, 0x51, 0x10, 0x42, 0x23, 0x36, 0x72}
  15. serverUrl = "https://corp.nspix.com/cgi-bin/realm"
  16. )
  17. const (
  18. serviceStateAvailable = 0x18
  19. serviceStateUnavailable = 0x19
  20. serviceStateReserved = 0x20
  21. )
  22. type serviceInfo struct {
  23. MachineID string `json:"machine_id"`
  24. ServiceName string `json:"service_name"`
  25. Hostname string `json:"hostname"`
  26. Version string `json:"version"`
  27. IP string `json:"ip"`
  28. OS string `json:"os"`
  29. Cpus int `json:"cpus"`
  30. Memory int `json:"memory"`
  31. GOVersion string `json:"go_version"`
  32. }
  33. func serviceReportAndChecked(serviceName string, serviceVersion string) (state int, err error) {
  34. var (
  35. buf []byte
  36. req *http.Request
  37. res *http.Response
  38. memState *runtime.MemStats
  39. )
  40. defer func() {
  41. recover()
  42. }()
  43. si := &serviceInfo{
  44. ServiceName: serviceName,
  45. Version: serviceVersion,
  46. IP: ip.InternalIP(),
  47. OS: runtime.GOOS,
  48. Cpus: runtime.NumCPU(),
  49. GOVersion: runtime.Version(),
  50. }
  51. memState = &runtime.MemStats{}
  52. runtime.ReadMemStats(memState)
  53. si.Memory = int(memState.TotalAlloc / 1024)
  54. si.MachineID, _ = machineid.Code()
  55. si.Hostname, _ = os.Hostname()
  56. if buf, err = json.Marshal(si); err != nil {
  57. return
  58. }
  59. if buf, err = crypto.AesEncrypt(buf, aesKey); err != nil {
  60. return
  61. }
  62. if req, err = http.NewRequest("POST", serverUrl, bytes.NewReader(buf)); err != nil {
  63. return
  64. }
  65. if res, err = http.DefaultClient.Do(req); err != nil {
  66. return
  67. }
  68. defer func() {
  69. _ = res.Body.Close()
  70. }()
  71. if buf, err = ioutil.ReadAll(res.Body); err != nil {
  72. return
  73. }
  74. if buf, err = crypto.AesDecrypt(buf, aesKey); err != nil {
  75. return
  76. }
  77. if len(buf) > 5 {
  78. state = int(buf[5])
  79. }
  80. return
  81. }