nodealert.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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 models
  15. import (
  16. "context"
  17. "fmt"
  18. "strings"
  19. "time"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/pkg/util/rbacscope"
  24. "yunion.io/x/sqlchemy"
  25. "yunion.io/x/onecloud/pkg/apis"
  26. "yunion.io/x/onecloud/pkg/apis/monitor"
  27. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  28. "yunion.io/x/onecloud/pkg/httperrors"
  29. "yunion.io/x/onecloud/pkg/mcclient"
  30. "yunion.io/x/onecloud/pkg/mcclient/auth"
  31. "yunion.io/x/onecloud/pkg/mcclient/modulebase"
  32. modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  33. merrors "yunion.io/x/onecloud/pkg/monitor/errors"
  34. "yunion.io/x/onecloud/pkg/monitor/options"
  35. "yunion.io/x/onecloud/pkg/util/stringutils2"
  36. )
  37. const (
  38. NodeAlertMetadataType = "type"
  39. NodeAlertMetadataNodeId = "node_id"
  40. NodeAlertMetadataNodeName = "node_name"
  41. )
  42. var NodeAlertManager *SNodeAlertManager
  43. func init() {
  44. NodeAlertManager = NewNodeAlertManager()
  45. }
  46. // +onecloud:swagger-gen-ignore
  47. type SV1AlertManager struct {
  48. SAlertManager
  49. }
  50. // +onecloud:swagger-gen-model-singular=nodealert
  51. // +onecloud:swagger-gen-model-plural=nodealerts
  52. type SNodeAlertManager struct {
  53. SCommonAlertManager
  54. }
  55. func NewNodeAlertManager() *SNodeAlertManager {
  56. man := &SNodeAlertManager{
  57. SCommonAlertManager: SCommonAlertManager{
  58. SAlertManager: *NewAlertManager(SNodeAlert{}, "nodealert", "nodealerts"),
  59. },
  60. }
  61. man.SetVirtualObject(man)
  62. return man
  63. }
  64. // +onecloud:swagger-gen-ignore
  65. type SV1Alert struct {
  66. SAlert
  67. }
  68. type SNodeAlert struct {
  69. SCommonAlert
  70. }
  71. func (v1man *SV1AlertManager) CreateNotification(
  72. ctx context.Context,
  73. userCred mcclient.TokenCredential,
  74. alertName string,
  75. channel string,
  76. recipients string) (*SNotification, error) {
  77. userIds := strings.Split(recipients, ",")
  78. s := &monitor.NotificationSettingOneCloud{
  79. Channel: channel,
  80. UserIds: userIds,
  81. }
  82. return NotificationManager.CreateOneCloudNotification(ctx, userCred, alertName, s, "")
  83. }
  84. func (man *SNodeAlertManager) ValidateCreateData(
  85. ctx context.Context, userCred mcclient.TokenCredential,
  86. ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject,
  87. data monitor.NodeAlertCreateInput) (*monitor.NodeAlertCreateInput, error) {
  88. if data.Period == "" {
  89. data.Period = "5m"
  90. }
  91. if _, err := time.ParseDuration(data.Period); err != nil {
  92. return nil, httperrors.NewInputParameterError("Invalid period format: %s", data.Period)
  93. }
  94. if data.Metric == "" {
  95. return nil, merrors.NewArgIsEmptyErr("metric")
  96. }
  97. parts := strings.Split(data.Metric, ".")
  98. if len(parts) != 2 {
  99. return nil, httperrors.NewInputParameterError("metric %s is invalid format, usage <measurement>.<field>", data.Metric)
  100. }
  101. measurement, field, err := GetMeasurementField(data.Metric)
  102. if err != nil {
  103. return nil, err
  104. }
  105. if data.Recipients == "" {
  106. return nil, merrors.NewArgIsEmptyErr("recipients")
  107. }
  108. if data.NodeId == "" {
  109. return nil, merrors.NewArgIsEmptyErr("node_id")
  110. }
  111. nodeName, resType, err := man.validateResourceId(ctx, data.Type, data.NodeId)
  112. if err != nil {
  113. return nil, err
  114. }
  115. data.NodeName = nodeName
  116. name, err := man.genName(ctx, ownerId, resType, nodeName, data.Metric)
  117. if err != nil {
  118. return nil, err
  119. }
  120. alertInput := data.ToCommonAlertCreateInput(name, field, measurement, monitor.METRIC_DATABASE_TELE)
  121. alertInput, err = GetCommonAlertManager().ValidateCreateData(ctx, userCred, ownerId, query, alertInput)
  122. if err != nil {
  123. return nil, errors.Wrap(err, "CommonAlertManager.ValidateCreateData")
  124. }
  125. data.CommonAlertCreateInput = &alertInput
  126. data.AlertCreateInput = alertInput.AlertCreateInput
  127. data.UsedBy = AlertNotificationUsedByNodeAlert
  128. return &data, nil
  129. }
  130. func (man *SNodeAlertManager) genName(ctx context.Context, ownerId mcclient.IIdentityProvider, resType string, nodeName string, metric string) (string, error) {
  131. nameHint := fmt.Sprintf("%s %s %s", resType, nodeName, metric)
  132. name, err := db.GenerateName(ctx, man, ownerId, nameHint)
  133. if err != nil {
  134. return "", err
  135. }
  136. if name != nameHint {
  137. return "", httperrors.NewDuplicateNameError(man.Keyword(), metric)
  138. }
  139. return name, nil
  140. }
  141. func (man *SNodeAlertManager) validateResourceId(ctx context.Context, nodeType, nodeId string) (string, string, error) {
  142. var (
  143. retType string
  144. nodeName string
  145. err error
  146. )
  147. switch nodeType {
  148. case monitor.NodeAlertTypeHost:
  149. retType = "宿主机"
  150. nodeName, err = man.validateHostResource(ctx, nodeId)
  151. case monitor.NodeAlertTypeGuest:
  152. retType = "虚拟机"
  153. nodeName, err = man.validateGuestResource(ctx, nodeId)
  154. default:
  155. return "", "", httperrors.NewInputParameterError("unsupported resource type %s", nodeType)
  156. }
  157. return nodeName, retType, err
  158. }
  159. func (man *SNodeAlertManager) validateGuestResource(ctx context.Context, id string) (string, error) {
  160. return man.validateResourceByMod(ctx, &modules.Servers, id)
  161. }
  162. func (man *SNodeAlertManager) validateHostResource(ctx context.Context, id string) (string, error) {
  163. return man.validateResourceByMod(ctx, &modules.Hosts, id)
  164. }
  165. func (man *SNodeAlertManager) validateResourceByMod(ctx context.Context, mod modulebase.Manager, id string) (string, error) {
  166. s := auth.GetAdminSession(ctx, options.Options.Region)
  167. ret, err := mod.Get(s, id, nil)
  168. if err != nil {
  169. return "", err
  170. }
  171. name, err := ret.GetString("name")
  172. if err != nil {
  173. return "", err
  174. }
  175. return name, nil
  176. }
  177. func (man *SNodeAlertManager) ValidateListConditions(ctx context.Context, userCred mcclient.TokenCredential, query *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
  178. // hack: always use details in query to get more details
  179. query.Set("details", jsonutils.JSONTrue)
  180. return query, nil
  181. }
  182. func (man *SV1AlertManager) ListItemFilter(
  183. ctx context.Context,
  184. q *sqlchemy.SQuery,
  185. userCred mcclient.TokenCredential,
  186. query monitor.V1AlertListInput,
  187. ) (*sqlchemy.SQuery, error) {
  188. var err error
  189. q, err = man.SAlertManager.ListItemFilter(ctx, q, userCred, query.AlertListInput)
  190. if err != nil {
  191. return nil, errors.Wrap(err, "SAlertManager.ListItemFilter")
  192. }
  193. return q, nil
  194. }
  195. func (man *SV1AlertManager) OrderByExtraFields(
  196. ctx context.Context,
  197. q *sqlchemy.SQuery,
  198. userCred mcclient.TokenCredential,
  199. query monitor.V1AlertListInput,
  200. ) (*sqlchemy.SQuery, error) {
  201. var err error
  202. q, err = man.SAlertManager.OrderByExtraFields(ctx, q, userCred, query.AlertListInput)
  203. if err != nil {
  204. return nil, errors.Wrap(err, "SAlertManager.OrderByExtraFields")
  205. }
  206. return q, nil
  207. }
  208. func (man *SV1AlertManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
  209. var err error
  210. q, err = man.SAlertManager.QueryDistinctExtraField(q, field)
  211. if err == nil {
  212. return q, nil
  213. }
  214. return q, httperrors.ErrNotFound
  215. }
  216. func (alertV1 *SV1Alert) ValidateUpdateData(
  217. ctx context.Context,
  218. userCred mcclient.TokenCredential,
  219. query jsonutils.JSONObject,
  220. input monitor.V1AlertUpdateInput,
  221. ) (monitor.V1AlertUpdateInput, error) {
  222. var err error
  223. input.AlertUpdateInput, err = alertV1.SAlert.ValidateUpdateData(ctx, userCred, query, input.AlertUpdateInput)
  224. if err != nil {
  225. return input, errors.Wrap(err, "SAlert.ValidateUpdateData")
  226. }
  227. return input, nil
  228. }
  229. func (man *SNodeAlertManager) ListItemFilter(
  230. ctx context.Context, q *sqlchemy.SQuery,
  231. userCred mcclient.TokenCredential,
  232. query monitor.NodeAlertListInput,
  233. ) (*sqlchemy.SQuery, error) {
  234. q, err := man.SCommonAlertManager.ListItemFilter(ctx, q, userCred, query.ToCommonAlertListInput())
  235. if err != nil {
  236. return nil, err
  237. }
  238. if len(query.Metric) > 0 {
  239. }
  240. if len(query.Type) > 0 {
  241. }
  242. if len(query.NodeId) > 0 {
  243. }
  244. if len(query.NodeName) > 0 {
  245. }
  246. q = q.Equals("used_by", AlertNotificationUsedByNodeAlert)
  247. return q, nil
  248. }
  249. func (man *SNodeAlertManager) OrderByExtraFields(
  250. ctx context.Context,
  251. q *sqlchemy.SQuery,
  252. userCred mcclient.TokenCredential,
  253. query monitor.NodeAlertListInput,
  254. ) (*sqlchemy.SQuery, error) {
  255. var err error
  256. q, err = man.SCommonAlertManager.OrderByExtraFields(ctx, q, userCred, query.AlertListInput)
  257. if err != nil {
  258. return nil, errors.Wrap(err, "SV1AlertManager.OrderByExtraFields")
  259. }
  260. return q, nil
  261. }
  262. func (man *SNodeAlertManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
  263. var err error
  264. q, err = man.SCommonAlertManager.QueryDistinctExtraField(q, field)
  265. if err == nil {
  266. return q, nil
  267. }
  268. return q, httperrors.ErrNotFound
  269. }
  270. func (man *SNodeAlertManager) GetAlert(id string) (*SNodeAlert, error) {
  271. obj, err := man.FetchById(id)
  272. if err != nil {
  273. return nil, err
  274. }
  275. return obj.(*SNodeAlert), nil
  276. }
  277. func (man *SNodeAlertManager) CustomizeFilterList(
  278. ctx context.Context, q *sqlchemy.SQuery,
  279. userCred mcclient.TokenCredential, query jsonutils.JSONObject) (
  280. *db.CustomizeListFilters, error) {
  281. filters, err := man.SCommonAlertManager.CustomizeFilterList(ctx, q, userCred, query)
  282. if err != nil {
  283. return nil, err
  284. }
  285. input := new(monitor.NodeAlertListInput)
  286. if err := query.Unmarshal(input); err != nil {
  287. return nil, err
  288. }
  289. wrapF := func(f func(obj *SNodeAlert) (bool, error)) func(object jsonutils.JSONObject) (bool, error) {
  290. return func(data jsonutils.JSONObject) (bool, error) {
  291. id, err := data.GetString("id")
  292. if err != nil {
  293. return false, err
  294. }
  295. obj, err := man.GetAlert(id)
  296. if err != nil {
  297. return false, err
  298. }
  299. return f(obj)
  300. }
  301. }
  302. if input.Metric != "" {
  303. metric := input.Metric
  304. meaurement, field, err := GetMeasurementField(metric)
  305. if err != nil {
  306. return nil, err
  307. }
  308. mF := func(obj *SNodeAlert) (bool, error) {
  309. settings := obj.Settings
  310. for _, s := range settings.Conditions {
  311. if s.Query.Model.Measurement == meaurement && len(s.Query.Model.Selects) == 1 {
  312. if IsQuerySelectHasField(s.Query.Model.Selects[0], field) {
  313. return true, nil
  314. }
  315. }
  316. }
  317. return false, nil
  318. }
  319. filters.Append(wrapF(mF))
  320. }
  321. if input.NodeName != "" {
  322. nf := func(obj *SNodeAlert) (bool, error) {
  323. return obj.getNodeName() == input.NodeName, nil
  324. }
  325. filters.Append(wrapF(nf))
  326. }
  327. if input.NodeId != "" {
  328. filters.Append(wrapF(func(obj *SNodeAlert) (bool, error) {
  329. return obj.getNodeId() == input.NodeId, nil
  330. }))
  331. }
  332. if input.Type != "" {
  333. filters.Append(wrapF(func(obj *SNodeAlert) (bool, error) {
  334. return obj.getType() == input.Type, nil
  335. }))
  336. }
  337. return filters, nil
  338. }
  339. func (alert *SV1Alert) CustomizeCreate(
  340. ctx context.Context, userCred mcclient.TokenCredential,
  341. notiName, channel, recipients, usedBy string) error {
  342. noti, err := MeterAlertManager.CreateNotification(ctx, userCred, notiName, channel, recipients)
  343. if err != nil {
  344. return errors.Wrap(err, "create notification")
  345. }
  346. if alert.Id == "" {
  347. alert.Id = db.DefaultUUIDGenerator()
  348. }
  349. alert.UsedBy = usedBy
  350. _, err = alert.AttachNotification(
  351. ctx, userCred, noti,
  352. monitor.AlertNotificationStateUnknown,
  353. usedBy)
  354. return err
  355. }
  356. func (alert *SV1Alert) PostUpdate(
  357. ctx context.Context, userCred mcclient.TokenCredential,
  358. query jsonutils.JSONObject, data jsonutils.JSONObject) {
  359. if data.(*jsonutils.JSONDict).Contains("status") {
  360. status, _ := data.(*jsonutils.JSONDict).GetString("status")
  361. alert.UpdateIsEnabledStatus(ctx, userCred, &status)
  362. }
  363. }
  364. func (alert *SNodeAlert) CustomizeCreate(
  365. ctx context.Context, userCred mcclient.TokenCredential,
  366. ownerId mcclient.IIdentityProvider,
  367. query jsonutils.JSONObject,
  368. data jsonutils.JSONObject,
  369. ) error {
  370. input := new(monitor.NodeAlertCreateInput)
  371. if err := data.Unmarshal(input); err != nil {
  372. return err
  373. }
  374. if alert.Id == "" {
  375. alert.Id = db.DefaultUUIDGenerator()
  376. }
  377. alert.UsedBy = input.UsedBy
  378. caInput := input.CommonAlertCreateInput
  379. if err := alert.SCommonAlert.CustomizeCreate(ctx, userCred, ownerId, query, caInput.JSON(caInput)); err != nil {
  380. return errors.Wrap(err, "CommonAlert.CustomizeCreate")
  381. }
  382. return nil
  383. }
  384. func (alert *SNodeAlert) getNodeId() string {
  385. return alert.GetMetadata(context.Background(), NodeAlertMetadataNodeId, nil)
  386. }
  387. func (alert *SNodeAlert) setNodeId(ctx context.Context, userCred mcclient.TokenCredential, id string) error {
  388. return alert.SetMetadata(ctx, NodeAlertMetadataNodeId, id, userCred)
  389. }
  390. func (alert *SNodeAlert) getNodeName() string {
  391. return alert.GetMetadata(context.Background(), NodeAlertMetadataNodeName, nil)
  392. }
  393. func (alert *SNodeAlert) setNodeName(ctx context.Context, userCred mcclient.TokenCredential, name string) error {
  394. return alert.SetMetadata(ctx, NodeAlertMetadataNodeName, name, userCred)
  395. }
  396. func (alert *SNodeAlert) getType() string {
  397. return alert.GetMetadata(context.Background(), NodeAlertMetadataType, nil)
  398. }
  399. func (alert *SNodeAlert) setType(ctx context.Context, userCred mcclient.TokenCredential, typ string) error {
  400. return alert.SetMetadata(ctx, NodeAlertMetadataType, typ, userCred)
  401. }
  402. func (alert *SNodeAlert) PostCreate(ctx context.Context,
  403. userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider,
  404. query jsonutils.JSONObject, data jsonutils.JSONObject) {
  405. input := new(monitor.NodeAlertCreateInput)
  406. if err := data.Unmarshal(input); err != nil {
  407. log.Errorf("post create unmarshal input: %v", err)
  408. return
  409. }
  410. if err := alert.setNodeId(ctx, userCred, input.NodeId); err != nil {
  411. log.Errorf("set node id: %v", err)
  412. return
  413. }
  414. if err := alert.setNodeName(ctx, userCred, input.NodeName); err != nil {
  415. log.Errorf("set node name: %v", err)
  416. return
  417. }
  418. if err := alert.setType(ctx, userCred, input.Type); err != nil {
  419. log.Errorf("set type: %v", err)
  420. return
  421. }
  422. caInput := input.CommonAlertCreateInput
  423. alert.SCommonAlert.PostCreate(ctx, userCred, ownerId, query, caInput.JSON(caInput))
  424. }
  425. func (man *SV1AlertManager) FetchCustomizeColumns(
  426. ctx context.Context,
  427. userCred mcclient.TokenCredential,
  428. query jsonutils.JSONObject,
  429. objs []interface{},
  430. fields stringutils2.SSortedStrings,
  431. isList bool,
  432. ) []monitor.AlertV1Details {
  433. rows := make([]monitor.AlertV1Details, len(objs))
  434. alertRows := man.SAlertManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  435. for i := range rows {
  436. rows[i] = monitor.AlertV1Details{
  437. AlertDetails: alertRows[i],
  438. }
  439. }
  440. return rows
  441. }
  442. const (
  443. V1AlertDisabledStatus = "Disabled"
  444. V1AlertEnabledStatus = "Enabled"
  445. )
  446. func (alert *SV1Alert) GetStatus() string {
  447. if alert.IsEnable() {
  448. return V1AlertEnabledStatus
  449. }
  450. return V1AlertDisabledStatus
  451. }
  452. func (alert *SV1Alert) getMoreDetails(out monitor.AlertV1Details, usedBy string) (monitor.AlertV1Details, error) {
  453. out.Name = alert.GetName()
  454. if alert.Frequency < 60 {
  455. out.Window = fmt.Sprintf("%ds", alert.Frequency)
  456. } else {
  457. out.Window = fmt.Sprintf("%dm", alert.Frequency/60)
  458. }
  459. setting, err := alert.GetSettings()
  460. if err != nil {
  461. return out, errors.Wrapf(err, "GetSettings")
  462. }
  463. if len(setting.Conditions) == 0 {
  464. return out, nil
  465. }
  466. cond := setting.Conditions[0]
  467. cmp := ""
  468. switch cond.Evaluator.Type {
  469. case "gt":
  470. cmp = ">="
  471. case "lt":
  472. cmp = "<="
  473. }
  474. out.Level = alert.Level
  475. out.Comparator = cmp
  476. out.Threshold = cond.Evaluator.Params[0]
  477. out.Period = cond.Query.From
  478. noti, err := alert.GetNotification(usedBy)
  479. if err != nil {
  480. return out, errors.Wrapf(err, "GetNotification for %q", usedBy)
  481. }
  482. if noti != nil {
  483. out.NotifierId = noti.GetId()
  484. settings := new(monitor.NotificationSettingOneCloud)
  485. if err := noti.Settings.Unmarshal(settings); err != nil {
  486. return out, errors.Wrapf(err, "Unmarshal to NotificationSettingOneCloud")
  487. }
  488. out.Recipients = strings.Join(settings.UserIds, ",")
  489. out.Channel = settings.Channel
  490. }
  491. q := cond.Query
  492. measurement := q.Model.Measurement
  493. field := q.Model.Selects[0][0].Params[0]
  494. db := q.Model.Database
  495. out.Measurement = measurement
  496. out.Field = field
  497. out.DB = db
  498. out.Status = alert.GetStatus()
  499. return out, nil
  500. }
  501. func (man *SNodeAlertManager) FetchCustomizeColumns(
  502. ctx context.Context,
  503. userCred mcclient.TokenCredential,
  504. query jsonutils.JSONObject,
  505. objs []interface{},
  506. fields stringutils2.SSortedStrings,
  507. isList bool,
  508. ) []monitor.NodeAlertDetails {
  509. rows := make([]monitor.NodeAlertDetails, len(objs))
  510. cObjs := make([]interface{}, len(objs))
  511. for i := range objs {
  512. obj := objs[i].(*SNodeAlert)
  513. cObjs[i] = &SCommonAlert{obj.SAlert}
  514. }
  515. v1Rows := man.SCommonAlertManager.FetchCustomizeColumns(ctx, userCred, query, cObjs, fields, isList)
  516. for i := range rows {
  517. rows[i] = monitor.NodeAlertDetails{
  518. AlertV1Details: monitor.AlertV1Details{
  519. AlertDetails: v1Rows[i].AlertDetails,
  520. },
  521. }
  522. var err error
  523. rows[i], err = objs[i].(*SNodeAlert).getMoreDetails(ctx, v1Rows[i], rows[i])
  524. if err != nil {
  525. log.Warningf("getMoreDetails for nodealert %s: %v", rows[i].Name, err)
  526. }
  527. }
  528. return rows
  529. }
  530. func (alert *SNodeAlert) getMoreDetails(ctx context.Context, input monitor.CommonAlertDetails, out monitor.NodeAlertDetails) (monitor.NodeAlertDetails, error) {
  531. out.Type = alert.getType()
  532. out.NodeId = alert.getNodeId()
  533. out.NodeName = alert.getNodeName()
  534. out.AlertDetails = input.AlertDetails
  535. out.Name = alert.GetName()
  536. out.Period = input.Period
  537. if alert.Frequency < 60 {
  538. out.Window = fmt.Sprintf("%ds", alert.Frequency)
  539. } else {
  540. out.Window = fmt.Sprintf("%dm", alert.Frequency/60)
  541. }
  542. setting, err := alert.GetSettings()
  543. if err != nil {
  544. return out, errors.Wrap(err, "GetSettings")
  545. }
  546. if len(setting.Conditions) == 0 {
  547. return out, nil
  548. }
  549. cond := setting.Conditions[0]
  550. cmp := ""
  551. switch cond.Evaluator.Type {
  552. case "gt":
  553. cmp = ">="
  554. case "lt":
  555. cmp = "<="
  556. }
  557. out.Level = alert.Level
  558. out.Comparator = cmp
  559. out.Threshold = cond.Evaluator.Params[0]
  560. out.Period = cond.Query.From
  561. q := cond.Query
  562. measurement := q.Model.Measurement
  563. field := q.Model.Selects[0][0].Params[0]
  564. db := q.Model.Database
  565. out.Measurement = measurement
  566. out.Field = field
  567. out.Metric = fmt.Sprintf("%s.%s", out.Measurement, out.Field)
  568. out.DB = db
  569. out.Status = alert.GetStatus()
  570. input, err = alert.SCommonAlert.GetMoreDetails(ctx, input)
  571. if err != nil {
  572. return out, errors.Wrap(err, "SCommonAlert.GetMoreDetails")
  573. }
  574. if len(input.Channel) > 0 {
  575. out.Channel = input.Channel[0]
  576. }
  577. out.Recipients = strings.Join(input.Recipients, ",")
  578. return out, nil
  579. }
  580. func (alert *SV1Alert) GetNotification(usedby string) (*SNotification, error) {
  581. alertNotis, err := alert.GetNotifications()
  582. if err != nil {
  583. return nil, err
  584. }
  585. if len(alertNotis) == 0 {
  586. return nil, nil
  587. }
  588. for _, an := range alertNotis {
  589. if an.GetUsedBy() == usedby {
  590. return an.GetNotification()
  591. }
  592. }
  593. return nil, httperrors.NewNotFoundError("not found alert notification used by %s", usedby)
  594. }
  595. func (alert *SV1Alert) UpdateNotification(usedBy string, channel, recipients *string) error {
  596. obj, err := alert.GetNotification(usedBy)
  597. if err != nil {
  598. return errors.Wrap(err, "Get notification when update")
  599. }
  600. if obj == nil {
  601. return nil
  602. }
  603. setting := new(monitor.NotificationSettingOneCloud)
  604. if err := obj.Settings.Unmarshal(setting); err != nil {
  605. return errors.Wrap(err, "unmarshal onecloud notification setting")
  606. }
  607. if channel != nil {
  608. setting.Channel = *channel
  609. }
  610. if recipients != nil {
  611. setting.UserIds = strings.Split(*recipients, ",")
  612. }
  613. _, err = db.Update(obj, func() error {
  614. obj.Settings = jsonutils.Marshal(setting)
  615. return nil
  616. })
  617. return err
  618. }
  619. func (alert *SV1Alert) UpdateIsEnabledStatus(ctx context.Context, userCred mcclient.TokenCredential, status *string) error {
  620. if status == nil {
  621. return nil
  622. }
  623. if status != nil {
  624. s := *status
  625. if s == V1AlertDisabledStatus {
  626. if _, err := alert.PerformDisable(ctx, userCred, nil, apis.PerformDisableInput{}); err != nil {
  627. return err
  628. }
  629. db.Update(&alert.SAlert, func() error {
  630. alert.SetStatus(ctx, userCred, V1AlertDisabledStatus, "")
  631. return nil
  632. })
  633. } else {
  634. if _, err := alert.PerformEnable(ctx, userCred, nil, apis.PerformEnableInput{}); err != nil {
  635. return err
  636. }
  637. db.Update(&alert.SAlert, func() error {
  638. alert.SetStatus(ctx, userCred, V1AlertEnabledStatus, "")
  639. return nil
  640. })
  641. }
  642. }
  643. return nil
  644. }
  645. func (alert *SV1Alert) CustomizeDelete(
  646. ctx context.Context, userCred mcclient.TokenCredential,
  647. query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  648. notis, err := alert.GetNotifications()
  649. if err != nil {
  650. return err
  651. }
  652. for _, noti := range notis {
  653. conf, err := noti.GetNotification()
  654. if err != nil {
  655. return err
  656. }
  657. if !conf.IsDefault {
  658. if err := conf.CustomizeDelete(ctx, userCred, query, data); err != nil {
  659. return err
  660. }
  661. if err := conf.Delete(ctx, userCred); err != nil {
  662. return err
  663. }
  664. }
  665. if err := noti.Detach(ctx, userCred); err != nil {
  666. return err
  667. }
  668. }
  669. return nil
  670. }
  671. func (alert *SNodeAlert) GetCommonAlertUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input *monitor.NodeAlertUpdateInput) (jsonutils.JSONObject, error) {
  672. detailsList := NodeAlertManager.FetchCustomizeColumns(ctx, userCred, nil, []interface{}{alert}, nil, false)
  673. if len(detailsList) == 0 {
  674. panic("inconsistent return results of FetchCustomizeColumns")
  675. }
  676. details := detailsList[0]
  677. nameChange := false
  678. if input.NodeId != nil && *input.NodeId != details.NodeId {
  679. nameChange = true
  680. details.NodeId = *input.NodeId
  681. if err := alert.setNodeId(ctx, userCred, details.NodeId); err != nil {
  682. return nil, err
  683. }
  684. }
  685. if input.Type != nil && *input.Type != details.Type {
  686. nameChange = true
  687. details.Type = *input.Type
  688. if err := alert.setType(ctx, userCred, details.Type); err != nil {
  689. return nil, err
  690. }
  691. }
  692. nodeName, resType, err := NodeAlertManager.validateResourceId(ctx, details.Type, details.NodeId)
  693. if err != nil {
  694. return nil, err
  695. }
  696. if details.NodeName != nodeName {
  697. nameChange = true
  698. if err := alert.setNodeName(ctx, userCred, nodeName); err != nil {
  699. return nil, err
  700. }
  701. details.NodeName = nodeName
  702. }
  703. if input.Level != nil && *input.Level != details.Level {
  704. details.Level = *input.Level
  705. }
  706. if input.Window != nil && *input.Window != details.Window {
  707. details.Window = *input.Window
  708. freq, err := time.ParseDuration(details.Window)
  709. if err != nil {
  710. return nil, err
  711. }
  712. freqSec := int64(freq / time.Second)
  713. input.Frequency = &freqSec
  714. }
  715. if input.Threshold != nil && *input.Threshold != details.Threshold {
  716. details.Threshold = *input.Threshold
  717. }
  718. if input.Comparator != nil && *input.Comparator != details.Comparator {
  719. details.Comparator = *input.Comparator
  720. }
  721. if input.Period != nil && *input.Period != details.Period {
  722. details.Period = *input.Period
  723. }
  724. if input.Channel != nil {
  725. details.Channel = *input.Channel
  726. }
  727. if input.Recipients != nil {
  728. details.Recipients = *input.Recipients
  729. }
  730. if input.Metric != nil && *input.Metric != details.Metric {
  731. details.Metric = *input.Metric
  732. measurement, field, err := GetMeasurementField(*input.Metric)
  733. if err != nil {
  734. return nil, err
  735. }
  736. details.Measurement = measurement
  737. details.Field = field
  738. }
  739. name := alert.Name
  740. if nameChange {
  741. name, err = NodeAlertManager.genName(ctx, userCred, resType, details.NodeName, details.Metric)
  742. if err != nil {
  743. return nil, err
  744. }
  745. input.Name = name
  746. }
  747. tmpS := alert.getUpdateInput(name, details)
  748. input.Settings = &tmpS.Settings
  749. uData, err := alert.SCommonAlert.ValidateUpdateData(ctx, userCred, nil, tmpS.JSON(tmpS))
  750. if err != nil {
  751. return nil, errors.Wrap(err, "SCommonAlert.ValidateUpdateData")
  752. }
  753. return uData, nil
  754. }
  755. func (alert *SNodeAlert) ValidateUpdateData(
  756. ctx context.Context,
  757. userCred mcclient.TokenCredential,
  758. query jsonutils.JSONObject,
  759. input monitor.NodeAlertUpdateInput,
  760. ) (jsonutils.JSONObject, error) {
  761. return alert.GetCommonAlertUpdateData(ctx, userCred, query, &input)
  762. }
  763. func (alert *SNodeAlert) getUpdateInput(
  764. name string,
  765. details monitor.NodeAlertDetails,
  766. ) monitor.CommonAlertCreateInput {
  767. data := monitor.NodeAlertCreateInput{
  768. ResourceAlertV1CreateInput: monitor.ResourceAlertV1CreateInput{
  769. Period: details.Period,
  770. Window: details.Window,
  771. Comparator: details.Comparator,
  772. Threshold: details.Threshold,
  773. Channel: details.Channel,
  774. Recipients: details.Recipients,
  775. },
  776. Metric: details.Metric,
  777. Type: details.Type,
  778. NodeId: details.NodeId,
  779. }
  780. data.Level = details.Level
  781. out := data.ToCommonAlertCreateInput(name, details.Field, details.Measurement, details.DB)
  782. out.Settings = *setAlertDefaultSetting(&out.Settings)
  783. return out
  784. }
  785. func (alert *SNodeAlert) PostUpdate(
  786. ctx context.Context, userCred mcclient.TokenCredential,
  787. query jsonutils.JSONObject, data jsonutils.JSONObject) {
  788. input := new(monitor.NodeAlertUpdateInput)
  789. data.Unmarshal(input)
  790. uData, err := alert.GetCommonAlertUpdateData(ctx, userCred, query, input)
  791. if err != nil {
  792. log.Errorf("GetCommonAlertUpdateData when PostUpdate: %v", err)
  793. }
  794. alert.SCommonAlert.PostUpdate(ctx, userCred, query, uData)
  795. }
  796. func (alert *SNodeAlert) CustomizeDelete(
  797. ctx context.Context, userCred mcclient.TokenCredential,
  798. query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  799. return alert.SCommonAlert.CustomizeDelete(ctx, userCred, query, data)
  800. }
  801. func (m *SNodeAlertManager) FilterByOwner(ctx context.Context, q *sqlchemy.SQuery, man db.FilterByOwnerProvider, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, scope rbacscope.TRbacScope) *sqlchemy.SQuery {
  802. return q
  803. }