telegraf_influx.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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
  13. package metadata
  14. import (
  15. "bytes"
  16. "compress/gzip"
  17. "context"
  18. "io"
  19. "net/http"
  20. "strings"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/onecloud/pkg/hostman/guestman/desc"
  24. )
  25. const telegrafInfluxMaxBodyBytes = 16 << 20
  26. func (s *Service) rewriteTelegrafInfluxBodyIfNeeded(ctx context.Context, r *http.Request) error {
  27. prefix := s.monitorPrefix()
  28. if !strings.HasPrefix(r.URL.Path, prefix) {
  29. return nil
  30. }
  31. sub := r.URL.Path[len(prefix):]
  32. if r.Method != http.MethodPost && r.Method != http.MethodPut {
  33. return nil
  34. }
  35. if sub != "/write" && !strings.HasPrefix(sub, "/write?") {
  36. return nil
  37. }
  38. body, err := io.ReadAll(io.LimitReader(r.Body, telegrafInfluxMaxBodyBytes+1))
  39. if err != nil {
  40. return errors.Wrap(err, "read telegraf influx body")
  41. }
  42. if len(body) > telegrafInfluxMaxBodyBytes {
  43. return errors.Errorf("telegraf influx body exceeds %d bytes", telegrafInfluxMaxBodyBytes)
  44. }
  45. _ = r.Body.Close()
  46. if strings.Contains(strings.ToLower(r.Header.Get("Content-Encoding")), "gzip") {
  47. gr, err := gzip.NewReader(bytes.NewReader(body))
  48. if err != nil {
  49. return errors.Wrap(err, "gzip reader")
  50. }
  51. body, err = io.ReadAll(io.LimitReader(gr, telegrafInfluxMaxBodyBytes+1))
  52. _ = gr.Close()
  53. if err != nil {
  54. return errors.Wrap(err, "read gzipped telegraf body")
  55. }
  56. if len(body) > telegrafInfluxMaxBodyBytes {
  57. return errors.Errorf("telegraf influx body exceeds %d bytes after gzip", telegrafInfluxMaxBodyBytes)
  58. }
  59. r.Header.Del("Content-Encoding")
  60. }
  61. newBody, changed, err := rewriteInfluxLineProtocolTenant(body, func(vmId string) (string, bool) {
  62. gd := s.lookupGuestDescForTelegraf(r, vmId)
  63. if gd == nil || gd.TenantId == "" {
  64. return "", false
  65. }
  66. return gd.TenantId, true
  67. })
  68. if err != nil {
  69. return err
  70. }
  71. if changed {
  72. log.Debugf("metadata monitor: corrected tenant_id in telegraf influx payload from %s", r.RemoteAddr)
  73. }
  74. r.Body = io.NopCloser(bytes.NewReader(newBody))
  75. r.ContentLength = int64(len(newBody))
  76. r.Header.Del("Content-Length")
  77. return nil
  78. }
  79. func (s *Service) lookupGuestDescForTelegraf(r *http.Request, vmId string) *desc.SGuestDesc {
  80. if vmId == "" {
  81. return nil
  82. }
  83. gd := s.getGuestDesc(r)
  84. if gd != nil && gd.Uuid == vmId {
  85. return gd
  86. }
  87. return nil
  88. }
  89. func rewriteInfluxLineProtocolTenant(body []byte, resolveTenant func(vmId string) (tenantId string, ok bool)) ([]byte, bool, error) {
  90. raw := strings.Split(string(body), "\n")
  91. changed := false
  92. for i, line := range raw {
  93. line = strings.TrimRight(line, "\r")
  94. if line == "" || strings.HasPrefix(line, "#") {
  95. continue
  96. }
  97. newLine, lineChanged, err := rewriteInfluxLineTenant(line, resolveTenant)
  98. if err != nil {
  99. return body, false, err
  100. }
  101. if lineChanged {
  102. changed = true
  103. raw[i] = newLine
  104. }
  105. }
  106. if !changed {
  107. return body, false, nil
  108. }
  109. return []byte(strings.Join(raw, "\n")), true, nil
  110. }
  111. func rewriteInfluxLineTenant(line string, resolveTenant func(vmId string) (tenantId string, ok bool)) (string, bool, error) {
  112. measTags, fields, ok := splitMeasurementTagsAndFields(line)
  113. if !ok {
  114. return line, false, nil
  115. }
  116. parts := splitOnUnescapedComma(measTags)
  117. if len(parts) < 1 {
  118. return line, false, nil
  119. }
  120. measurement := parts[0]
  121. tagSegs := parts[1:]
  122. vmId := ""
  123. haveTenant := false
  124. curTenant := ""
  125. for _, seg := range tagSegs {
  126. k, v := splitInfluxTagKeyValue(seg)
  127. if k == "" {
  128. continue
  129. }
  130. switch k {
  131. case "vm_id":
  132. vmId = v
  133. case "tenant_id":
  134. haveTenant = true
  135. curTenant = v
  136. }
  137. }
  138. if vmId == "" {
  139. return line, false, nil
  140. }
  141. expectTenant, ok := resolveTenant(vmId)
  142. if !ok {
  143. return line, false, nil
  144. }
  145. if haveTenant && curTenant == expectTenant {
  146. return line, false, nil
  147. }
  148. newSegs := make([]string, 0, len(tagSegs)+1)
  149. for _, seg := range tagSegs {
  150. k, _ := splitInfluxTagKeyValue(seg)
  151. if k == "tenant_id" {
  152. newSegs = append(newSegs, "tenant_id="+expectTenant)
  153. } else {
  154. newSegs = append(newSegs, seg)
  155. }
  156. }
  157. if !haveTenant {
  158. newSegs = append(newSegs, "tenant_id="+expectTenant)
  159. }
  160. var b strings.Builder
  161. b.WriteString(measurement)
  162. for _, seg := range newSegs {
  163. b.WriteByte(',')
  164. b.WriteString(seg)
  165. }
  166. b.WriteByte(' ')
  167. b.WriteString(fields)
  168. return b.String(), true, nil
  169. }
  170. func splitMeasurementTagsAndFields(line string) (measTags string, fields string, ok bool) {
  171. for i := 0; i < len(line); i++ {
  172. if line[i] == ' ' && !influxByteEscaped(line, i) {
  173. return line[:i], line[i+1:], true
  174. }
  175. }
  176. return "", "", false
  177. }
  178. func influxByteEscaped(line string, i int) bool {
  179. if i == 0 {
  180. return false
  181. }
  182. n := 0
  183. for j := i - 1; j >= 0 && line[j] == '\\'; j-- {
  184. n++
  185. }
  186. return n%2 == 1
  187. }
  188. func splitOnUnescapedComma(s string) []string {
  189. var out []string
  190. var b strings.Builder
  191. escaped := false
  192. for i := 0; i < len(s); i++ {
  193. c := s[i]
  194. if escaped {
  195. b.WriteByte(c)
  196. escaped = false
  197. continue
  198. }
  199. if c == '\\' {
  200. escaped = true
  201. b.WriteByte('\\')
  202. continue
  203. }
  204. if c == ',' {
  205. out = append(out, b.String())
  206. b.Reset()
  207. continue
  208. }
  209. b.WriteByte(c)
  210. }
  211. out = append(out, b.String())
  212. return out
  213. }
  214. func splitInfluxTagKeyValue(seg string) (key, val string) {
  215. for i := 0; i < len(seg); i++ {
  216. if seg[i] == '=' && !influxByteEscaped(seg, i) {
  217. return influxUnescapeTagKey(seg[:i]), seg[i+1:]
  218. }
  219. }
  220. return "", ""
  221. }
  222. func influxUnescapeTagKey(s string) string {
  223. return influxUnescapeTag(s)
  224. }
  225. func influxUnescapeTag(s string) string {
  226. var b strings.Builder
  227. b.Grow(len(s))
  228. for i := 0; i < len(s); i++ {
  229. if s[i] == '\\' && i+1 < len(s) {
  230. switch s[i+1] {
  231. case '\\', ' ', ',', '=':
  232. b.WriteByte(s[i+1])
  233. i++
  234. continue
  235. }
  236. }
  237. b.WriteByte(s[i])
  238. }
  239. return b.String()
  240. }