scheduled_tasks.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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/tristate"
  24. "yunion.io/x/pkg/util/httputils"
  25. "yunion.io/x/pkg/util/sets"
  26. "yunion.io/x/pkg/utils"
  27. "yunion.io/x/sqlchemy"
  28. "yunion.io/x/onecloud/pkg/apis"
  29. comapi "yunion.io/x/onecloud/pkg/apis/compute"
  30. api "yunion.io/x/onecloud/pkg/apis/scheduledtask"
  31. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  32. "yunion.io/x/onecloud/pkg/cloudcommon/notifyclient"
  33. "yunion.io/x/onecloud/pkg/httperrors"
  34. "yunion.io/x/onecloud/pkg/mcclient"
  35. "yunion.io/x/onecloud/pkg/mcclient/auth"
  36. "yunion.io/x/onecloud/pkg/mcclient/modulebase"
  37. "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  38. "yunion.io/x/onecloud/pkg/mcclient/options"
  39. sop "yunion.io/x/onecloud/pkg/scheduledtask/options"
  40. "yunion.io/x/onecloud/pkg/util/logclient"
  41. "yunion.io/x/onecloud/pkg/util/stringutils2"
  42. )
  43. var ScheduledTaskManager *SScheduledTaskManager
  44. func init() {
  45. ScheduledTaskManager = &SScheduledTaskManager{
  46. SVirtualResourceBaseManager: db.NewVirtualResourceBaseManager(
  47. SScheduledTask{},
  48. "scheduledtasks_tbl",
  49. "scheduledtask",
  50. "scheduledtasks",
  51. ),
  52. }
  53. ScheduledTaskManager.SetVirtualObject(ScheduledTaskManager)
  54. }
  55. // +onecloud:swagger-gen-model-singular=scheduledtask
  56. // +onecloud:swagger-gen-model-singular=scheduledtasks
  57. type SScheduledTaskManager struct {
  58. db.SVirtualResourceBaseManager
  59. db.SEnabledResourceBaseManager
  60. }
  61. type SScheduledTask struct {
  62. db.SVirtualResourceBase
  63. db.SEnabledResourceBase
  64. ScheduledType string `width:"16" charset:"ascii" create:"required" list:"user" get:"user"`
  65. STimer
  66. ResourceType string `width:"32" charset:"ascii" create:"required" list:"user" get:"user"`
  67. Operation string `width:"32" charset:"ascii" create:"required" list:"user" get:"user"`
  68. LabelType string `width:"4" charset:"ascii" create:"required" list:"user" get:"user"`
  69. }
  70. func (stm *SScheduledTaskManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, input api.ScheduledTaskListInput) (*sqlchemy.SQuery, error) {
  71. var err error
  72. q, err = stm.SVirtualResourceBaseManager.ListItemFilter(ctx, q, userCred, input.VirtualResourceListInput)
  73. if err != nil {
  74. return q, err
  75. }
  76. q, err = stm.SEnabledResourceBaseManager.ListItemFilter(ctx, q, userCred, input.EnabledResourceBaseListInput)
  77. if err != nil {
  78. return q, err
  79. }
  80. if len(input.Operation) > 0 {
  81. q = q.Equals("operation", input.Operation)
  82. }
  83. if len(input.ResourceType) > 0 {
  84. q = q.Equals("resource_type", input.ResourceType)
  85. }
  86. if len(input.LabelType) > 0 {
  87. q = q.Equals("label_type", input.LabelType)
  88. }
  89. if len(input.Label) > 0 {
  90. sq := ScheduledTaskLabelManager.Query("scheduled_task_id").Equals("label", input.Label).SubQuery()
  91. q = q.Join(sq, sqlchemy.Equals(q.Field("id"), sq.Field("scheduled_task_id")))
  92. }
  93. return q, nil
  94. }
  95. func (stm *SScheduledTaskManager) OrderByExtraFields(ctx context.Context, q *sqlchemy.SQuery,
  96. userCred mcclient.TokenCredential, query api.ScheduledTaskListInput) (*sqlchemy.SQuery, error) {
  97. return stm.SVirtualResourceBaseManager.OrderByExtraFields(ctx, q, userCred, query.VirtualResourceListInput)
  98. }
  99. func (stm *SScheduledTaskManager) FetchCustomizeColumns(
  100. ctx context.Context,
  101. userCred mcclient.TokenCredential,
  102. query jsonutils.JSONObject,
  103. objs []interface{},
  104. fields stringutils2.SSortedStrings,
  105. isList bool,
  106. ) []api.ScheduledTaskDetails {
  107. utcOffset, _ := query.Int("utc_offset")
  108. zone := time.FixedZone("UTC", int(utcOffset)*3600)
  109. rows := make([]api.ScheduledTaskDetails, len(objs))
  110. virRows := stm.SVirtualResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  111. var err error
  112. for i := range rows {
  113. rows[i], err = objs[i].(*SScheduledTask).getMoreDetails(ctx, userCred, query, isList, zone)
  114. if err != nil {
  115. log.Errorf("SScheduledTask.getMoreDetails error: %s", err)
  116. }
  117. rows[i].VirtualResourceDetails = virRows[i]
  118. }
  119. return rows
  120. }
  121. func (st *SScheduledTask) getMoreDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, isList bool, zone *time.Location) (api.ScheduledTaskDetails, error) {
  122. var out api.ScheduledTaskDetails
  123. switch st.ScheduledType {
  124. case api.ST_TYPE_TIMING:
  125. out.Timer = st.STimer.TimerDetails()
  126. case api.ST_TYPE_CYCLE:
  127. out.CycleTimer = st.STimer.CycleTimerDetails()
  128. }
  129. out.TimerDesc = st.Description(ctx, st.CreatedAt, zone)
  130. // fill label
  131. stLabels, err := st.STLabels()
  132. if err != nil {
  133. return out, err
  134. }
  135. out.Labels = make([]string, len(stLabels))
  136. out.LabelDetails = make([]api.LabelDetail, len(stLabels))
  137. for i := range stLabels {
  138. out.Labels[i] = stLabels[i].Label
  139. out.LabelDetails[i].IsolatedTime = stLabels[i].CreatedAt
  140. out.LabelDetails[i].Label = stLabels[i].Label
  141. }
  142. return out, nil
  143. }
  144. func (stm *SScheduledTaskManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, input api.ScheduledTaskCreateInput) (api.ScheduledTaskCreateInput, error) {
  145. var err error
  146. input.VirtualResourceCreateInput, err = stm.SVirtualResourceBaseManager.ValidateCreateData(ctx, userCred, ownerId, query, input.VirtualResourceCreateInput)
  147. if err != nil {
  148. return input, err
  149. }
  150. if !utils.IsInStringArray(input.ScheduledType, []string{api.ST_TYPE_TIMING, api.ST_TYPE_CYCLE}) {
  151. return input, httperrors.NewInputParameterError("unkown scheduled type '%s'", input.ScheduledType)
  152. }
  153. if !utils.IsInStringArray(input.ResourceType, []string{api.ST_RESOURCE_SERVER, api.ST_RESOURCE_CLOUDACCOUNT}) {
  154. return input, httperrors.NewInputParameterError("unkown resource type '%s'", input.ResourceType)
  155. }
  156. if !utils.IsInStringArray(input.Operation, []string{api.ST_RESOURCE_OPERATION_RESTART, api.ST_RESOURCE_OPERATION_STOP, api.ST_RESOURCE_OPERATION_START, api.ST_RESOURCE_OPERATION_SYNC}) {
  157. return input, httperrors.NewInputParameterError("unkown resource operation '%s'", input.Operation)
  158. }
  159. if !utils.IsInStringArray(input.LabelType, []string{api.ST_LABEL_ID, api.ST_LABEL_TAG}) {
  160. return input, httperrors.NewInputParameterError("unkown label type '%s'", input.LabelType)
  161. }
  162. // check timer or cycletimer
  163. if input.ScheduledType == api.ST_TYPE_TIMING {
  164. input.Timer, err = checkTimerCreateInput(input.Timer)
  165. } else {
  166. input.CycleTimer, err = checkCycleTimerCreateInput(input.CycleTimer)
  167. }
  168. if err != nil {
  169. return input, httperrors.NewInputParameterError("%v", err)
  170. }
  171. return input, nil
  172. }
  173. func (st *SScheduledTask) PerformEnable(ctx context.Context, userCred mcclient.TokenCredential,
  174. query jsonutils.JSONObject, input apis.PerformEnableInput) (jsonutils.JSONObject, error) {
  175. err := db.EnabledPerformEnable(st, ctx, userCred, true)
  176. if err != nil {
  177. return nil, errors.Wrap(err, "EnabledPerformEnable")
  178. }
  179. return nil, nil
  180. }
  181. func (st *SScheduledTask) PerformDisable(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject,
  182. input apis.PerformDisableInput) (jsonutils.JSONObject, error) {
  183. err := db.EnabledPerformEnable(st, ctx, userCred, false)
  184. if err != nil {
  185. return nil, errors.Wrap(err, "EnabledPerformEnable")
  186. }
  187. return nil, nil
  188. }
  189. func (st *SScheduledTask) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  190. st.SVirtualResourceBase.PostCreate(ctx, userCred, ownerId, query, data)
  191. // add label
  192. createFailed := func(reason string) {
  193. st.SetStatus(ctx, userCred, api.ST_STATUS_CREATE_FAILED, reason)
  194. logclient.AddActionLogWithContext(ctx, st, logclient.ACT_CREATE, reason, userCred, false)
  195. }
  196. labels, _ := data.GetArray("labels")
  197. for i := range labels {
  198. label, _ := labels[i].GetString()
  199. err := ScheduledTaskLabelManager.Attach(ctx, st.Id, label)
  200. if err != nil {
  201. reason := fmt.Sprintf("unable to attach scheduled task '%s' with '%s'", st.Id, label)
  202. createFailed(reason)
  203. return
  204. }
  205. }
  206. input := api.ScheduledTaskCreateInput{}
  207. err := data.Unmarshal(&input)
  208. if err != nil {
  209. createFailed(err.Error())
  210. return
  211. }
  212. switch st.ScheduledType {
  213. case api.ST_TYPE_TIMING:
  214. st.STimer = STimer{
  215. Type: api.TIMER_TYPE_ONCE,
  216. StartTime: input.Timer.ExecTime,
  217. EndTime: input.Timer.ExecTime,
  218. NextTime: input.Timer.ExecTime,
  219. }
  220. case api.ST_TYPE_CYCLE:
  221. st.STimer = STimer{
  222. Type: input.CycleTimer.CycleType,
  223. Minute: input.CycleTimer.Minute,
  224. Hour: input.CycleTimer.Hour,
  225. StartTime: input.CycleTimer.StartTime,
  226. EndTime: input.CycleTimer.EndTime,
  227. CycleNum: input.CycleTimer.CycleNum,
  228. NextTime: time.Time{},
  229. }
  230. st.SetWeekDays(input.CycleTimer.WeekDays)
  231. st.SetMonthDays(input.CycleTimer.MonthDays)
  232. }
  233. st.Update(time.Time{})
  234. st.Status = api.ST_STATUS_READY
  235. st.Enabled = tristate.True
  236. // st.TimerDesc = st.Description(ctx)
  237. err = st.GetModelManager().TableSpec().InsertOrUpdate(ctx, st)
  238. if err != nil {
  239. createFailed("update itself")
  240. return
  241. }
  242. logclient.AddActionLogWithContext(ctx, st, logclient.ACT_CREATE, "", userCred, true)
  243. }
  244. func (st *SScheduledTask) ValidateDeleteCondition(ctx context.Context, info jsonutils.JSONObject) error {
  245. err := st.SVirtualResourceBase.ValidateDeleteCondition(ctx, nil)
  246. if err != nil {
  247. return err
  248. }
  249. ok, err := st.IsExecuted()
  250. if err != nil {
  251. return err
  252. }
  253. if ok {
  254. return httperrors.NewForbiddenError("This scheduled task is being executed now, please try later")
  255. }
  256. return nil
  257. }
  258. func (st *SScheduledTask) IsExecuted() (bool, error) {
  259. q := ScheduledTaskActivityManager.Query().Equals("status", api.ST_ACTIVITY_STATUS_EXEC).Equals("scheduled_task_id", st.Id)
  260. n, err := q.CountWithError()
  261. if err != nil {
  262. return false, err
  263. }
  264. return n > 0, nil
  265. }
  266. func (st *SScheduledTask) Labels() ([]string, error) {
  267. stLabels, err := st.STLabels()
  268. if err != nil {
  269. return nil, err
  270. }
  271. labels := make([]string, len(stLabels))
  272. for i := range labels {
  273. labels[i] = stLabels[i].Label
  274. }
  275. return labels, nil
  276. }
  277. func (st *SScheduledTask) STLabels() ([]SScheduledTaskLabel, error) {
  278. q := ScheduledTaskLabelManager.Query().Equals("scheduled_task_id", st.Id)
  279. labels := make([]SScheduledTaskLabel, 0, 1)
  280. err := db.FetchModelObjects(ScheduledTaskLabelManager, q, &labels)
  281. return labels, err
  282. }
  283. func (st *SScheduledTask) PerformSetLabels(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.ScheduledTaskSetLabelsInput) (jsonutils.JSONObject, error) {
  284. nowLabels, err := st.STLabels()
  285. if err != nil {
  286. return nil, err
  287. }
  288. nowLabelMap := make(map[string]*SScheduledTaskLabel, len(nowLabels))
  289. for i := range nowLabels {
  290. nowLabelMap[nowLabels[i].Label] = &nowLabels[i]
  291. }
  292. futureLabelSet := sets.NewString(input.Labels...)
  293. var attachs []string
  294. var detachs []*SScheduledTaskLabel
  295. for label := range futureLabelSet {
  296. if _, ok := nowLabelMap[label]; !ok {
  297. attachs = append(attachs, label)
  298. }
  299. }
  300. for label, stLable := range nowLabelMap {
  301. if !futureLabelSet.Has(label) {
  302. detachs = append(detachs, stLable)
  303. }
  304. }
  305. // attach
  306. for _, label := range attachs {
  307. err := ScheduledTaskLabelManager.Attach(ctx, st.Id, label)
  308. if err != nil {
  309. return nil, err
  310. }
  311. }
  312. // detach
  313. for _, stLabel := range detachs {
  314. err := stLabel.Detach(ctx, userCred)
  315. if err != nil {
  316. return nil, err
  317. }
  318. }
  319. return nil, nil
  320. }
  321. func (st *SScheduledTask) PerformTrigger(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.ScheduledTaskTriggerInput) (jsonutils.JSONObject, error) {
  322. go func() {
  323. log.Infof("start to execute scheduled task '%s'", st.Id)
  324. err := st.Execute(ctx, userCred)
  325. if err != nil {
  326. log.Errorf("fail to execute scheduled task '%s': %s", st.Id, err.Error())
  327. } else {
  328. log.Infof("execute scheduled task '%s' successfully", st.Id)
  329. }
  330. }()
  331. return nil, nil
  332. }
  333. func (st *SScheduledTask) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  334. err := st.SVirtualResourceBase.CustomizeDelete(ctx, userCred, query, data)
  335. if err != nil {
  336. return err
  337. }
  338. labels, err := st.STLabels()
  339. if err != nil {
  340. return err
  341. }
  342. for i := range labels {
  343. err := labels[i].Delete(ctx, userCred)
  344. if err != nil {
  345. log.Errorf("unbale to delete scheduled task label: %s", err.Error())
  346. }
  347. }
  348. return nil
  349. }
  350. func (st *SScheduledTask) Action(ctx context.Context, userCred mcclient.TokenCredential) SAction {
  351. session := auth.GetSession(ctx, userCred, "")
  352. return Action.ResourceOperation(st.ResourceOperation()).Session(session)
  353. }
  354. func (st *SScheduledTask) ExecuteNotify(ctx context.Context, userCred mcclient.TokenCredential, name string) {
  355. log.Infof("scheduledtask %s exec for resource %s", st.Name, name)
  356. notifyclient.EventNotify(ctx, userCred, notifyclient.SEventNotifyParam{
  357. Obj: st,
  358. Action: notifyclient.ActionExecute,
  359. ObjDetailsDecorator: func(ctx context.Context, details *jsonutils.JSONDict) {
  360. details.Set("resource_name", jsonutils.NewString(name))
  361. },
  362. })
  363. }
  364. func (st *SScheduledTask) Execute(ctx context.Context, userCred mcclient.TokenCredential) (err error) {
  365. exec, err := st.IsExecuted()
  366. if err != nil {
  367. return errors.Wrap(err, "unable to check if scheduled task is executed")
  368. }
  369. if exec {
  370. _, err := st.NewActivity(ctx, true)
  371. return err
  372. }
  373. sa, err := st.NewActivity(ctx, false)
  374. if err != nil {
  375. return err
  376. }
  377. over := false
  378. defer func() {
  379. if !over && err != nil {
  380. sa.Fail(err.Error())
  381. }
  382. }()
  383. action := st.Action(ctx, userCred)
  384. // Get All Resource
  385. labels, err := st.Labels()
  386. if err != nil {
  387. return err
  388. }
  389. var (
  390. ids []string
  391. opts options.BaseListOptions
  392. f bool
  393. limit int
  394. )
  395. switch st.LabelType {
  396. case api.ST_LABEL_TAG:
  397. opts = options.BaseListOptions{
  398. Details: &f,
  399. Limit: &limit,
  400. Scope: "system",
  401. Tags: labels,
  402. }
  403. case api.ST_LABEL_ID:
  404. opts = options.BaseListOptions{
  405. Details: &f,
  406. Limit: &limit,
  407. Scope: "system",
  408. Filter: []string{fmt.Sprintf("id.in(%s)", strings.Join(labels, ","))},
  409. }
  410. }
  411. res, err := action.List(&WrapperListOptions{opts})
  412. if err != nil {
  413. return err
  414. }
  415. if len(res) == 0 {
  416. reason := fmt.Sprintf("All %ss %s failed:\n%s", st.ResourceType, st.Operation, errors.ErrNotFound)
  417. sa.Fail(reason)
  418. return nil
  419. }
  420. for id := range res {
  421. ids = append(ids, id)
  422. }
  423. maxLimit := 20
  424. type result struct {
  425. id string
  426. succeed bool
  427. reason string
  428. }
  429. workerQueue := make(chan struct{}, maxLimit)
  430. results := make([]result, len(ids))
  431. log.Infof("servers to scheduledtask: %v", ids)
  432. for i, id := range ids {
  433. workerQueue <- struct{}{}
  434. go func(n int, id string) {
  435. ok, reason := action.Apply(id)
  436. log.Infof("exec successfully: %t, reason: %s", ok, reason)
  437. if ok {
  438. st.ExecuteNotify(ctx, userCred, res[id])
  439. }
  440. results[n] = result{id, ok, reason}
  441. <-workerQueue
  442. }(i, id)
  443. }
  444. // wait all finish
  445. for i := 0; i < maxLimit; i++ {
  446. workerQueue <- struct{}{}
  447. }
  448. failedReasons := make([]string, 0, 1)
  449. succeedIds := make([]string, 0, 1)
  450. displayStrs := res
  451. for _, ret := range results {
  452. if ret.succeed {
  453. succeedIds = append(succeedIds, displayStrs[ret.id])
  454. continue
  455. }
  456. failedReasons = append(failedReasons, fmt.Sprintf("\t%s: %s", displayStrs[ret.id], ret.reason))
  457. }
  458. if len(failedReasons) == 0 {
  459. sa.Succeed()
  460. return nil
  461. }
  462. if len(failedReasons) == len(ids) {
  463. reason := fmt.Sprintf("All %ss %s failed:\n%s", st.ResourceType, st.Operation, strings.Join(failedReasons, ";\n"))
  464. sa.Fail(reason)
  465. return nil
  466. }
  467. reason := fmt.Sprintf("Some %ss %s successfully:\n\t%s\n\n. Some %ss %s failed:\n%s", st.ResourceType, st.Operation, strings.Join(succeedIds, ";"), st.ResourceType, st.Operation, strings.Join(failedReasons, ";\n"))
  468. sa.PartFail(reason)
  469. return nil
  470. }
  471. func (st *SScheduledTask) NewActivity(ctx context.Context, reject bool) (*SScheduledTaskActivity, error) {
  472. now := time.Now()
  473. sa := &SScheduledTaskActivity{
  474. StartTime: now,
  475. }
  476. sa.Status = api.ST_ACTIVITY_STATUS_EXEC
  477. sa.ScheduledTaskId = st.Id
  478. if reject {
  479. sa.Status = api.ST_ACTIVITY_STATUS_REJECT
  480. sa.EndTime = now
  481. sa.Reason = "This Scheduled Task is being executed now"
  482. }
  483. err := ScheduledTaskActivityManager.TableSpec().Insert(ctx, sa)
  484. if err != nil {
  485. return nil, err
  486. }
  487. sa.SetModelManager(ScheduledTaskActivityManager, sa)
  488. return sa, nil
  489. }
  490. func (st *SScheduledTask) ResourceOperation() ResourceOperation {
  491. return ResourceOperationMap[fmt.Sprintf("%s.%s", st.ResourceType, st.Operation)]
  492. }
  493. type STimeScope struct {
  494. Start time.Time
  495. End time.Time
  496. Median time.Time
  497. }
  498. func (stm *SScheduledTaskManager) timeScope(median time.Time, interval time.Duration) STimeScope {
  499. ri := interval / 2
  500. return STimeScope{
  501. Start: median.Add(-ri),
  502. End: median.Add(ri),
  503. Median: median,
  504. }
  505. }
  506. var timerQueue chan struct{}
  507. func (stm *SScheduledTaskManager) Timer(ctx context.Context, userCred mcclient.TokenCredential, isStart bool) {
  508. if timerQueue == nil {
  509. timerQueue = make(chan struct{}, sop.Options.ScheduledTaskQueueSize)
  510. }
  511. log.Infof("queueSize: %d", sop.Options.ScheduledTaskQueueSize)
  512. // 60 is for fault tolerance
  513. interval := 60 + 30
  514. timeScope := stm.timeScope(time.Now(), time.Duration(interval)*time.Second)
  515. q := stm.Query().Equals("status", api.ST_STATUS_READY).Equals("enabled", true).LT("next_time", timeScope.End).IsFalse("is_expired")
  516. sts := make([]SScheduledTask, 0, 5)
  517. err := db.FetchModelObjects(stm, q, &sts)
  518. if err != nil {
  519. log.Errorf("db.FetchModelObjects error: %s", err.Error())
  520. return
  521. }
  522. log.Debugf("timeScope: start: %s, end: %s", timeScope.Start, timeScope.End)
  523. waitQueue := make(chan struct{}, len(sts))
  524. for i := range sts {
  525. log.Infof("sts[%d]: %s", i, jsonutils.Marshal(sts[i]))
  526. // 对于关联资源为空或获取关联资源异常的定时任务,不执行
  527. lables, err := sts[i].Labels()
  528. if err != nil {
  529. log.Errorf("scheduled_task get lables error:%s", err.Error())
  530. continue
  531. }
  532. if len(lables) == 0 {
  533. log.Errorf("scheduled_task %s lables not found:", sts[i].Id)
  534. continue
  535. }
  536. st := sts[i]
  537. timerQueue <- struct{}{}
  538. waitQueue <- struct{}{}
  539. go func(ctx context.Context) {
  540. defer func() {
  541. <-timerQueue
  542. <-waitQueue
  543. }()
  544. if st.NextTime.Before(timeScope.Start) {
  545. // For unknown reasons, the scalingTimer did not execute at the specified time
  546. st.Update(timeScope.Start)
  547. // scalingTimer should not exec for now.
  548. if st.NextTime.After(timeScope.End) || st.IsExpired {
  549. err = stm.TableSpec().InsertOrUpdate(ctx, &st)
  550. if err != nil {
  551. log.Errorf("update Scheduled task whose id is %s error: %s", st.Id, err.Error())
  552. }
  553. return
  554. }
  555. }
  556. err := st.Execute(ctx, userCred)
  557. if err != nil {
  558. log.Errorf("unable to execute scheduled task '%s'", st.Id)
  559. }
  560. st.Update(timeScope.End)
  561. err = stm.TableSpec().InsertOrUpdate(ctx, &st)
  562. if err != nil {
  563. log.Errorf("update Scheduled task whose id is %s error: %s", st.Id, err.Error())
  564. }
  565. }(ctx)
  566. }
  567. // wait all finish
  568. for i := 0; i < len(sts); i++ {
  569. waitQueue <- struct{}{}
  570. }
  571. }
  572. func init() {
  573. Register(ResourceServer, compute.Servers.ResourceManager)
  574. Register(ResourceCloudAccount, compute.Cloudaccounts.ResourceManager)
  575. }
  576. // Modules describe the correspondence between Resource and modulebase.ResourceManager,
  577. // which is equivalent to onecloud resource client.
  578. var Modules = make(map[Resource]modulebase.ResourceManager)
  579. // Every Resource should call Register to register their modulebase.ResourceManager.
  580. func Register(resource Resource, manager modulebase.ResourceManager) {
  581. Modules[resource] = manager
  582. }
  583. // Resoruce describe a onecloud resource, such as:
  584. type Resource string
  585. const (
  586. ResourceServer Resource = api.ST_RESOURCE_SERVER
  587. ResourceCloudAccount Resource = api.ST_RESOURCE_CLOUDACCOUNT
  588. )
  589. // ResourceOperation describe the operation for onecloud resource like create, update, delete and so on.
  590. type ResourceOperation struct {
  591. Resource Resource
  592. Operation string
  593. StatusSuccess []string
  594. Fail []ResourceOperationFail
  595. Params *jsonutils.JSONDict
  596. }
  597. type ResourceOperationFail struct {
  598. Status string
  599. LogEvent string
  600. }
  601. // It is clearer to write each ResourceOperation as a constant
  602. func init() {
  603. ServerStart = ResourceOperation{
  604. Resource: ResourceServer,
  605. Operation: api.ST_RESOURCE_OPERATION_START,
  606. StatusSuccess: []string{comapi.VM_RUNNING},
  607. Fail: []ResourceOperationFail{
  608. {comapi.VM_START_FAILED, db.ACT_START_FAIL},
  609. },
  610. }
  611. ServerStop = ResourceOperation{
  612. Resource: ResourceServer,
  613. Operation: api.ST_RESOURCE_OPERATION_STOP,
  614. StatusSuccess: []string{comapi.VM_READY},
  615. Fail: []ResourceOperationFail{
  616. {comapi.VM_STOP_FAILED, db.ACT_STOP_FAIL},
  617. },
  618. }
  619. ServerRestart = ResourceOperation{
  620. Resource: ResourceServer,
  621. Operation: api.ST_RESOURCE_OPERATION_RESTART,
  622. StatusSuccess: []string{comapi.VM_RUNNING},
  623. Fail: []ResourceOperationFail{
  624. {comapi.VM_START_FAILED, db.ACT_START_FAIL},
  625. {comapi.VM_STOP_FAILED, db.ACT_STOP_FAIL},
  626. },
  627. }
  628. paramsAccoutSync := jsonutils.NewDict()
  629. paramsAccoutSync.Add(jsonutils.JSONTrue, "full_sync")
  630. paramsAccoutSync.Add(jsonutils.JSONTrue, "force")
  631. CloudAccountSync = ResourceOperation{
  632. Resource: ResourceCloudAccount,
  633. Operation: api.ST_RESOURCE_OPERATION_SYNC,
  634. Params: paramsAccoutSync,
  635. }
  636. ResourceOperationMap = map[string]ResourceOperation{
  637. fmt.Sprintf("%s.%s", ResourceServer, api.ST_RESOURCE_OPERATION_START): ServerStart,
  638. fmt.Sprintf("%s.%s", ResourceServer, api.ST_RESOURCE_OPERATION_STOP): ServerStop,
  639. fmt.Sprintf("%s.%s", ResourceServer, api.ST_RESOURCE_OPERATION_RESTART): ServerRestart,
  640. fmt.Sprintf("%s.%s", ResourceCloudAccount, api.ST_RESOURCE_OPERATION_SYNC): CloudAccountSync,
  641. }
  642. }
  643. var (
  644. ServerStart ResourceOperation
  645. ServerStop ResourceOperation
  646. ServerRestart ResourceOperation
  647. CloudAccountSync ResourceOperation
  648. ResourceOperationMap map[string]ResourceOperation
  649. )
  650. // Action itself is meaningless, a meaningful Action is generated by
  651. // calling Resource, Operation, Session and DefaultParams.
  652. // A example:
  653. //
  654. // Action.ResourceOperation(ServerStart).Session(...).Apply(...)
  655. var Action = SAction{timeout: 5 * time.Minute}
  656. // SAction encapsulates action to for onecloud resources
  657. type SAction struct {
  658. operation ResourceOperation
  659. session *mcclient.ClientSession
  660. timeout time.Duration
  661. }
  662. func (r SAction) ResourceOperation(oper ResourceOperation) SAction {
  663. r.operation = oper
  664. return r
  665. }
  666. func (r SAction) Session(session *mcclient.ClientSession) SAction {
  667. r.session = session
  668. return r
  669. }
  670. func (r SAction) Timeout(time time.Duration) SAction {
  671. r.timeout = time
  672. return r
  673. }
  674. type WrapperListOptions struct {
  675. options.BaseListOptions
  676. }
  677. func (r SAction) List(opts *WrapperListOptions) (map[string]string, error) {
  678. resourceManager, ok := Modules[r.operation.Resource]
  679. if !ok {
  680. return nil, errors.Errorf("no such resource '%s' in Modules", r.operation.Resource)
  681. }
  682. params, err := options.ListStructToParams(opts)
  683. if err != nil {
  684. return nil, err
  685. }
  686. ret, err := resourceManager.List(r.session, params)
  687. if err != nil {
  688. return nil, err
  689. }
  690. out := make(map[string]string, len(ret.Data))
  691. for i := range ret.Data {
  692. id, _ := ret.Data[i].GetString("id")
  693. name, _ := ret.Data[i].GetString("name")
  694. out[id] = name
  695. }
  696. return out, nil
  697. }
  698. func (r SAction) Apply(id string) (success bool, failReason string) {
  699. success = true
  700. resourceManager, ok := Modules[r.operation.Resource]
  701. if !ok {
  702. return false, fmt.Sprintf("no such resource '%s' in Modules", r.operation.Resource)
  703. }
  704. var requestFunc func(session *mcclient.ClientSession, id string, params *jsonutils.JSONDict) error
  705. action := utils.CamelSplit(r.operation.Operation, "-")
  706. requestFunc = func(session *mcclient.ClientSession, id string, params *jsonutils.JSONDict) error {
  707. if params == nil {
  708. params = jsonutils.NewDict()
  709. }
  710. _, err := resourceManager.PerformAction(session, id, action, params)
  711. return err
  712. }
  713. err := requestFunc(r.session, id, r.operation.Params)
  714. if err != nil {
  715. clientErr, _ := err.(*httputils.JSONClientError)
  716. return false, clientErr.Details
  717. }
  718. if len(r.operation.StatusSuccess) == 0 {
  719. return true, ""
  720. }
  721. // wait for status
  722. timer := time.NewTimer(r.timeout)
  723. ticker := time.NewTicker(10 * time.Second)
  724. defer func() {
  725. ticker.Stop()
  726. timer.Stop()
  727. }()
  728. for {
  729. select {
  730. default:
  731. ret, e := resourceManager.GetSpecific(r.session, id, "status", nil)
  732. if e != nil {
  733. log.Errorf("fail to exec resouce(%s.%s).GetStatus: %s", r.operation.Resource, id, e.Error())
  734. <-ticker.C
  735. continue
  736. }
  737. status, _ := ret.GetString("status")
  738. if utils.IsInStringArray(status, r.operation.StatusSuccess) {
  739. return
  740. }
  741. for _, fail := range r.operation.Fail {
  742. if status != fail.Status {
  743. continue
  744. }
  745. params := jsonutils.NewDict()
  746. params.Add(jsonutils.NewString(id), "obj_id")
  747. params.Add(jsonutils.NewStringArray([]string{fail.LogEvent}), "action")
  748. params.Add(jsonutils.NewInt(1), "limit")
  749. events, err := compute.Logs.List(r.session, params)
  750. if err != nil {
  751. log.Errorf("Logs.List failed: %s", err.Error())
  752. <-ticker.C
  753. continue
  754. }
  755. if len(events.Data) == 0 {
  756. log.Errorf("These is no opslog about action '%s' for %s.%s: %s", fail.LogEvent, r.operation.Resource, id, err.Error())
  757. <-ticker.C
  758. continue
  759. }
  760. reason, _ := events.Data[0].GetString("notes")
  761. return false, reason
  762. }
  763. <-ticker.C
  764. case <-timer.C:
  765. log.Errorf("timeout(%s) to exec resource(%s.%s).%s", r.timeout.String(), r.operation.Resource, id, r.operation.Operation)
  766. return false, "timeout"
  767. }
  768. }
  769. }