point.go 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  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 influxdbsubscribe
  15. import (
  16. "bytes"
  17. "encoding/binary"
  18. "fmt"
  19. "math"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/pkg/errors"
  25. )
  26. var (
  27. measurementEscapeCodes = map[byte][]byte{
  28. ',': []byte(`\,`),
  29. ' ': []byte(`\ `),
  30. }
  31. tagEscapeCodes = map[byte][]byte{
  32. ',': []byte(`\,`),
  33. ' ': []byte(`\ `),
  34. '=': []byte(`\=`),
  35. }
  36. ErrPointMustHaveAField = errors.New("point without fields is unsupported")
  37. ErrInvalidNumber = errors.New("invalid number")
  38. ErrInvalidPoint = errors.New("point is invalid")
  39. ErrMaxKeyLengthExceeded = errors.New("max key length exceeded")
  40. )
  41. const (
  42. MaxKeyLength = 65535
  43. )
  44. // Point defines the values that will be written to the database
  45. type Point interface {
  46. Name() string
  47. SetName(string)
  48. Tags() Tags
  49. AddTag(key, value string)
  50. SetTags(tags Tags)
  51. Fields() Fields
  52. Time() time.Time
  53. SetTime(t time.Time)
  54. UnixNano() int64
  55. Key() []byte
  56. Data() []byte
  57. SetData(buf []byte)
  58. // String returns a string representation of the point, if there is a
  59. // timestamp associated with the point then it will be specified with the default
  60. // precision of nanoseconds
  61. String() string
  62. // Bytes returns a []byte representation of the point similar to string.
  63. MarshalBinary() ([]byte, error)
  64. // PrecisionString returns a string representation of the point, if there
  65. // is a timestamp associated with the point then it will be specified in the
  66. // given unit
  67. PrecisionString(precision string) string
  68. // RoundedString returns a string representation of the point, if there
  69. // is a timestamp associated with the point, then it will be rounded to the
  70. // given duration
  71. RoundedString(d time.Duration) string
  72. // Split will attempt to return multiple points with the same timestamp whose
  73. // string representations are no longer than size. Points with a single field or
  74. // a point without a timestamp may exceed the requested size.
  75. Split(size int) []Point
  76. // Round will round the timestamp of the point to the given duration
  77. Round(d time.Duration)
  78. // StringSize returns the length of the string that would be returned by String()
  79. StringSize() int
  80. // AppendString appends the result of String() to the provided buffer and returns
  81. // the result, potentially reducing string allocations
  82. AppendString(buf []byte) []byte
  83. // FieldIterator retuns a FieldIterator that can be used to traverse the
  84. // fields of a point without constructing the in-memory map
  85. FieldIterator() FieldIterator
  86. }
  87. type FieldType int
  88. const (
  89. Integer FieldType = iota
  90. Float
  91. Boolean
  92. String
  93. Empty
  94. )
  95. type FieldIterator interface {
  96. Next() bool
  97. FieldKey() []byte
  98. Type() FieldType
  99. StringValue() string
  100. IntegerValue() int64
  101. BooleanValue() bool
  102. FloatValue() float64
  103. Delete()
  104. Reset()
  105. }
  106. // Points represents a sortable list of points by timestamp.
  107. type Points []Point
  108. func (a Points) Len() int { return len(a) }
  109. func (a Points) Less(i, j int) bool { return a[i].Time().Before(a[j].Time()) }
  110. func (a Points) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  111. // point is the default implementation of Point.
  112. type point struct {
  113. time time.Time
  114. // text encoding of measurement and tags
  115. // key must always be stored sorted by tags, if the original line was not sorted,
  116. // we need to resort it
  117. key []byte
  118. // text encoding of field data
  119. fields []byte
  120. // text encoding of timestamp
  121. ts []byte
  122. // binary encoded field data
  123. data []byte
  124. // cached version of parsed fields from data
  125. cachedFields map[string]interface{}
  126. // cached version of parsed name from key
  127. cachedName string
  128. // cached version of parsed tags
  129. cachedTags Tags
  130. it fieldIterator
  131. }
  132. const (
  133. // the number of characters for the largest possible int64 (9223372036854775807)
  134. maxInt64Digits = 19
  135. // the number of characters for the smallest possible int64 (-9223372036854775808)
  136. minInt64Digits = 20
  137. // the number of characters required for the largest float64 before a range check
  138. // would occur during parsing
  139. maxFloat64Digits = 25
  140. // the number of characters required for smallest float64 before a range check occur
  141. // would occur during parsing
  142. minFloat64Digits = 27
  143. )
  144. // ParsePoints returns a slice of Points from a text representation of a point
  145. // with each point separated by newlines. If any points fail to parse, a non-nil error
  146. // will be returned in addition to the points that parsed successfully.
  147. func ParsePoints(buf []byte) ([]Point, error) {
  148. return ParsePointsWithPrecision(buf, time.Now().UTC(), "n")
  149. }
  150. // ParsePointsString is identical to ParsePoints but accepts a string
  151. // buffer.
  152. func ParsePointsString(buf string) ([]Point, error) {
  153. return ParsePoints([]byte(buf))
  154. }
  155. // ParseKey returns the measurement name and tags from a point.
  156. //
  157. // NOTE: to minimize heap allocations, the returned Tags will refer to subslices of buf.
  158. // This can have the unintended effect preventing buf from being garbage collected.
  159. func ParseKey(buf []byte) (string, Tags, error) {
  160. // Ignore the error because scanMeasurement returns "missing fields" which we ignore
  161. // when just parsing a key
  162. state, i, _ := scanMeasurement(buf, 0)
  163. var tags Tags
  164. if state == tagKeyState {
  165. tags = parseTags(buf)
  166. // scanMeasurement returns the location of the comma if there are tags, strip that off
  167. return string(buf[:i-1]), tags, nil
  168. }
  169. return string(buf[:i]), tags, nil
  170. }
  171. // ParsePointsWithPrecision is similar to ParsePoints, but allows the
  172. // caller to provide a precision for time.
  173. //
  174. // NOTE: to minimize heap allocations, the returned Points will refer to subslices of buf.
  175. // This can have the unintended effect preventing buf from being garbage collected.
  176. func ParsePointsWithPrecision(buf []byte, defaultTime time.Time, precision string) ([]Point, error) {
  177. points := make([]Point, 0, bytes.Count(buf, []byte{'\n'})+1)
  178. var (
  179. pos int
  180. block []byte
  181. failed []string
  182. )
  183. for pos < len(buf) {
  184. pos, block = scanLine(buf, pos)
  185. pos++
  186. if len(block) == 0 {
  187. continue
  188. }
  189. // lines which start with '#' are comments
  190. start := skipWhitespace(block, 0)
  191. // If line is all whitespace, just skip it
  192. if start >= len(block) {
  193. continue
  194. }
  195. if block[start] == '#' {
  196. continue
  197. }
  198. // strip the newline if one is present
  199. if block[len(block)-1] == '\n' {
  200. block = block[:len(block)-1]
  201. }
  202. pt, err := parsePoint(block[start:], defaultTime, precision)
  203. if err != nil {
  204. failed = append(failed, fmt.Sprintf("unable to parse '%s': %v", string(block[start:len(block)]), err))
  205. } else {
  206. points = append(points, pt)
  207. }
  208. }
  209. if len(failed) > 0 {
  210. return points, fmt.Errorf("%s", strings.Join(failed, "\n"))
  211. }
  212. return points, nil
  213. }
  214. func parsePoint(buf []byte, defaultTime time.Time, precision string) (Point, error) {
  215. // scan the first block which is measurement[,tag1=value1,tag2=value=2...]
  216. pos, key, err := scanKey(buf, 0)
  217. if err != nil {
  218. return nil, err
  219. }
  220. // measurement name is required
  221. if len(key) == 0 {
  222. return nil, fmt.Errorf("missing measurement")
  223. }
  224. if len(key) > MaxKeyLength {
  225. return nil, fmt.Errorf("max key length exceeded: %v > %v", len(key), MaxKeyLength)
  226. }
  227. // scan the second block is which is field1=value1[,field2=value2,...]
  228. pos, fields, err := scanFields(buf, pos)
  229. if err != nil {
  230. return nil, err
  231. }
  232. // at least one field is required
  233. if len(fields) == 0 {
  234. return nil, fmt.Errorf("missing fields")
  235. }
  236. // scan the last block which is an optional integer timestamp
  237. pos, ts, err := scanTime(buf, pos)
  238. if err != nil {
  239. return nil, err
  240. }
  241. pt := &point{
  242. key: key,
  243. fields: fields,
  244. ts: ts,
  245. }
  246. if len(ts) == 0 {
  247. pt.time = defaultTime
  248. pt.SetPrecision(precision)
  249. } else {
  250. ts, err := parseIntBytes(ts, 10, 64)
  251. if err != nil {
  252. return nil, err
  253. }
  254. pt.time, err = SafeCalcTime(ts, precision)
  255. if err != nil {
  256. return nil, err
  257. }
  258. // Determine if there are illegal non-whitespace characters after the
  259. // timestamp block.
  260. for pos < len(buf) {
  261. if buf[pos] != ' ' {
  262. return nil, ErrInvalidPoint
  263. }
  264. pos++
  265. }
  266. }
  267. return pt, nil
  268. }
  269. // GetPrecisionMultiplier will return a multiplier for the precision specified
  270. func GetPrecisionMultiplier(precision string) int64 {
  271. d := time.Nanosecond
  272. switch precision {
  273. case "u":
  274. d = time.Microsecond
  275. case "ms":
  276. d = time.Millisecond
  277. case "s":
  278. d = time.Second
  279. case "m":
  280. d = time.Minute
  281. case "h":
  282. d = time.Hour
  283. }
  284. return int64(d)
  285. }
  286. // scanKey scans buf starting at i for the measurement and tag portion of the point.
  287. // It returns the ending position and the byte slice of key within buf. If there
  288. // are tags, they will be sorted if they are not already.
  289. func scanKey(buf []byte, i int) (int, []byte, error) {
  290. start := skipWhitespace(buf, i)
  291. i = start
  292. // Determines whether the tags are sort, assume they are
  293. sorted := true
  294. // indices holds the indexes within buf of the start of each tag. For example,
  295. // a buf of 'cpu,host=a,region=b,zone=c' would have indices slice of [4,11,20]
  296. // which indicates that the first tag starts at buf[4], seconds at buf[11], and
  297. // last at buf[20]
  298. indices := make([]int, 100)
  299. // tracks how many commas we've seen so we know how many values are indices.
  300. // Since indices is an arbitrarily large slice,
  301. // we need to know how many values in the buffer are in use.
  302. commas := 0
  303. // First scan the Point's measurement.
  304. state, i, err := scanMeasurement(buf, i)
  305. if err != nil {
  306. return i, buf[start:i], err
  307. }
  308. // Optionally scan tags if needed.
  309. if state == tagKeyState {
  310. i, commas, indices, err = scanTags(buf, i, indices)
  311. if err != nil {
  312. return i, buf[start:i], err
  313. }
  314. }
  315. // Now we know where the key region is within buf, and the location of tags, we
  316. // need to determine if duplicate tags exist and if the tags are sorted. This iterates
  317. // over the list comparing each tag in the sequence with each other.
  318. for j := 0; j < commas-1; j++ {
  319. // get the left and right tags
  320. _, left := scanTo(buf[indices[j]:indices[j+1]-1], 0, '=')
  321. _, right := scanTo(buf[indices[j+1]:indices[j+2]-1], 0, '=')
  322. // If left is greater than right, the tags are not sorted. We do not have to
  323. // continue because the short path no longer works.
  324. // If the tags are equal, then there are duplicate tags, and we should abort.
  325. // If the tags are not sorted, this pass may not find duplicate tags and we
  326. // need to do a more exhaustive search later.
  327. if cmp := bytes.Compare(left, right); cmp > 0 {
  328. sorted = false
  329. break
  330. } else if cmp == 0 {
  331. return i, buf[start:i], fmt.Errorf("duplicate tags")
  332. }
  333. }
  334. // If the tags are not sorted, then sort them. This sort is inline and
  335. // uses the tag indices we created earlier. The actual buffer is not sorted, the
  336. // indices are using the buffer for value comparison. After the indices are sorted,
  337. // the buffer is reconstructed from the sorted indices.
  338. if !sorted && commas > 0 {
  339. // Get the measurement name for later
  340. measurement := buf[start : indices[0]-1]
  341. // Sort the indices
  342. indices := indices[:commas]
  343. insertionSort(0, commas, buf, indices)
  344. // Create a new key using the measurement and sorted indices
  345. b := make([]byte, len(buf[start:i]))
  346. pos := copy(b, measurement)
  347. for _, i := range indices {
  348. b[pos] = ','
  349. pos++
  350. _, v := scanToSpaceOr(buf, i, ',')
  351. pos += copy(b[pos:], v)
  352. }
  353. // Check again for duplicate tags now that the tags are sorted.
  354. for j := 0; j < commas-1; j++ {
  355. // get the left and right tags
  356. _, left := scanTo(buf[indices[j]:], 0, '=')
  357. _, right := scanTo(buf[indices[j+1]:], 0, '=')
  358. // If the tags are equal, then there are duplicate tags, and we should abort.
  359. // If the tags are not sorted, this pass may not find duplicate tags and we
  360. // need to do a more exhaustive search later.
  361. if bytes.Equal(left, right) {
  362. return i, b, fmt.Errorf("duplicate tags")
  363. }
  364. }
  365. return i, b, nil
  366. }
  367. return i, buf[start:i], nil
  368. }
  369. // The following constants allow us to specify which state to move to
  370. // next, when scanning sections of a Point.
  371. const (
  372. tagKeyState = iota
  373. tagValueState
  374. fieldsState
  375. )
  376. // scanMeasurement examines the measurement part of a Point, returning
  377. // the next state to move to, and the current location in the buffer.
  378. func scanMeasurement(buf []byte, i int) (int, int, error) {
  379. // Check first byte of measurement, anything except a comma is fine.
  380. // It can't be a space, since whitespace is stripped prior to this
  381. // function call.
  382. if i >= len(buf) || buf[i] == ',' {
  383. return -1, i, fmt.Errorf("missing measurement")
  384. }
  385. for {
  386. i++
  387. if i >= len(buf) {
  388. // cpu
  389. return -1, i, fmt.Errorf("missing fields")
  390. }
  391. if buf[i-1] == '\\' {
  392. // Skip character (it's escaped).
  393. continue
  394. }
  395. // Unescaped comma; move onto scanning the tags.
  396. if buf[i] == ',' {
  397. return tagKeyState, i + 1, nil
  398. }
  399. // Unescaped space; move onto scanning the fields.
  400. if buf[i] == ' ' {
  401. // cpu value=1.0
  402. return fieldsState, i, nil
  403. }
  404. }
  405. }
  406. // scanTags examines all the tags in a Point, keeping track of and
  407. // returning the updated indices slice, number of commas and location
  408. // in buf where to start examining the Point fields.
  409. func scanTags(buf []byte, i int, indices []int) (int, int, []int, error) {
  410. var (
  411. err error
  412. commas int
  413. state = tagKeyState
  414. )
  415. for {
  416. switch state {
  417. case tagKeyState:
  418. // Grow our indices slice if we have too many tags.
  419. if commas >= len(indices) {
  420. newIndics := make([]int, cap(indices)*2)
  421. copy(newIndics, indices)
  422. indices = newIndics
  423. }
  424. indices[commas] = i
  425. commas++
  426. i, err = scanTagsKey(buf, i)
  427. state = tagValueState // tag value always follows a tag key
  428. case tagValueState:
  429. state, i, err = scanTagsValue(buf, i)
  430. case fieldsState:
  431. indices[commas] = i + 1
  432. return i, commas, indices, nil
  433. }
  434. if err != nil {
  435. return i, commas, indices, err
  436. }
  437. }
  438. }
  439. // scanTagsKey scans each character in a tag key.
  440. func scanTagsKey(buf []byte, i int) (int, error) {
  441. // First character of the key.
  442. if i >= len(buf) || buf[i] == ' ' || buf[i] == ',' || buf[i] == '=' {
  443. // cpu,{'', ' ', ',', '='}
  444. return i, fmt.Errorf("missing tag key")
  445. }
  446. // Examine each character in the tag key until we hit an unescaped
  447. // equals (the tag value), or we hit an error (i.e., unescaped
  448. // space or comma).
  449. for {
  450. i++
  451. // Either we reached the end of the buffer or we hit an
  452. // unescaped comma or space.
  453. if i >= len(buf) ||
  454. ((buf[i] == ' ' || buf[i] == ',') && buf[i-1] != '\\') {
  455. // cpu,tag{'', ' ', ','}
  456. return i, fmt.Errorf("missing tag value")
  457. }
  458. if buf[i] == '=' && buf[i-1] != '\\' {
  459. // cpu,tag=
  460. return i + 1, nil
  461. }
  462. }
  463. }
  464. // scanTagsValue scans each character in a tag value.
  465. func scanTagsValue(buf []byte, i int) (int, int, error) {
  466. // Tag value cannot be empty.
  467. if i >= len(buf) || buf[i] == ',' || buf[i] == ' ' {
  468. // cpu,tag={',', ' '}
  469. return -1, i, fmt.Errorf("missing tag value")
  470. }
  471. // Examine each character in the tag value until we hit an unescaped
  472. // comma (move onto next tag key), an unescaped space (move onto
  473. // fields), or we error out.
  474. for {
  475. i++
  476. if i >= len(buf) {
  477. // cpu,tag=value
  478. return -1, i, fmt.Errorf("missing fields")
  479. }
  480. // An unescaped equals sign is an invalid tag value.
  481. if buf[i] == '=' && buf[i-1] != '\\' {
  482. // cpu,tag={'=', 'fo=o'}
  483. return -1, i, fmt.Errorf("invalid tag format")
  484. }
  485. if buf[i] == ',' && buf[i-1] != '\\' {
  486. // cpu,tag=foo,
  487. return tagKeyState, i + 1, nil
  488. }
  489. // cpu,tag=foo value=1.0
  490. // cpu, tag=foo\= value=1.0
  491. if buf[i] == ' ' && buf[i-1] != '\\' {
  492. return fieldsState, i, nil
  493. }
  494. }
  495. }
  496. func insertionSort(l, r int, buf []byte, indices []int) {
  497. for i := l + 1; i < r; i++ {
  498. for j := i; j > l && less(buf, indices, j, j-1); j-- {
  499. indices[j], indices[j-1] = indices[j-1], indices[j]
  500. }
  501. }
  502. }
  503. func less(buf []byte, indices []int, i, j int) bool {
  504. // This grabs the tag names for i & j, it ignores the values
  505. _, a := scanTo(buf, indices[i], '=')
  506. _, b := scanTo(buf, indices[j], '=')
  507. return bytes.Compare(a, b) < 0
  508. }
  509. // scanFields scans buf, starting at i for the fields section of a point. It returns
  510. // the ending position and the byte slice of the fields within buf
  511. func scanFields(buf []byte, i int) (int, []byte, error) {
  512. start := skipWhitespace(buf, i)
  513. i = start
  514. quoted := false
  515. // tracks how many '=' we've seen
  516. equals := 0
  517. // tracks how many commas we've seen
  518. commas := 0
  519. for {
  520. // reached the end of buf?
  521. if i >= len(buf) {
  522. break
  523. }
  524. // escaped characters?
  525. if buf[i] == '\\' && i+1 < len(buf) {
  526. i += 2
  527. continue
  528. }
  529. // If the value is quoted, scan until we get to the end quote
  530. // Only quote values in the field value since quotes are not significant
  531. // in the field key
  532. if buf[i] == '"' && equals > commas {
  533. quoted = !quoted
  534. i++
  535. continue
  536. }
  537. // If we see an =, ensure that there is at least on char before and after it
  538. if buf[i] == '=' && !quoted {
  539. equals++
  540. // check for "... =123" but allow "a\ =123"
  541. if buf[i-1] == ' ' && buf[i-2] != '\\' {
  542. return i, buf[start:i], fmt.Errorf("missing field key")
  543. }
  544. // check for "...a=123,=456" but allow "a=123,a\,=456"
  545. if buf[i-1] == ',' && buf[i-2] != '\\' {
  546. return i, buf[start:i], fmt.Errorf("missing field key")
  547. }
  548. // check for "... value="
  549. if i+1 >= len(buf) {
  550. return i, buf[start:i], fmt.Errorf("missing field value")
  551. }
  552. // check for "... value=,value2=..."
  553. if buf[i+1] == ',' || buf[i+1] == ' ' {
  554. return i, buf[start:i], fmt.Errorf("missing field value")
  555. }
  556. if isNumeric(buf[i+1]) || buf[i+1] == '-' || buf[i+1] == 'N' || buf[i+1] == 'n' {
  557. var err error
  558. i, err = scanNumber(buf, i+1)
  559. if err != nil {
  560. return i, buf[start:i], err
  561. }
  562. continue
  563. }
  564. // If next byte is not a double-quote, the value must be a boolean
  565. if buf[i+1] != '"' {
  566. var err error
  567. i, _, err = scanBoolean(buf, i+1)
  568. if err != nil {
  569. return i, buf[start:i], err
  570. }
  571. continue
  572. }
  573. }
  574. if buf[i] == ',' && !quoted {
  575. commas++
  576. }
  577. // reached end of block?
  578. if buf[i] == ' ' && !quoted {
  579. break
  580. }
  581. i++
  582. }
  583. if quoted {
  584. return i, buf[start:i], fmt.Errorf("unbalanced quotes")
  585. }
  586. // check that all field sections had key and values (e.g. prevent "a=1,b"
  587. if equals == 0 || commas != equals-1 {
  588. return i, buf[start:i], fmt.Errorf("invalid field format")
  589. }
  590. return i, buf[start:i], nil
  591. }
  592. // scanTime scans buf, starting at i for the time section of a point. It
  593. // returns the ending position and the byte slice of the timestamp within buf
  594. // and and error if the timestamp is not in the correct numeric format.
  595. func scanTime(buf []byte, i int) (int, []byte, error) {
  596. start := skipWhitespace(buf, i)
  597. i = start
  598. for {
  599. // reached the end of buf?
  600. if i >= len(buf) {
  601. break
  602. }
  603. // Reached end of block or trailing whitespace?
  604. if buf[i] == '\n' || buf[i] == ' ' {
  605. break
  606. }
  607. // Handle negative timestamps
  608. if i == start && buf[i] == '-' {
  609. i++
  610. continue
  611. }
  612. // Timestamps should be integers, make sure they are so we don't need
  613. // to actually parse the timestamp until needed.
  614. if buf[i] < '0' || buf[i] > '9' {
  615. return i, buf[start:i], fmt.Errorf("bad timestamp")
  616. }
  617. i++
  618. }
  619. return i, buf[start:i], nil
  620. }
  621. func isNumeric(b byte) bool {
  622. return (b >= '0' && b <= '9') || b == '.'
  623. }
  624. // scanNumber returns the end position within buf, start at i after
  625. // scanning over buf for an integer, or float. It returns an
  626. // error if a invalid number is scanned.
  627. func scanNumber(buf []byte, i int) (int, error) {
  628. start := i
  629. var isInt bool
  630. // Is negative number?
  631. if i < len(buf) && buf[i] == '-' {
  632. i++
  633. // There must be more characters now, as just '-' is illegal.
  634. if i == len(buf) {
  635. return i, ErrInvalidNumber
  636. }
  637. }
  638. // how many decimal points we've see
  639. decimal := false
  640. // indicates the number is float in scientific notation
  641. scientific := false
  642. for {
  643. if i >= len(buf) {
  644. break
  645. }
  646. if buf[i] == ',' || buf[i] == ' ' {
  647. break
  648. }
  649. if buf[i] == 'i' && i > start && !isInt {
  650. isInt = true
  651. i++
  652. continue
  653. }
  654. if buf[i] == '.' {
  655. // Can't have more than 1 decimal (e.g. 1.1.1 should fail)
  656. if decimal {
  657. return i, ErrInvalidNumber
  658. }
  659. decimal = true
  660. }
  661. // `e` is valid for floats but not as the first char
  662. if i > start && (buf[i] == 'e' || buf[i] == 'E') {
  663. scientific = true
  664. i++
  665. continue
  666. }
  667. // + and - are only valid at this point if they follow an e (scientific notation)
  668. if (buf[i] == '+' || buf[i] == '-') && (buf[i-1] == 'e' || buf[i-1] == 'E') {
  669. i++
  670. continue
  671. }
  672. // NaN is an unsupported value
  673. if i+2 < len(buf) && (buf[i] == 'N' || buf[i] == 'n') {
  674. return i, ErrInvalidNumber
  675. }
  676. if !isNumeric(buf[i]) {
  677. return i, ErrInvalidNumber
  678. }
  679. i++
  680. }
  681. if isInt && (decimal || scientific) {
  682. return i, ErrInvalidNumber
  683. }
  684. numericDigits := i - start
  685. if isInt {
  686. numericDigits--
  687. }
  688. if decimal {
  689. numericDigits--
  690. }
  691. if buf[start] == '-' {
  692. numericDigits--
  693. }
  694. if numericDigits == 0 {
  695. return i, ErrInvalidNumber
  696. }
  697. // It's more common that numbers will be within min/max range for their type but we need to prevent
  698. // out or range numbers from being parsed successfully. This uses some simple heuristics to decide
  699. // if we should parse the number to the actual type. It does not do it all the time because it incurs
  700. // extra allocations and we end up converting the type again when writing points to disk.
  701. if isInt {
  702. // Make sure the last char is an 'i' for integers (e.g. 9i10 is not valid)
  703. if buf[i-1] != 'i' {
  704. return i, ErrInvalidNumber
  705. }
  706. // Parse the int to check bounds the number of digits could be larger than the max range
  707. // We subtract 1 from the index to remove the `i` from our tests
  708. if len(buf[start:i-1]) >= maxInt64Digits || len(buf[start:i-1]) >= minInt64Digits {
  709. if _, err := parseIntBytes(buf[start:i-1], 10, 64); err != nil {
  710. return i, fmt.Errorf("unable to parse integer %s: %s", buf[start:i-1], err)
  711. }
  712. }
  713. } else {
  714. // Parse the float to check bounds if it's scientific or the number of digits could be larger than the max range
  715. if scientific || len(buf[start:i]) >= maxFloat64Digits || len(buf[start:i]) >= minFloat64Digits {
  716. if _, err := parseFloatBytes(buf[start:i], 10); err != nil {
  717. return i, fmt.Errorf("invalid float")
  718. }
  719. }
  720. }
  721. return i, nil
  722. }
  723. // scanBoolean returns the end position within buf, start at i after
  724. // scanning over buf for boolean. Valid values for a boolean are
  725. // t, T, true, TRUE, f, F, false, FALSE. It returns an error if a invalid boolean
  726. // is scanned.
  727. func scanBoolean(buf []byte, i int) (int, []byte, error) {
  728. start := i
  729. if i < len(buf) && (buf[i] != 't' && buf[i] != 'f' && buf[i] != 'T' && buf[i] != 'F') {
  730. return i, buf[start:i], fmt.Errorf("invalid boolean")
  731. }
  732. i++
  733. for {
  734. if i >= len(buf) {
  735. break
  736. }
  737. if buf[i] == ',' || buf[i] == ' ' {
  738. break
  739. }
  740. i++
  741. }
  742. // Single char bool (t, T, f, F) is ok
  743. if i-start == 1 {
  744. return i, buf[start:i], nil
  745. }
  746. // length must be 4 for true or TRUE
  747. if (buf[start] == 't' || buf[start] == 'T') && i-start != 4 {
  748. return i, buf[start:i], fmt.Errorf("invalid boolean")
  749. }
  750. // length must be 5 for false or FALSE
  751. if (buf[start] == 'f' || buf[start] == 'F') && i-start != 5 {
  752. return i, buf[start:i], fmt.Errorf("invalid boolean")
  753. }
  754. // Otherwise
  755. valid := false
  756. switch buf[start] {
  757. case 't':
  758. valid = bytes.Equal(buf[start:i], []byte("true"))
  759. case 'f':
  760. valid = bytes.Equal(buf[start:i], []byte("false"))
  761. case 'T':
  762. valid = bytes.Equal(buf[start:i], []byte("TRUE")) || bytes.Equal(buf[start:i], []byte("True"))
  763. case 'F':
  764. valid = bytes.Equal(buf[start:i], []byte("FALSE")) || bytes.Equal(buf[start:i], []byte("False"))
  765. }
  766. if !valid {
  767. return i, buf[start:i], fmt.Errorf("invalid boolean")
  768. }
  769. return i, buf[start:i], nil
  770. }
  771. // skipWhitespace returns the end position within buf, starting at i after
  772. // scanning over spaces in tags
  773. func skipWhitespace(buf []byte, i int) int {
  774. for i < len(buf) {
  775. if buf[i] != ' ' && buf[i] != '\t' && buf[i] != 0 {
  776. break
  777. }
  778. i++
  779. }
  780. return i
  781. }
  782. // scanLine returns the end position in buf and the next line found within
  783. // buf.
  784. func scanLine(buf []byte, i int) (int, []byte) {
  785. start := i
  786. quoted := false
  787. fields := false
  788. // tracks how many '=' and commas we've seen
  789. // this duplicates some of the functionality in scanFields
  790. equals := 0
  791. commas := 0
  792. for {
  793. // reached the end of buf?
  794. if i >= len(buf) {
  795. break
  796. }
  797. // skip past escaped characters
  798. if buf[i] == '\\' {
  799. i += 2
  800. continue
  801. }
  802. if buf[i] == ' ' {
  803. fields = true
  804. }
  805. // If we see a double quote, makes sure it is not escaped
  806. if fields {
  807. if !quoted && buf[i] == '=' {
  808. i++
  809. equals++
  810. continue
  811. } else if !quoted && buf[i] == ',' {
  812. i++
  813. commas++
  814. continue
  815. } else if buf[i] == '"' && equals > commas {
  816. i++
  817. quoted = !quoted
  818. continue
  819. }
  820. }
  821. if buf[i] == '\n' && !quoted {
  822. break
  823. }
  824. i++
  825. }
  826. return i, buf[start:i]
  827. }
  828. // scanTo returns the end position in buf and the next consecutive block
  829. // of bytes, starting from i and ending with stop byte, where stop byte
  830. // has not been escaped.
  831. //
  832. // If there are leading spaces, they are skipped.
  833. func scanTo(buf []byte, i int, stop byte) (int, []byte) {
  834. start := i
  835. for {
  836. // reached the end of buf?
  837. if i >= len(buf) {
  838. break
  839. }
  840. // Reached unescaped stop value?
  841. if buf[i] == stop && (i == 0 || buf[i-1] != '\\') {
  842. break
  843. }
  844. i++
  845. }
  846. return i, buf[start:i]
  847. }
  848. // scanTo returns the end position in buf and the next consecutive block
  849. // of bytes, starting from i and ending with stop byte. If there are leading
  850. // spaces, they are skipped.
  851. func scanToSpaceOr(buf []byte, i int, stop byte) (int, []byte) {
  852. start := i
  853. if buf[i] == stop || buf[i] == ' ' {
  854. return i, buf[start:i]
  855. }
  856. for {
  857. i++
  858. if buf[i-1] == '\\' {
  859. continue
  860. }
  861. // reached the end of buf?
  862. if i >= len(buf) {
  863. return i, buf[start:i]
  864. }
  865. // reached end of block?
  866. if buf[i] == stop || buf[i] == ' ' {
  867. return i, buf[start:i]
  868. }
  869. }
  870. }
  871. func scanTagValue(buf []byte, i int) (int, []byte) {
  872. start := i
  873. for {
  874. if i >= len(buf) {
  875. break
  876. }
  877. if buf[i] == ',' && buf[i-1] != '\\' {
  878. break
  879. }
  880. i++
  881. }
  882. return i, buf[start:i]
  883. }
  884. func scanFieldValue(buf []byte, i int) (int, []byte) {
  885. start := i
  886. quoted := false
  887. for i < len(buf) {
  888. // Only escape char for a field value is a double-quote and backslash
  889. if buf[i] == '\\' && i+1 < len(buf) && (buf[i+1] == '"' || buf[i+1] == '\\') {
  890. i += 2
  891. continue
  892. }
  893. // Quoted value? (e.g. string)
  894. if buf[i] == '"' {
  895. i++
  896. quoted = !quoted
  897. continue
  898. }
  899. if buf[i] == ',' && !quoted {
  900. break
  901. }
  902. i++
  903. }
  904. return i, buf[start:i]
  905. }
  906. func escapeMeasurement(in []byte) []byte {
  907. for b, esc := range measurementEscapeCodes {
  908. in = bytes.Replace(in, []byte{b}, esc, -1)
  909. }
  910. return in
  911. }
  912. func unescapeMeasurement(in []byte) []byte {
  913. for b, esc := range measurementEscapeCodes {
  914. in = bytes.Replace(in, esc, []byte{b}, -1)
  915. }
  916. return in
  917. }
  918. func escapeTag(in []byte) []byte {
  919. for b, esc := range tagEscapeCodes {
  920. if bytes.IndexByte(in, b) != -1 {
  921. in = bytes.Replace(in, []byte{b}, esc, -1)
  922. }
  923. }
  924. return in
  925. }
  926. func unescapeTag(in []byte) []byte {
  927. if bytes.IndexByte(in, '\\') == -1 {
  928. return in
  929. }
  930. for b, esc := range tagEscapeCodes {
  931. if bytes.IndexByte(in, b) != -1 {
  932. in = bytes.Replace(in, esc, []byte{b}, -1)
  933. }
  934. }
  935. return in
  936. }
  937. // EscapeStringField returns a copy of in with any double quotes or
  938. // backslashes with escaped values
  939. func EscapeStringField(in string) string {
  940. var out []byte
  941. i := 0
  942. for {
  943. if i >= len(in) {
  944. break
  945. }
  946. // escape double-quotes
  947. if in[i] == '\\' {
  948. out = append(out, '\\')
  949. out = append(out, '\\')
  950. i++
  951. continue
  952. }
  953. // escape double-quotes
  954. if in[i] == '"' {
  955. out = append(out, '\\')
  956. out = append(out, '"')
  957. i++
  958. continue
  959. }
  960. out = append(out, in[i])
  961. i++
  962. }
  963. return string(out)
  964. }
  965. // unescapeStringField returns a copy of in with any escaped double-quotes
  966. // or backslashes unescaped
  967. func unescapeStringField(in string) string {
  968. if strings.IndexByte(in, '\\') == -1 {
  969. return in
  970. }
  971. var out []byte
  972. i := 0
  973. for {
  974. if i >= len(in) {
  975. break
  976. }
  977. // unescape backslashes
  978. if in[i] == '\\' && i+1 < len(in) && in[i+1] == '\\' {
  979. out = append(out, '\\')
  980. i += 2
  981. continue
  982. }
  983. // unescape double-quotes
  984. if in[i] == '\\' && i+1 < len(in) && in[i+1] == '"' {
  985. out = append(out, '"')
  986. i += 2
  987. continue
  988. }
  989. out = append(out, in[i])
  990. i++
  991. }
  992. return string(out)
  993. }
  994. // NewPoint returns a new point with the given measurement name, tags, fields and timestamp. If
  995. // an unsupported field value (NaN) or out of range time is passed, this function returns an error.
  996. func NewPoint(name string, tags Tags, fields Fields, t time.Time) (Point, error) {
  997. key, err := pointKey(name, tags, fields, t)
  998. if err != nil {
  999. return nil, err
  1000. }
  1001. return &point{
  1002. key: key,
  1003. time: t,
  1004. fields: fields.MarshalBinary(),
  1005. }, nil
  1006. }
  1007. // pointKey checks some basic requirements for valid points, and returns the
  1008. // key, along with an possible error
  1009. func pointKey(measurement string, tags Tags, fields Fields, t time.Time) ([]byte, error) {
  1010. if len(fields) == 0 {
  1011. return nil, ErrPointMustHaveAField
  1012. }
  1013. if !t.IsZero() {
  1014. if err := CheckTime(t); err != nil {
  1015. return nil, err
  1016. }
  1017. }
  1018. for key, value := range fields {
  1019. switch value := value.(type) {
  1020. case float64:
  1021. // Ensure the caller validates and handles invalid field values
  1022. if math.IsNaN(value) {
  1023. return nil, fmt.Errorf("NaN is an unsupported value for field %s", key)
  1024. }
  1025. case float32:
  1026. // Ensure the caller validates and handles invalid field values
  1027. if math.IsNaN(float64(value)) {
  1028. return nil, fmt.Errorf("NaN is an unsupported value for field %s", key)
  1029. }
  1030. }
  1031. if len(key) == 0 {
  1032. return nil, fmt.Errorf("all fields must have non-empty names")
  1033. }
  1034. }
  1035. key := MakeKey([]byte(measurement), tags)
  1036. if len(key) > MaxKeyLength {
  1037. return nil, fmt.Errorf("max key length exceeded: %v > %v", len(key), MaxKeyLength)
  1038. }
  1039. return key, nil
  1040. }
  1041. // NewPointFromBytes returns a new Point from a marshalled Point.
  1042. func NewPointFromBytes(b []byte) (Point, error) {
  1043. p := &point{}
  1044. if err := p.UnmarshalBinary(b); err != nil {
  1045. return nil, err
  1046. }
  1047. if len(p.Fields()) == 0 {
  1048. return nil, ErrPointMustHaveAField
  1049. }
  1050. return p, nil
  1051. }
  1052. // MustNewPoint returns a new point with the given measurement name, tags, fields and timestamp. If
  1053. // an unsupported field value (NaN) is passed, this function panics.
  1054. func MustNewPoint(name string, tags Tags, fields Fields, time time.Time) Point {
  1055. pt, err := NewPoint(name, tags, fields, time)
  1056. if err != nil {
  1057. panic(err.Error())
  1058. }
  1059. return pt
  1060. }
  1061. func (p *point) Data() []byte {
  1062. return p.data
  1063. }
  1064. func (p *point) SetData(b []byte) {
  1065. p.data = b
  1066. }
  1067. func (p *point) Key() []byte {
  1068. return p.key
  1069. }
  1070. func (p *point) name() []byte {
  1071. _, name := scanTo(p.key, 0, ',')
  1072. return name
  1073. }
  1074. // Name return the measurement name for the point
  1075. func (p *point) Name() string {
  1076. if p.cachedName != "" {
  1077. return p.cachedName
  1078. }
  1079. p.cachedName = string(Unescape(p.name()))
  1080. return p.cachedName
  1081. }
  1082. // SetName updates the measurement name for the point
  1083. func (p *point) SetName(name string) {
  1084. p.cachedName = ""
  1085. p.key = MakeKey([]byte(name), p.Tags())
  1086. }
  1087. // Time return the timestamp for the point
  1088. func (p *point) Time() time.Time {
  1089. return p.time
  1090. }
  1091. // SetTime updates the timestamp for the point
  1092. func (p *point) SetTime(t time.Time) {
  1093. p.time = t
  1094. }
  1095. // Round implements Point.Round
  1096. func (p *point) Round(d time.Duration) {
  1097. p.time = p.time.Round(d)
  1098. }
  1099. // Tags returns the tag set for the point
  1100. func (p *point) Tags() Tags {
  1101. if p.cachedTags != nil {
  1102. return p.cachedTags
  1103. }
  1104. p.cachedTags = parseTags(p.key)
  1105. return p.cachedTags
  1106. }
  1107. func parseTags(buf []byte) Tags {
  1108. if len(buf) == 0 {
  1109. return nil
  1110. }
  1111. pos, name := scanTo(buf, 0, ',')
  1112. // it's an empty key, so there are no tags
  1113. if len(name) == 0 {
  1114. return nil
  1115. }
  1116. tags := make(Tags, 0, bytes.Count(buf, []byte(",")))
  1117. hasEscape := bytes.IndexByte(buf, '\\') != -1
  1118. i := pos + 1
  1119. var key, value []byte
  1120. for {
  1121. if i >= len(buf) {
  1122. break
  1123. }
  1124. i, key = scanTo(buf, i, '=')
  1125. i, value = scanTagValue(buf, i+1)
  1126. if len(value) == 0 {
  1127. continue
  1128. }
  1129. if hasEscape {
  1130. tags = append(tags, Tag{Key: unescapeTag(key), Value: unescapeTag(value)})
  1131. } else {
  1132. tags = append(tags, Tag{Key: key, Value: value})
  1133. }
  1134. i++
  1135. }
  1136. return tags
  1137. }
  1138. // MakeKey creates a key for a set of tags.
  1139. func MakeKey(name []byte, tags Tags) []byte {
  1140. // unescape the name and then re-escape it to avoid double escaping.
  1141. // The key should always be stored in escaped form.
  1142. return append(escapeMeasurement(unescapeMeasurement(name)), tags.HashKey()...)
  1143. }
  1144. // SetTags replaces the tags for the point
  1145. func (p *point) SetTags(tags Tags) {
  1146. p.key = MakeKey([]byte(p.Name()), tags)
  1147. p.cachedTags = tags
  1148. }
  1149. // AddTag adds or replaces a tag value for a point
  1150. func (p *point) AddTag(key, value string) {
  1151. tags := p.Tags()
  1152. tags = append(tags, Tag{Key: []byte(key), Value: []byte(value)})
  1153. sort.Sort(tags)
  1154. p.cachedTags = tags
  1155. p.key = MakeKey([]byte(p.Name()), tags)
  1156. }
  1157. // Fields returns the fields for the point
  1158. func (p *point) Fields() Fields {
  1159. if p.cachedFields != nil {
  1160. return p.cachedFields
  1161. }
  1162. p.cachedFields = p.unmarshalBinary()
  1163. return p.cachedFields
  1164. }
  1165. // SetPrecision will round a time to the specified precision
  1166. func (p *point) SetPrecision(precision string) {
  1167. switch precision {
  1168. case "n":
  1169. case "u":
  1170. p.SetTime(p.Time().Truncate(time.Microsecond))
  1171. case "ms":
  1172. p.SetTime(p.Time().Truncate(time.Millisecond))
  1173. case "s":
  1174. p.SetTime(p.Time().Truncate(time.Second))
  1175. case "m":
  1176. p.SetTime(p.Time().Truncate(time.Minute))
  1177. case "h":
  1178. p.SetTime(p.Time().Truncate(time.Hour))
  1179. }
  1180. }
  1181. func (p *point) String() string {
  1182. if p.Time().IsZero() {
  1183. return string(p.Key()) + " " + string(p.fields)
  1184. }
  1185. return string(p.Key()) + " " + string(p.fields) + " " + strconv.FormatInt(p.UnixNano(), 10)
  1186. }
  1187. // AppendString implements Point.AppendString
  1188. func (p *point) AppendString(buf []byte) []byte {
  1189. buf = append(buf, p.key...)
  1190. buf = append(buf, ' ')
  1191. buf = append(buf, p.fields...)
  1192. if !p.time.IsZero() {
  1193. buf = append(buf, ' ')
  1194. buf = strconv.AppendInt(buf, p.UnixNano(), 10)
  1195. }
  1196. return buf
  1197. }
  1198. func (p *point) StringSize() int {
  1199. size := len(p.key) + len(p.fields) + 1
  1200. if !p.time.IsZero() {
  1201. digits := 1 // even "0" has one digit
  1202. t := p.UnixNano()
  1203. if t < 0 {
  1204. // account for negative sign, then negate
  1205. digits++
  1206. t = -t
  1207. }
  1208. for t > 9 { // already accounted for one digit
  1209. digits++
  1210. t /= 10
  1211. }
  1212. size += digits + 1 // digits and a space
  1213. }
  1214. return size
  1215. }
  1216. func (p *point) MarshalBinary() ([]byte, error) {
  1217. tb, err := p.time.MarshalBinary()
  1218. if err != nil {
  1219. return nil, err
  1220. }
  1221. b := make([]byte, 8+len(p.key)+len(p.fields)+len(tb))
  1222. i := 0
  1223. binary.BigEndian.PutUint32(b[i:], uint32(len(p.key)))
  1224. i += 4
  1225. i += copy(b[i:], p.key)
  1226. binary.BigEndian.PutUint32(b[i:i+4], uint32(len(p.fields)))
  1227. i += 4
  1228. i += copy(b[i:], p.fields)
  1229. copy(b[i:], tb)
  1230. return b, nil
  1231. }
  1232. func (p *point) UnmarshalBinary(b []byte) error {
  1233. var i int
  1234. keyLen := int(binary.BigEndian.Uint32(b[:4]))
  1235. i += int(4)
  1236. p.key = b[i : i+keyLen]
  1237. i += keyLen
  1238. fieldLen := int(binary.BigEndian.Uint32(b[i : i+4]))
  1239. i += int(4)
  1240. p.fields = b[i : i+fieldLen]
  1241. i += fieldLen
  1242. p.time = time.Now()
  1243. p.time.UnmarshalBinary(b[i:])
  1244. return nil
  1245. }
  1246. func (p *point) PrecisionString(precision string) string {
  1247. if p.Time().IsZero() {
  1248. return fmt.Sprintf("%s %s", p.Key(), string(p.fields))
  1249. }
  1250. return fmt.Sprintf("%s %s %d", p.Key(), string(p.fields),
  1251. p.UnixNano()/GetPrecisionMultiplier(precision))
  1252. }
  1253. func (p *point) RoundedString(d time.Duration) string {
  1254. if p.Time().IsZero() {
  1255. return fmt.Sprintf("%s %s", p.Key(), string(p.fields))
  1256. }
  1257. return fmt.Sprintf("%s %s %d", p.Key(), string(p.fields),
  1258. p.time.Round(d).UnixNano())
  1259. }
  1260. func (p *point) unmarshalBinary() Fields {
  1261. iter := p.FieldIterator()
  1262. fields := make(Fields, 8)
  1263. for iter.Next() {
  1264. if len(iter.FieldKey()) == 0 {
  1265. continue
  1266. }
  1267. switch iter.Type() {
  1268. case Float:
  1269. fields[string(iter.FieldKey())] = iter.FloatValue()
  1270. case Integer:
  1271. fields[string(iter.FieldKey())] = iter.IntegerValue()
  1272. case String:
  1273. fields[string(iter.FieldKey())] = iter.StringValue()
  1274. case Boolean:
  1275. fields[string(iter.FieldKey())] = iter.BooleanValue()
  1276. }
  1277. }
  1278. return fields
  1279. }
  1280. func (p *point) UnixNano() int64 {
  1281. return p.Time().UnixNano()
  1282. }
  1283. func (p *point) Split(size int) []Point {
  1284. if p.time.IsZero() || len(p.String()) <= size {
  1285. return []Point{p}
  1286. }
  1287. // key string, timestamp string, spaces
  1288. size -= len(p.key) + len(strconv.FormatInt(p.time.UnixNano(), 10)) + 2
  1289. var points []Point
  1290. var start, cur int
  1291. for cur < len(p.fields) {
  1292. end, _ := scanTo(p.fields, cur, '=')
  1293. end, _ = scanFieldValue(p.fields, end+1)
  1294. if cur > start && end-start > size {
  1295. points = append(points, &point{
  1296. key: p.key,
  1297. time: p.time,
  1298. fields: p.fields[start : cur-1],
  1299. })
  1300. start = cur
  1301. }
  1302. cur = end + 1
  1303. }
  1304. points = append(points, &point{
  1305. key: p.key,
  1306. time: p.time,
  1307. fields: p.fields[start:],
  1308. })
  1309. return points
  1310. }
  1311. // Tag represents a single key/value tag pair.
  1312. type Tag struct {
  1313. Key []byte
  1314. Value []byte
  1315. }
  1316. // Clone returns a shallow copy of Tag.
  1317. //
  1318. // Tags associated with a Point created by ParsePointsWithPrecision will hold references to the byte slice that was parsed.
  1319. // Use Clone to create a Tag with new byte slices that do not refer to the argument to ParsePointsWithPrecision.
  1320. func (t Tag) Clone() Tag {
  1321. other := Tag{
  1322. Key: make([]byte, len(t.Key)),
  1323. Value: make([]byte, len(t.Value)),
  1324. }
  1325. copy(other.Key, t.Key)
  1326. copy(other.Value, t.Value)
  1327. return other
  1328. }
  1329. // Tags represents a sorted list of tags.
  1330. type Tags []Tag
  1331. // NewTags returns a new Tags from a map.
  1332. func NewTags(m map[string]string) Tags {
  1333. if len(m) == 0 {
  1334. return nil
  1335. }
  1336. a := make(Tags, 0, len(m))
  1337. for k, v := range m {
  1338. a = append(a, Tag{Key: []byte(k), Value: []byte(v)})
  1339. }
  1340. sort.Sort(a)
  1341. return a
  1342. }
  1343. // Clone returns a copy of the slice where the elements are a result of calling `Clone` on the original elements
  1344. //
  1345. // Tags associated with a Point created by ParsePointsWithPrecision will hold references to the byte slice that was parsed.
  1346. // Use Clone to create Tags with new byte slices that do not refer to the argument to ParsePointsWithPrecision.
  1347. func (a Tags) Clone() Tags {
  1348. if len(a) == 0 {
  1349. return nil
  1350. }
  1351. others := make(Tags, len(a))
  1352. for i := range a {
  1353. others[i] = a[i].Clone()
  1354. }
  1355. return others
  1356. }
  1357. func (a Tags) Len() int { return len(a) }
  1358. func (a Tags) Less(i, j int) bool { return bytes.Compare(a[i].Key, a[j].Key) == -1 }
  1359. func (a Tags) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1360. // Get returns the value for a key.
  1361. func (a Tags) Get(key []byte) []byte {
  1362. // OPTIMIZE: Use sort.Search if tagset is large.
  1363. for _, t := range a {
  1364. if bytes.Equal(t.Key, key) {
  1365. return t.Value
  1366. }
  1367. }
  1368. return nil
  1369. }
  1370. // GetString returns the string value for a string key.
  1371. func (a Tags) GetString(key string) string {
  1372. return string(a.Get([]byte(key)))
  1373. }
  1374. // Set sets the value for a key.
  1375. func (a *Tags) Set(key, value []byte) {
  1376. for _, t := range *a {
  1377. if bytes.Equal(t.Key, key) {
  1378. t.Value = value
  1379. return
  1380. }
  1381. }
  1382. *a = append(*a, Tag{Key: key, Value: value})
  1383. sort.Sort(*a)
  1384. }
  1385. // SetString sets the string value for a string key.
  1386. func (a *Tags) SetString(key, value string) {
  1387. a.Set([]byte(key), []byte(value))
  1388. }
  1389. // Delete removes a tag by key.
  1390. func (a *Tags) Delete(key []byte) {
  1391. for i, t := range *a {
  1392. if bytes.Equal(t.Key, key) {
  1393. copy((*a)[i:], (*a)[i+1:])
  1394. (*a)[len(*a)-1] = Tag{}
  1395. *a = (*a)[:len(*a)-1]
  1396. return
  1397. }
  1398. }
  1399. }
  1400. // Map returns a map representation of the tags.
  1401. func (a Tags) Map() map[string]string {
  1402. m := make(map[string]string, len(a))
  1403. for _, t := range a {
  1404. m[string(t.Key)] = string(t.Value)
  1405. }
  1406. return m
  1407. }
  1408. // Merge merges the tags combining the two. If both define a tag with the
  1409. // same key, the merged value overwrites the old value.
  1410. // A new map is returned.
  1411. func (a Tags) Merge(other map[string]string) Tags {
  1412. merged := make(map[string]string, len(a)+len(other))
  1413. for _, t := range a {
  1414. merged[string(t.Key)] = string(t.Value)
  1415. }
  1416. for k, v := range other {
  1417. merged[k] = v
  1418. }
  1419. return NewTags(merged)
  1420. }
  1421. // HashKey hashes all of a tag's keys.
  1422. func (a Tags) HashKey() []byte {
  1423. // Empty maps marshal to empty bytes.
  1424. if len(a) == 0 {
  1425. return nil
  1426. }
  1427. escaped := make(Tags, 0, len(a))
  1428. for _, t := range a {
  1429. ek := escapeTag(t.Key)
  1430. ev := escapeTag(t.Value)
  1431. if len(ev) > 0 {
  1432. escaped = append(escaped, Tag{Key: ek, Value: ev})
  1433. }
  1434. }
  1435. // Extract keys and determine final size.
  1436. sz := len(escaped) + (len(escaped) * 2) // separators
  1437. keys := make([][]byte, len(escaped)+1)
  1438. for i, t := range escaped {
  1439. keys[i] = t.Key
  1440. sz += len(t.Key) + len(t.Value)
  1441. }
  1442. keys = keys[:len(escaped)]
  1443. sort.Sort(byteSlices(keys))
  1444. // Generate marshaled bytes.
  1445. b := make([]byte, sz)
  1446. buf := b
  1447. idx := 0
  1448. for i, k := range keys {
  1449. buf[idx] = ','
  1450. idx++
  1451. copy(buf[idx:idx+len(k)], k)
  1452. idx += len(k)
  1453. buf[idx] = '='
  1454. idx++
  1455. v := escaped[i].Value
  1456. copy(buf[idx:idx+len(v)], v)
  1457. idx += len(v)
  1458. }
  1459. return b[:idx]
  1460. }
  1461. // Fields represents a mapping between a Point's field names and their
  1462. // values.
  1463. type Fields map[string]interface{}
  1464. func parseNumber(val []byte) (interface{}, error) {
  1465. if val[len(val)-1] == 'i' {
  1466. val = val[:len(val)-1]
  1467. return parseIntBytes(val, 10, 64)
  1468. }
  1469. for i := 0; i < len(val); i++ {
  1470. // If there is a decimal or an N (NaN), I (Inf), parse as float
  1471. if val[i] == '.' || val[i] == 'N' || val[i] == 'n' || val[i] == 'I' || val[i] == 'i' || val[i] == 'e' {
  1472. return parseFloatBytes(val, 64)
  1473. }
  1474. if val[i] < '0' && val[i] > '9' {
  1475. return string(val), nil
  1476. }
  1477. }
  1478. return parseFloatBytes(val, 64)
  1479. }
  1480. func (p *point) FieldIterator() FieldIterator {
  1481. p.Reset()
  1482. return p
  1483. }
  1484. type fieldIterator struct {
  1485. start, end int
  1486. key, keybuf []byte
  1487. valueBuf []byte
  1488. fieldType FieldType
  1489. }
  1490. func (p *point) Next() bool {
  1491. p.it.start = p.it.end
  1492. if p.it.start >= len(p.fields) {
  1493. return false
  1494. }
  1495. p.it.end, p.it.key = scanTo(p.fields, p.it.start, '=')
  1496. if IsEscaped(p.it.key) {
  1497. p.it.keybuf = AppendUnescaped(p.it.keybuf[:0], p.it.key)
  1498. p.it.key = p.it.keybuf
  1499. }
  1500. p.it.end, p.it.valueBuf = scanFieldValue(p.fields, p.it.end+1)
  1501. p.it.end++
  1502. if len(p.it.valueBuf) == 0 {
  1503. p.it.fieldType = Empty
  1504. return true
  1505. }
  1506. c := p.it.valueBuf[0]
  1507. if c == '"' {
  1508. p.it.fieldType = String
  1509. return true
  1510. }
  1511. if strings.IndexByte(`0123456789-.nNiI`, c) >= 0 {
  1512. if p.it.valueBuf[len(p.it.valueBuf)-1] == 'i' {
  1513. p.it.fieldType = Integer
  1514. p.it.valueBuf = p.it.valueBuf[:len(p.it.valueBuf)-1]
  1515. } else {
  1516. p.it.fieldType = Float
  1517. }
  1518. return true
  1519. }
  1520. // to keep the same behavior that currently exists, default to boolean
  1521. p.it.fieldType = Boolean
  1522. return true
  1523. }
  1524. func (p *point) FieldKey() []byte {
  1525. return p.it.key
  1526. }
  1527. func (p *point) Type() FieldType {
  1528. return p.it.fieldType
  1529. }
  1530. func (p *point) StringValue() string {
  1531. return unescapeStringField(string(p.it.valueBuf[1 : len(p.it.valueBuf)-1]))
  1532. }
  1533. func (p *point) IntegerValue() int64 {
  1534. n, err := parseIntBytes(p.it.valueBuf, 10, 64)
  1535. if err != nil {
  1536. panic(fmt.Sprintf("unable to parse integer value %q: %v", p.it.valueBuf, err))
  1537. }
  1538. return n
  1539. }
  1540. func (p *point) BooleanValue() bool {
  1541. b, err := parseBoolBytes(p.it.valueBuf)
  1542. if err != nil {
  1543. panic(fmt.Sprintf("unable to parse bool value %q: %v", p.it.valueBuf, err))
  1544. }
  1545. return b
  1546. }
  1547. func (p *point) FloatValue() float64 {
  1548. f, err := parseFloatBytes(p.it.valueBuf, 64)
  1549. if err != nil {
  1550. // panic because that's what the non-iterator code does
  1551. panic(fmt.Sprintf("unable to parse floating point value %q: %v", p.it.valueBuf, err))
  1552. }
  1553. return f
  1554. }
  1555. func (p *point) Delete() {
  1556. switch {
  1557. case p.it.end == p.it.start:
  1558. case p.it.end >= len(p.fields):
  1559. p.fields = p.fields[:p.it.start]
  1560. case p.it.start == 0:
  1561. p.fields = p.fields[p.it.end:]
  1562. default:
  1563. p.fields = append(p.fields[:p.it.start], p.fields[p.it.end:]...)
  1564. }
  1565. p.it.end = p.it.start
  1566. p.it.key = nil
  1567. p.it.valueBuf = nil
  1568. p.it.fieldType = Empty
  1569. }
  1570. func (p *point) Reset() {
  1571. p.it.fieldType = Empty
  1572. p.it.key = nil
  1573. p.it.valueBuf = nil
  1574. p.it.start = 0
  1575. p.it.end = 0
  1576. }
  1577. // MarshalBinary encodes all the fields to their proper type and returns the binary
  1578. // represenation
  1579. // NOTE: uint64 is specifically not supported due to potential overflow when we decode
  1580. // again later to an int64
  1581. // NOTE2: uint is accepted, and may be 64 bits, and is for some reason accepted...
  1582. func (p Fields) MarshalBinary() []byte {
  1583. var b []byte
  1584. keys := make([]string, 0, len(p))
  1585. for k := range p {
  1586. keys = append(keys, k)
  1587. }
  1588. // Not really necessary, can probably be removed.
  1589. sort.Strings(keys)
  1590. for i, k := range keys {
  1591. if i > 0 {
  1592. b = append(b, ',')
  1593. }
  1594. b = appendField(b, k, p[k])
  1595. }
  1596. return b
  1597. }
  1598. func appendField(b []byte, k string, v interface{}) []byte {
  1599. b = append(b, []byte(GetString(k))...)
  1600. b = append(b, '=')
  1601. // check popular types first
  1602. switch v := v.(type) {
  1603. case float64:
  1604. b = strconv.AppendFloat(b, v, 'f', -1, 64)
  1605. case int64:
  1606. b = strconv.AppendInt(b, v, 10)
  1607. b = append(b, 'i')
  1608. case string:
  1609. b = append(b, '"')
  1610. b = append(b, []byte(EscapeStringField(v))...)
  1611. b = append(b, '"')
  1612. case bool:
  1613. b = strconv.AppendBool(b, v)
  1614. case int32:
  1615. b = strconv.AppendInt(b, int64(v), 10)
  1616. b = append(b, 'i')
  1617. case int16:
  1618. b = strconv.AppendInt(b, int64(v), 10)
  1619. b = append(b, 'i')
  1620. case int8:
  1621. b = strconv.AppendInt(b, int64(v), 10)
  1622. b = append(b, 'i')
  1623. case int:
  1624. b = strconv.AppendInt(b, int64(v), 10)
  1625. b = append(b, 'i')
  1626. case uint32:
  1627. b = strconv.AppendInt(b, int64(v), 10)
  1628. b = append(b, 'i')
  1629. case uint16:
  1630. b = strconv.AppendInt(b, int64(v), 10)
  1631. b = append(b, 'i')
  1632. case uint8:
  1633. b = strconv.AppendInt(b, int64(v), 10)
  1634. b = append(b, 'i')
  1635. // TODO: 'uint' should be considered just as "dangerous" as a uint64,
  1636. // perhaps the value should be checked and capped at MaxInt64? We could
  1637. // then include uint64 as an accepted value
  1638. case uint:
  1639. b = strconv.AppendInt(b, int64(v), 10)
  1640. b = append(b, 'i')
  1641. case float32:
  1642. b = strconv.AppendFloat(b, float64(v), 'f', -1, 32)
  1643. case []byte:
  1644. b = append(b, v...)
  1645. case nil:
  1646. // skip
  1647. default:
  1648. // Can't determine the type, so convert to string
  1649. b = append(b, '"')
  1650. b = append(b, []byte(EscapeStringField(fmt.Sprintf("%v", v)))...)
  1651. b = append(b, '"')
  1652. }
  1653. return b
  1654. }
  1655. type byteSlices [][]byte
  1656. func (a byteSlices) Len() int { return len(a) }
  1657. func (a byteSlices) Less(i, j int) bool { return bytes.Compare(a[i], a[j]) == -1 }
  1658. func (a byteSlices) Swap(i, j int) { a[i], a[j] = a[j], a[i] }