influxdb.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 influxdb
  15. import (
  16. "context"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "net/url"
  21. "path"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "yunion.io/x/jsonutils"
  26. "yunion.io/x/log"
  27. "yunion.io/x/pkg/errors"
  28. "yunion.io/x/pkg/gotypes"
  29. "yunion.io/x/pkg/util/httputils"
  30. "yunion.io/x/pkg/utils"
  31. "yunion.io/x/onecloud/pkg/httperrors"
  32. )
  33. type SInfluxdb struct {
  34. accessUrl string
  35. client *http.Client
  36. dbName string
  37. debug bool
  38. }
  39. func NewInfluxdb(accessUrl string) *SInfluxdb {
  40. return NewInfluxdbWithDebug(accessUrl, false)
  41. }
  42. func NewInfluxdbWithDebug(accessUrl string, debug bool) *SInfluxdb {
  43. inst := SInfluxdb{
  44. accessUrl: accessUrl,
  45. client: httputils.GetDefaultClient(),
  46. debug: debug,
  47. }
  48. return &inst
  49. }
  50. type dbResult struct {
  51. Name string
  52. Tags *jsonutils.JSONDict
  53. Columns []string
  54. Values [][]jsonutils.JSONObject
  55. }
  56. func (db *SInfluxdb) Write(data string, precision string) error {
  57. if precision == "" {
  58. precision = "ns"
  59. }
  60. nurl := fmt.Sprintf("%s/write?db=%s&precision=%s", db.accessUrl, db.dbName, precision)
  61. header := http.Header{}
  62. header.Set("Content-Type", "application/octet-stream")
  63. resp, err := httputils.Request(db.client, context.Background(), "POST", nurl, header, strings.NewReader(data), db.debug)
  64. if err != nil {
  65. return errors.Wrap(err, "httputils.Request")
  66. }
  67. defer httputils.CloseResponse(resp)
  68. b, err := ioutil.ReadAll(resp.Body)
  69. if err != nil {
  70. return errors.Wrap(err, "ioutil.ReadAll")
  71. }
  72. if resp.StatusCode >= 300 {
  73. return errors.Error(fmt.Sprintf("Status: %d Message: %s", resp.StatusCode, string(b)))
  74. }
  75. return nil
  76. }
  77. func (db *SInfluxdb) BatchWrite(data []string, precision string) error {
  78. if precision == "" {
  79. precision = "ns"
  80. }
  81. nurl := fmt.Sprintf("%s/write?db=%s&precision=%s", db.accessUrl, db.dbName, precision)
  82. header := http.Header{}
  83. header.Set("Content-Type", "application/octet-stream")
  84. resp, err := httputils.Request(db.client, context.Background(), "POST", nurl, header, strings.NewReader(strings.Join(data, "\n")), db.debug)
  85. if err != nil {
  86. return errors.Wrap(err, "httputils.Request")
  87. }
  88. defer httputils.CloseResponse(resp)
  89. b, err := ioutil.ReadAll(resp.Body)
  90. if err != nil {
  91. return errors.Wrap(err, "ioutil.ReadAll")
  92. }
  93. if resp.StatusCode >= 300 {
  94. return errors.Error(fmt.Sprintf("Status: %d Message: %s", resp.StatusCode, string(b)))
  95. }
  96. return nil
  97. }
  98. func (db *SInfluxdb) Query(sql string) ([][]dbResult, error) {
  99. nurl := fmt.Sprintf("%s/query?db=%s&q=%s&epoch=ms", db.accessUrl, db.dbName, url.QueryEscape(sql))
  100. _, body, err := httputils.JSONRequest(db.client, context.Background(), "GET", nurl, nil, nil, db.debug)
  101. if err != nil {
  102. return nil, err
  103. }
  104. if db.debug {
  105. log.Debugf("influx query: %s %s", db.accessUrl, body)
  106. }
  107. results, err := body.GetArray("results")
  108. if err != nil {
  109. return nil, err
  110. }
  111. rets := make([][]dbResult, len(results))
  112. for i := range results {
  113. series, err := results[i].Get("series")
  114. if err == nil {
  115. ret := make([]dbResult, 0)
  116. err = series.Unmarshal(&ret)
  117. if err != nil {
  118. return nil, err
  119. }
  120. rets[i] = ret
  121. }
  122. }
  123. return rets, nil
  124. }
  125. func (db *SInfluxdb) GetQuery(sql string) ([][]dbResult, error) {
  126. u, _ := url.Parse(db.accessUrl)
  127. u.Path = path.Join(u.Path, "query")
  128. _, body, err := JSONRequest(db.client, context.Background(), http.MethodPost, u.String(), nil, sql, db.debug)
  129. if err != nil {
  130. return nil, err
  131. }
  132. if db.debug {
  133. log.Debugf("influx query: %s %s", db.accessUrl, body)
  134. }
  135. results, err := body.GetArray("results")
  136. if err != nil {
  137. return nil, err
  138. }
  139. rets := make([][]dbResult, len(results))
  140. for i := range results {
  141. series, err := results[i].Get("series")
  142. if err == nil {
  143. ret := make([]dbResult, 0)
  144. err = series.Unmarshal(&ret)
  145. if err != nil {
  146. return nil, err
  147. }
  148. rets[i] = ret
  149. continue
  150. }
  151. val, err := results[i].Get("error")
  152. if err == nil {
  153. log.Errorln(val)
  154. return nil, httperrors.ErrNotSupported
  155. }
  156. }
  157. return rets, nil
  158. }
  159. func JSONRequest(client *http.Client, ctx context.Context, method httputils.THttpMethod, urlStr string, header http.Header,
  160. body string, debug bool) (http.Header, jsonutils.JSONObject, error) {
  161. var bodystr string
  162. if !gotypes.IsNil(body) {
  163. // use POST mode
  164. bodyValues := url.Values{}
  165. bodyValues.Add("q", body)
  166. bodystr = bodyValues.Encode()
  167. }
  168. jbody := strings.NewReader(bodystr)
  169. if header == nil {
  170. header = http.Header{}
  171. }
  172. header.Set("Content-Length", strconv.FormatInt(int64(len(bodystr)), 10))
  173. header.Set("Content-Type", "application/x-www-form-urlencoded")
  174. resp, err := httputils.Request(client, ctx, method, urlStr, header, jbody, debug)
  175. return httputils.ParseJSONResponse(bodystr, resp, err, debug)
  176. }
  177. func (db *SInfluxdb) SetDatabase(dbName string) error {
  178. dbs, err := db.GetDatabases()
  179. if err != nil {
  180. return err
  181. }
  182. if !utils.IsInStringArray(dbName, dbs) {
  183. err = db.CreateDatabase(dbName)
  184. if err != nil {
  185. return err
  186. }
  187. return nil
  188. }
  189. db.dbName = dbName
  190. return nil
  191. }
  192. func (db *SInfluxdb) CreateDatabase(dbName string) error {
  193. _, err := db.Query(fmt.Sprintf("CREATE DATABASE %s", dbName))
  194. if err != nil {
  195. return err
  196. }
  197. return nil
  198. }
  199. func (db *SInfluxdb) GetDatabases() ([]string, error) {
  200. results, err := db.Query("SHOW DATABASES")
  201. if err != nil {
  202. return nil, err
  203. }
  204. res := results[0][0]
  205. ret := make([]string, len(res.Values))
  206. for i := range res.Values {
  207. ret[i], _ = res.Values[i][0].GetString()
  208. }
  209. return ret, nil
  210. }
  211. type SRetentionPolicy struct {
  212. Name string
  213. Duration string
  214. ShardGroupDuration string
  215. ReplicaN int
  216. Default bool
  217. }
  218. func (rp *SRetentionPolicy) String(dbName string) string {
  219. var buf strings.Builder
  220. buf.WriteString("RETENTION POLICY \"")
  221. buf.WriteString(rp.Name)
  222. buf.WriteString("\" ON \"")
  223. buf.WriteString(dbName)
  224. buf.WriteString("\" DURATION ")
  225. buf.WriteString(rp.Duration)
  226. buf.WriteString(fmt.Sprintf(" REPLICATION %d", rp.ReplicaN))
  227. if len(rp.ShardGroupDuration) > 0 {
  228. buf.WriteString(fmt.Sprintf(" SHARD DURATION %s", rp.ShardGroupDuration))
  229. }
  230. if rp.Default {
  231. buf.WriteString(" DEFAULT")
  232. }
  233. return buf.String()
  234. }
  235. func (db *SInfluxdb) GetRetentionPolicies() ([]SRetentionPolicy, error) {
  236. results, err := db.Query(fmt.Sprintf("SHOW RETENTION POLICIES ON %s", db.dbName))
  237. if err != nil {
  238. return nil, err
  239. }
  240. res := results[0][0]
  241. ret := make([]SRetentionPolicy, len(res.Values))
  242. for i := range res.Values {
  243. tmpDict := jsonutils.NewDict()
  244. for j := range res.Columns {
  245. tmpDict.Add(res.Values[i][j], res.Columns[j])
  246. }
  247. err = tmpDict.Unmarshal(&ret[i])
  248. if err != nil {
  249. return nil, err
  250. }
  251. }
  252. return ret, nil
  253. }
  254. func (db *SInfluxdb) CreateRetentionPolicy(rp SRetentionPolicy) error {
  255. _, err := db.Query(fmt.Sprintf("CREATE %s", rp.String(db.dbName)))
  256. return err
  257. }
  258. func (db *SInfluxdb) AlterRetentionPolicy(rp SRetentionPolicy) error {
  259. _, err := db.Query(fmt.Sprintf("ALTER %s", rp.String(db.dbName)))
  260. return err
  261. }
  262. func (db *SInfluxdb) SetRetentionPolicy(rp SRetentionPolicy) error {
  263. rps, err := db.GetRetentionPolicies()
  264. if err != nil {
  265. return err
  266. }
  267. find := false
  268. for i := range rps {
  269. if rps[i].Name == rp.Name {
  270. find = true
  271. break
  272. }
  273. }
  274. if find {
  275. return db.AlterRetentionPolicy(rp)
  276. } else {
  277. return db.CreateRetentionPolicy(rp)
  278. }
  279. }
  280. func (db *SInfluxdb) SetTimeout(timeout time.Duration) {
  281. db.client.Timeout = timeout
  282. }