metricquery.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 conditions
  15. import (
  16. gocontext "context"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. "yunion.io/x/jsonutils"
  23. "yunion.io/x/log"
  24. "yunion.io/x/pkg/errors"
  25. "yunion.io/x/pkg/util/workqueue"
  26. "yunion.io/x/pkg/utils"
  27. "yunion.io/x/onecloud/pkg/apis/monitor"
  28. "yunion.io/x/onecloud/pkg/mcclient"
  29. "yunion.io/x/onecloud/pkg/mcclient/auth"
  30. "yunion.io/x/onecloud/pkg/monitor/alerting"
  31. "yunion.io/x/onecloud/pkg/monitor/datasource"
  32. mq "yunion.io/x/onecloud/pkg/monitor/metricquery"
  33. "yunion.io/x/onecloud/pkg/monitor/tsdb"
  34. "yunion.io/x/onecloud/pkg/monitor/validators"
  35. )
  36. func init() {
  37. mq.RegisterMetricQuery(monitor.ConditionTypeMetricQuery, func(model []*monitor.AlertCondition) (mq.MetricQuery, error) {
  38. return NewMetricQueryCondition(model)
  39. })
  40. }
  41. type MetricQueryCondition struct {
  42. QueryCons []QueryCondition
  43. HandleRequest tsdb.HandleRequestFunc
  44. }
  45. func NewMetricQueryCondition(models []*monitor.AlertCondition) (*MetricQueryCondition, error) {
  46. cond := new(MetricQueryCondition)
  47. cond.HandleRequest = tsdb.HandleRequest
  48. for index, model := range models {
  49. qc := new(QueryCondition)
  50. qc.Index = index
  51. q := model.Query
  52. qc.Query.Model = q.Model
  53. qc.Query.From = q.From
  54. qc.Query.To = q.To
  55. if err := validators.ValidateFromValue(qc.Query.From); err != nil {
  56. return nil, errors.Wrapf(err, "validate from value %q", qc.Query.From)
  57. }
  58. if err := validators.ValidateToValue(qc.Query.To); err != nil {
  59. return nil, errors.Wrapf(err, "validate to value %q", qc.Query.To)
  60. }
  61. reducer, err := NewAlertReducer(&model.Reducer)
  62. if err != nil {
  63. return nil, errors.Wrapf(err, "NewAlertReducer")
  64. }
  65. qc.Reducer = reducer
  66. qc.ReducerOrder = model.ReducerOrder
  67. qc.setResType()
  68. cond.QueryCons = append(cond.QueryCons, *qc)
  69. }
  70. return cond, nil
  71. }
  72. type queryReducedResultSorter struct {
  73. r *queryResult
  74. order monitor.ResultReducerOrder
  75. }
  76. func newQueryReducedResultSorter(
  77. r *queryResult,
  78. order monitor.ResultReducerOrder) *queryReducedResultSorter {
  79. return &queryReducedResultSorter{
  80. r: r,
  81. order: order,
  82. }
  83. }
  84. func (q *queryReducedResultSorter) Len() int {
  85. return len(q.r.reducedResult.Result)
  86. }
  87. func (q *queryReducedResultSorter) Less(i, j int) bool {
  88. vi, vj := q.r.reducedResult.Result[i], q.r.reducedResult.Result[j]
  89. if q.order == monitor.RESULT_REDUCER_ORDER_ASC {
  90. if vi < vj {
  91. return true
  92. }
  93. return false
  94. }
  95. if vi > vj {
  96. return true
  97. }
  98. return false
  99. }
  100. func (q *queryReducedResultSorter) Swap(i, j int) {
  101. q.r.reducedResult.Result[i], q.r.reducedResult.Result[j] = q.r.reducedResult.Result[j], q.r.reducedResult.Result[i]
  102. q.r.series[i], q.r.series[j] = q.r.series[j], q.r.series[i]
  103. if len(q.r.metas) > i && len(q.r.metas) > j {
  104. q.r.metas[i], q.r.metas[j] = q.r.metas[j], q.r.metas[i]
  105. }
  106. }
  107. func (query *MetricQueryCondition) ExecuteQuery(userCred mcclient.TokenCredential, scope string, skipCheckSeries bool) (*monitor.MetricsQueryResult, error) {
  108. firstCond := query.QueryCons[0]
  109. timeRange := tsdb.NewTimeRange(firstCond.Query.From, firstCond.Query.To)
  110. ctx := gocontext.Background()
  111. evalContext := alerting.EvalContext{
  112. Ctx: ctx,
  113. IsDebug: true,
  114. IsTestRun: false,
  115. }
  116. allStartTime := time.Now()
  117. var qr *queryResult
  118. var err error
  119. ds, err := datasource.GetDefaultSource("")
  120. if err != nil {
  121. return nil, errors.Wrapf(err, "Can't find default datasource")
  122. }
  123. sortMetrics := func(metrics *queryResult, order monitor.ResultReducerOrder) *queryResult {
  124. if metrics.reducedResult != nil && len(metrics.reducedResult.Result) > 0 {
  125. s := newQueryReducedResultSorter(metrics, order)
  126. sort.Sort(s)
  127. return s.r
  128. }
  129. return metrics
  130. }
  131. queryTSDB := func() (*queryResult, error) {
  132. startTime := time.Now()
  133. queryResult, err := query.executeQuery(ds, &evalContext, timeRange)
  134. if err != nil {
  135. return nil, errors.Wrapf(err, "query.executeQuery from %s", ds.Type)
  136. }
  137. log.Debugf("query metrics from TSDB %q elapsed: %s", ds.Type, time.Since(startTime))
  138. if firstCond.Reducer.GetType() != "" {
  139. if queryResult.reducedResult == nil {
  140. queryResult.reducedResult = &monitor.ReducedResult{
  141. Reducer: monitor.Condition{
  142. Type: string(firstCond.Reducer.GetType()),
  143. Params: firstCond.Reducer.GetParams(),
  144. },
  145. Result: make([]float64, len(queryResult.series)),
  146. }
  147. }
  148. for i, ss := range queryResult.series {
  149. resultReducerValue, _ := firstCond.Reducer.Reduce(ss)
  150. if resultReducerValue != nil {
  151. queryResult.reducedResult.Result[i] = *resultReducerValue
  152. }
  153. }
  154. }
  155. return sortMetrics(queryResult, firstCond.ReducerOrder), nil
  156. }
  157. noCheck := query.noCheckSeries(skipCheckSeries)
  158. if noCheck {
  159. qr, err = queryTSDB()
  160. if err != nil {
  161. return nil, errors.Wrap(err, "queryTSDB")
  162. }
  163. metrics := &monitor.MetricsQueryResult{
  164. Series: qr.series,
  165. Metas: qr.metas,
  166. ReducedResult: qr.reducedResult,
  167. }
  168. return metrics, nil
  169. }
  170. qInfluxdbCh := make(chan bool, 0)
  171. qRegionCh := make(chan bool, 0)
  172. go func() {
  173. qr, err = queryTSDB()
  174. qInfluxdbCh <- true
  175. }()
  176. var (
  177. regionErr error
  178. ress []jsonutils.JSONObject
  179. resMap = make(map[string]jsonutils.JSONObject)
  180. )
  181. go func() {
  182. startTime := time.Now()
  183. defer func() {
  184. qRegionCh <- true
  185. log.Debugf("get resources from region elapsed: %s", time.Since(startTime))
  186. }()
  187. s := auth.GetSession(ctx, userCred, "")
  188. ress, regionErr = firstCond.getOnecloudResources(s, scope, false)
  189. if err != nil {
  190. regionErr = errors.Wrap(regionErr, "get resources from region")
  191. return
  192. }
  193. // convert resources to map
  194. for _, res := range ress {
  195. id, _ := res.GetString("id")
  196. if id == "" {
  197. continue
  198. }
  199. tmpRes := res
  200. resMap[id] = tmpRes
  201. }
  202. }()
  203. <-qInfluxdbCh
  204. <-qRegionCh
  205. if err != nil || regionErr != nil {
  206. return nil, errors.Errorf("tsdb error: %v, region error: %v", err, regionErr)
  207. }
  208. startTime := time.Now()
  209. //for _, serie := range queryResult.series {
  210. // isLatestOfSerie, resource := firstCond.serieIsLatestResource(resMap, serie)
  211. // if !isLatestOfSerie {
  212. // continue
  213. // }
  214. // firstCond.FillSerieByResourceField(resource, serie)
  215. // metrics.Series = append(metrics.Series, serie)
  216. //}
  217. metrics := monitor.MetricsQueryResult{
  218. Series: make(monitor.TimeSeriesSlice, 0),
  219. Metas: qr.metas,
  220. ReducedResult: qr.reducedResult,
  221. }
  222. mtx := sync.Mutex{}
  223. workqueue.Parallelize(4, len(qr.series), func(piece int) {
  224. serie := qr.series[piece]
  225. isLatestOfSerie, resource := firstCond.serieIsLatestResource(resMap, serie)
  226. if !isLatestOfSerie {
  227. return
  228. }
  229. firstCond.FillSerieByResourceField(resource, serie)
  230. mtx.Lock()
  231. defer mtx.Unlock()
  232. metrics.Series = append(metrics.Series, serie)
  233. })
  234. log.Debugf("fill metrics tag elapsed: %s", time.Since(startTime))
  235. log.Debugf("all steps elapsed: %s", time.Since(allStartTime))
  236. return &metrics, nil
  237. }
  238. func (query *MetricQueryCondition) noCheckSeries(skipCheckSeries bool) bool {
  239. firstCond := query.QueryCons[0]
  240. // always check series when resource type is "" or external resource
  241. if len(firstCond.ResType) == 0 || strings.HasPrefix(firstCond.ResType, monitor.EXT_PREFIX) {
  242. return true
  243. }
  244. if len(firstCond.Query.Model.GroupBy) == 0 {
  245. return true
  246. }
  247. if skipCheckSeries {
  248. return true
  249. }
  250. groupBys := make([]string, 0)
  251. containGlob := false
  252. for _, groupby := range firstCond.Query.Model.GroupBy {
  253. if utils.IsInStringArray("*", groupby.Params) {
  254. containGlob = true
  255. }
  256. groupBys = append(groupBys, groupby.Params...)
  257. }
  258. for _, supportId := range monitor.MEASUREMENT_TAG_ID {
  259. if utils.IsInStringArray(supportId, groupBys) {
  260. return false
  261. }
  262. }
  263. containNoCheckAggregator := false
  264. sels := firstCond.Query.Model.Selects
  265. lastSel := sels[len(sels)-1]
  266. for _, part := range lastSel {
  267. if utils.IsInStringArray(part.Type, []string{"sum"}) {
  268. containNoCheckAggregator = true
  269. }
  270. }
  271. if containGlob {
  272. if containNoCheckAggregator {
  273. return true
  274. }
  275. return false
  276. }
  277. return true
  278. }
  279. func (c *MetricQueryCondition) executeQuery(ds *tsdb.DataSource, context *alerting.EvalContext, timeRange *tsdb.TimeRange) (*queryResult, error) {
  280. req := c.getRequestQuery(ds, timeRange, context.IsDebug)
  281. result := make(monitor.TimeSeriesSlice, 0)
  282. metas := make([]monitor.QueryResultMeta, 0)
  283. if context.IsDebug {
  284. setContextLog(context, req)
  285. }
  286. resp, err := c.HandleRequest(context.Ctx, ds, req)
  287. if err != nil {
  288. if err == gocontext.DeadlineExceeded {
  289. return nil, errors.Error("Alert execution exceeded the timeout")
  290. }
  291. return nil, errors.Wrap(err, "metricQuery HandleRequest")
  292. }
  293. for _, v := range resp.Results {
  294. if v.Error != nil {
  295. return nil, errors.Wrap(err, "metricQuery HandleResult response error")
  296. }
  297. result = append(result, v.Series...)
  298. metas = append(metas, v.Meta)
  299. queryResultData := map[string]interface{}{}
  300. if context.IsTestRun {
  301. queryResultData["series"] = v.Series
  302. }
  303. if context.IsDebug {
  304. queryResultData["meta"] = v.Meta
  305. }
  306. if context.IsTestRun || context.IsDebug {
  307. context.Logs = append(context.Logs, &monitor.ResultLogEntry{
  308. Message: "Metric Query Result",
  309. Data: queryResultData,
  310. })
  311. }
  312. }
  313. return &queryResult{
  314. series: result,
  315. metas: metas,
  316. }, nil
  317. }
  318. func setContextLog(context *alerting.EvalContext, req *tsdb.TsdbQuery) {
  319. data := jsonutils.NewDict()
  320. if req.TimeRange != nil {
  321. data.Set("from", jsonutils.NewInt(req.TimeRange.GetFromAsMsEpoch()))
  322. data.Set("to", jsonutils.NewInt(req.TimeRange.GetToAsMsEpoch()))
  323. }
  324. type queryDto struct {
  325. RefId string `json:"refId"`
  326. Model monitor.MetricQuery `json:"model"`
  327. Datasource tsdb.DataSource `json:"datasource"`
  328. MaxDataPoints int64 `json:"maxDataPoints"`
  329. IntervalMs int64 `json:"intervalMs"`
  330. }
  331. queries := []*queryDto{}
  332. for _, q := range req.Queries {
  333. queries = append(queries, &queryDto{
  334. RefId: q.RefId,
  335. Model: q.MetricQuery,
  336. Datasource: q.DataSource,
  337. MaxDataPoints: q.MaxDataPoints,
  338. IntervalMs: q.IntervalMs,
  339. })
  340. }
  341. data.Set("queries", jsonutils.Marshal(queries))
  342. context.Logs = append(context.Logs, &monitor.ResultLogEntry{
  343. Message: "Metric Query",
  344. Data: data,
  345. })
  346. }
  347. func (query *MetricQueryCondition) getRequestQuery(ds *tsdb.DataSource, timeRange *tsdb.TimeRange, debug bool) *tsdb.TsdbQuery {
  348. querys := make([]*tsdb.Query, 0)
  349. for _, qc := range query.QueryCons {
  350. nDs := *ds
  351. nDs.Database = qc.Query.Model.Database
  352. querys = append(querys, &tsdb.Query{
  353. RefId: strconv.FormatInt(int64(qc.Index), 10),
  354. MetricQuery: qc.Query.Model,
  355. DataSource: nDs,
  356. })
  357. }
  358. req := &tsdb.TsdbQuery{
  359. TimeRange: timeRange,
  360. Queries: querys,
  361. Debug: debug,
  362. }
  363. return req
  364. }