func_provider.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package interpreter
  11. import (
  12. "fmt"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "devt.de/krotik/common/errorutil"
  17. "devt.de/krotik/common/timeutil"
  18. "devt.de/krotik/ecal/engine"
  19. "devt.de/krotik/ecal/parser"
  20. "devt.de/krotik/ecal/scope"
  21. "devt.de/krotik/ecal/stdlib"
  22. "devt.de/krotik/ecal/util"
  23. )
  24. /*
  25. InbuildFuncMap contains the mapping of inbuild functions.
  26. */
  27. var InbuildFuncMap = map[string]util.ECALFunction{
  28. "range": &rangeFunc{&inbuildBaseFunc{}},
  29. "new": &newFunc{&inbuildBaseFunc{}},
  30. "len": &lenFunc{&inbuildBaseFunc{}},
  31. "del": &delFunc{&inbuildBaseFunc{}},
  32. "add": &addFunc{&inbuildBaseFunc{}},
  33. "concat": &concatFunc{&inbuildBaseFunc{}},
  34. "dumpenv": &dumpenvFunc{&inbuildBaseFunc{}},
  35. "doc": &docFunc{&inbuildBaseFunc{}},
  36. "raise": &raise{&inbuildBaseFunc{}},
  37. "addEvent": &addevent{&inbuildBaseFunc{}},
  38. "addEventAndWait": &addeventandwait{&addevent{&inbuildBaseFunc{}}},
  39. "setCronTrigger": &setCronTrigger{&inbuildBaseFunc{}},
  40. "setPulseTrigger": &setPulseTrigger{&inbuildBaseFunc{}},
  41. }
  42. /*
  43. inbuildBaseFunc is the base structure for inbuild functions providing some
  44. utility functions.
  45. */
  46. type inbuildBaseFunc struct {
  47. }
  48. /*
  49. AssertNumParam converts a general interface{} parameter into a number.
  50. */
  51. func (ibf *inbuildBaseFunc) AssertNumParam(index int, val interface{}) (float64, error) {
  52. var err error
  53. resNum, ok := val.(float64)
  54. if !ok {
  55. resNum, err = strconv.ParseFloat(fmt.Sprint(val), 64)
  56. if err != nil {
  57. err = fmt.Errorf("Parameter %v should be a number", index)
  58. }
  59. }
  60. return resNum, err
  61. }
  62. /*
  63. AssertMapParam converts a general interface{} parameter into a map.
  64. */
  65. func (ibf *inbuildBaseFunc) AssertMapParam(index int, val interface{}) (map[interface{}]interface{}, error) {
  66. valMap, ok := val.(map[interface{}]interface{})
  67. if ok {
  68. return valMap, nil
  69. }
  70. return nil, fmt.Errorf("Parameter %v should be a map", index)
  71. }
  72. /*
  73. AssertListParam converts a general interface{} parameter into a list.
  74. */
  75. func (ibf *inbuildBaseFunc) AssertListParam(index int, val interface{}) ([]interface{}, error) {
  76. valList, ok := val.([]interface{})
  77. if ok {
  78. return valList, nil
  79. }
  80. return nil, fmt.Errorf("Parameter %v should be a list", index)
  81. }
  82. // Range
  83. // =====
  84. /*
  85. rangeFunc is an interator function which returns a range of numbers.
  86. */
  87. type rangeFunc struct {
  88. *inbuildBaseFunc
  89. }
  90. /*
  91. Run executes this function.
  92. */
  93. func (rf *rangeFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  94. var currVal, to float64
  95. var err error
  96. lenargs := len(args)
  97. from := 0.
  98. step := 1.
  99. if lenargs == 0 {
  100. err = fmt.Errorf("Need at least an end range as first parameter")
  101. }
  102. if err == nil {
  103. if stepVal, ok := is[instanceID+"step"]; ok {
  104. step = stepVal.(float64)
  105. from = is[instanceID+"from"].(float64)
  106. to = is[instanceID+"to"].(float64)
  107. currVal = is[instanceID+"currVal"].(float64)
  108. is[instanceID+"currVal"] = currVal + step
  109. // Check for end of iteration
  110. if (from < to && currVal > to) || (from > to && currVal < to) || from == to {
  111. err = util.ErrEndOfIteration
  112. }
  113. } else {
  114. if lenargs == 1 {
  115. to, err = rf.AssertNumParam(1, args[0])
  116. } else {
  117. from, err = rf.AssertNumParam(1, args[0])
  118. if err == nil {
  119. to, err = rf.AssertNumParam(2, args[1])
  120. }
  121. if err == nil && lenargs > 2 {
  122. step, err = rf.AssertNumParam(3, args[2])
  123. }
  124. }
  125. if err == nil {
  126. is[instanceID+"from"] = from
  127. is[instanceID+"to"] = to
  128. is[instanceID+"step"] = step
  129. is[instanceID+"currVal"] = from
  130. currVal = from
  131. }
  132. }
  133. }
  134. if err == nil {
  135. err = util.ErrIsIterator // Identify as iterator
  136. }
  137. return currVal, err
  138. }
  139. /*
  140. DocString returns a descriptive string.
  141. */
  142. func (rf *rangeFunc) DocString() (string, error) {
  143. return "Range function which can be used to iterate over number ranges. Parameters are start, end and step.", nil
  144. }
  145. // New
  146. // ===
  147. /*
  148. newFunc instantiates a new object.
  149. */
  150. type newFunc struct {
  151. *inbuildBaseFunc
  152. }
  153. /*
  154. Run executes this function.
  155. */
  156. func (rf *newFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  157. var res interface{}
  158. err := fmt.Errorf("Need a map as first parameter")
  159. if len(args) > 0 {
  160. var argMap map[interface{}]interface{}
  161. if argMap, err = rf.AssertMapParam(1, args[0]); err == nil {
  162. obj := make(map[interface{}]interface{})
  163. res = obj
  164. _, err = rf.addSuperClasses(vs, is, obj, argMap)
  165. if initObj, ok := obj["init"]; ok {
  166. if initFunc, ok := initObj.(*function); ok {
  167. initvs := scope.NewScope(fmt.Sprintf("newfunc: %v", instanceID))
  168. initis := make(map[string]interface{})
  169. _, err = initFunc.Run(instanceID, initvs, initis, args[1:])
  170. }
  171. }
  172. }
  173. }
  174. return res, err
  175. }
  176. /*
  177. addSuperClasses adds super class functions to a given object.
  178. */
  179. func (rf *newFunc) addSuperClasses(vs parser.Scope, is map[string]interface{},
  180. obj map[interface{}]interface{}, template map[interface{}]interface{}) (interface{}, error) {
  181. var err error
  182. var initFunc interface{}
  183. var initSuperList []interface{}
  184. // First loop into the base classes (i.e. top-most classes)
  185. if super, ok := template["super"]; ok {
  186. if superList, ok := super.([]interface{}); ok {
  187. for _, superObj := range superList {
  188. var superInit interface{}
  189. if superTemplate, ok := superObj.(map[interface{}]interface{}); ok {
  190. superInit, err = rf.addSuperClasses(vs, is, obj, superTemplate)
  191. initSuperList = append(initSuperList, superInit) // Build up the list of super functions
  192. }
  193. }
  194. } else {
  195. err = fmt.Errorf("Property _super must be a list of super classes")
  196. }
  197. }
  198. // Copy all properties from template to obj
  199. for k, v := range template {
  200. // Save previous init function
  201. if funcVal, ok := v.(*function); ok {
  202. newFunction := &function{funcVal.name, nil, obj, funcVal.declaration, funcVal.declarationVS}
  203. if k == "init" {
  204. newFunction.super = initSuperList
  205. initFunc = newFunction
  206. }
  207. obj[k] = newFunction
  208. } else {
  209. obj[k] = v
  210. }
  211. }
  212. return initFunc, err
  213. }
  214. /*
  215. DocString returns a descriptive string.
  216. */
  217. func (rf *newFunc) DocString() (string, error) {
  218. return "New creates a new object instance.", nil
  219. }
  220. // Len
  221. // ===
  222. /*
  223. lenFunc returns the size of a list or map.
  224. */
  225. type lenFunc struct {
  226. *inbuildBaseFunc
  227. }
  228. /*
  229. Run executes this function.
  230. */
  231. func (rf *lenFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  232. var res float64
  233. err := fmt.Errorf("Need a list or a map as first parameter")
  234. if len(args) > 0 {
  235. argList, ok1 := args[0].([]interface{})
  236. argMap, ok2 := args[0].(map[interface{}]interface{})
  237. if ok1 {
  238. res = float64(len(argList))
  239. err = nil
  240. } else if ok2 {
  241. res = float64(len(argMap))
  242. err = nil
  243. }
  244. }
  245. return res, err
  246. }
  247. /*
  248. DocString returns a descriptive string.
  249. */
  250. func (rf *lenFunc) DocString() (string, error) {
  251. return "Len returns the size of a list or map.", nil
  252. }
  253. // Del
  254. // ===
  255. /*
  256. delFunc removes an element from a list or map.
  257. */
  258. type delFunc struct {
  259. *inbuildBaseFunc
  260. }
  261. /*
  262. Run executes this function.
  263. */
  264. func (rf *delFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  265. var res interface{}
  266. err := fmt.Errorf("Need a list or a map as first parameter and an index or key as second parameter")
  267. if len(args) == 2 {
  268. if argList, ok1 := args[0].([]interface{}); ok1 {
  269. var index float64
  270. index, err = rf.AssertNumParam(2, args[1])
  271. if err == nil {
  272. res = append(argList[:int(index)], argList[int(index+1):]...)
  273. }
  274. }
  275. if argMap, ok2 := args[0].(map[interface{}]interface{}); ok2 {
  276. key := fmt.Sprint(args[1])
  277. delete(argMap, key)
  278. res = argMap
  279. err = nil
  280. }
  281. }
  282. return res, err
  283. }
  284. /*
  285. DocString returns a descriptive string.
  286. */
  287. func (rf *delFunc) DocString() (string, error) {
  288. return "Del removes an item from a list or map.", nil
  289. }
  290. // Add
  291. // ===
  292. /*
  293. addFunc adds an element to a list.
  294. */
  295. type addFunc struct {
  296. *inbuildBaseFunc
  297. }
  298. /*
  299. Run executes this function.
  300. */
  301. func (rf *addFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  302. var res interface{}
  303. err := fmt.Errorf("Need a list as first parameter and a value as second parameter")
  304. if len(args) > 1 {
  305. var argList []interface{}
  306. if argList, err = rf.AssertListParam(1, args[0]); err == nil {
  307. if len(args) == 3 {
  308. var index float64
  309. if index, err = rf.AssertNumParam(3, args[2]); err == nil {
  310. argList = append(argList, 0)
  311. copy(argList[int(index+1):], argList[int(index):])
  312. argList[int(index)] = args[1]
  313. res = argList
  314. }
  315. } else {
  316. res = append(argList, args[1])
  317. }
  318. }
  319. }
  320. return res, err
  321. }
  322. /*
  323. DocString returns a descriptive string.
  324. */
  325. func (rf *addFunc) DocString() (string, error) {
  326. return "Add adds an item to a list. The item is added at the optionally given index or at the end if no index is specified.", nil
  327. }
  328. // Concat
  329. // ======
  330. /*
  331. concatFunc joins one or more lists together.
  332. */
  333. type concatFunc struct {
  334. *inbuildBaseFunc
  335. }
  336. /*
  337. Run executes this function.
  338. */
  339. func (rf *concatFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  340. var res interface{}
  341. err := fmt.Errorf("Need at least two lists as parameters")
  342. if len(args) > 1 {
  343. var argList []interface{}
  344. resList := make([]interface{}, 0)
  345. err = nil
  346. for _, a := range args {
  347. if err == nil {
  348. if argList, err = rf.AssertListParam(1, a); err == nil {
  349. resList = append(resList, argList...)
  350. }
  351. }
  352. }
  353. if err == nil {
  354. res = resList
  355. }
  356. }
  357. return res, err
  358. }
  359. /*
  360. DocString returns a descriptive string.
  361. */
  362. func (rf *concatFunc) DocString() (string, error) {
  363. return "Concat joins one or more lists together. The result is a new list.", nil
  364. }
  365. // dumpenv
  366. // =======
  367. /*
  368. dumpenvFunc returns the current variable environment as a string.
  369. */
  370. type dumpenvFunc struct {
  371. *inbuildBaseFunc
  372. }
  373. /*
  374. Run executes this function.
  375. */
  376. func (rf *dumpenvFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  377. return vs.String(), nil
  378. }
  379. /*
  380. DocString returns a descriptive string.
  381. */
  382. func (rf *dumpenvFunc) DocString() (string, error) {
  383. return "Dumpenv returns the current variable environment as a string.", nil
  384. }
  385. // doc
  386. // ===
  387. /*
  388. docFunc returns the docstring of a function.
  389. */
  390. type docFunc struct {
  391. *inbuildBaseFunc
  392. }
  393. /*
  394. Run executes this function.
  395. */
  396. func (rf *docFunc) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  397. var res interface{}
  398. err := fmt.Errorf("Need a function as parameter")
  399. if len(args) > 0 {
  400. funcObj, ok := args[0].(util.ECALFunction)
  401. if args[0] == nil {
  402. // Try to lookup by the given identifier
  403. c := is["astnode"].(*parser.ASTNode).Children[0].Children[0]
  404. astring := c.Token.Val
  405. if len(c.Children) > 0 {
  406. astring = fmt.Sprintf("%v.%v", astring, c.Children[0].Token.Val)
  407. }
  408. // Check for stdlib function
  409. if funcObj, ok = stdlib.GetStdlibFunc(astring); !ok {
  410. // Check for inbuild function
  411. funcObj, ok = InbuildFuncMap[astring]
  412. }
  413. }
  414. if ok {
  415. res, err = funcObj.DocString()
  416. }
  417. }
  418. return res, err
  419. }
  420. /*
  421. DocString returns a descriptive string.
  422. */
  423. func (rf *docFunc) DocString() (string, error) {
  424. return "Doc returns the docstring of a function.", nil
  425. }
  426. // raise
  427. // =====
  428. /*
  429. raise returns an error. Outside of sinks this will stop the code execution
  430. if the error is not handled by try / except. Inside a sink only the specific sink
  431. will fail. This error can be used to break trigger sequences of sinks if
  432. FailOnFirstErrorInTriggerSequence is set.
  433. */
  434. type raise struct {
  435. *inbuildBaseFunc
  436. }
  437. /*
  438. Run executes this function.
  439. */
  440. func (rf *raise) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  441. var err error
  442. var detailMsg string
  443. var detail interface{}
  444. if len(args) > 0 {
  445. err = fmt.Errorf("%v", args[0])
  446. if len(args) > 1 {
  447. if args[1] != nil {
  448. detailMsg = fmt.Sprint(args[1])
  449. }
  450. if len(args) > 2 {
  451. detail = args[2]
  452. }
  453. }
  454. }
  455. erp := is["erp"].(*ECALRuntimeProvider)
  456. node := is["astnode"].(*parser.ASTNode)
  457. return nil, &util.RuntimeErrorWithDetail{
  458. RuntimeError: erp.NewRuntimeError(err, detailMsg, node).(*util.RuntimeError),
  459. Environment: vs,
  460. Data: detail,
  461. }
  462. }
  463. /*
  464. DocString returns a descriptive string.
  465. */
  466. func (rf *raise) DocString() (string, error) {
  467. return "Raise returns an error object.", nil
  468. }
  469. // addEvent
  470. // ========
  471. /*
  472. addevent adds an event to trigger sinks. This function will return immediately
  473. and not wait for the event cascade to finish. Use this function for event cascades.
  474. */
  475. type addevent struct {
  476. *inbuildBaseFunc
  477. }
  478. /*
  479. Run executes this function.
  480. */
  481. func (rf *addevent) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  482. return rf.addEvent(func(proc engine.Processor, event *engine.Event, scope *engine.RuleScope) (interface{}, error) {
  483. var monitor engine.Monitor
  484. parentMonitor, ok := is["monitor"]
  485. if scope != nil || !ok {
  486. monitor = proc.NewRootMonitor(nil, scope)
  487. } else {
  488. monitor = parentMonitor.(engine.Monitor).NewChildMonitor(0)
  489. }
  490. _, err := proc.AddEvent(event, monitor)
  491. return nil, err
  492. }, is, args)
  493. }
  494. func (rf *addevent) addEvent(addFunc func(engine.Processor, *engine.Event, *engine.RuleScope) (interface{}, error),
  495. is map[string]interface{}, args []interface{}) (interface{}, error) {
  496. var res interface{}
  497. var stateMap map[interface{}]interface{}
  498. erp := is["erp"].(*ECALRuntimeProvider)
  499. proc := erp.Processor
  500. if proc.Stopped() {
  501. proc.Start()
  502. }
  503. err := fmt.Errorf("Need at least three parameters: name, kind and state")
  504. if len(args) > 2 {
  505. if stateMap, err = rf.AssertMapParam(3, args[2]); err == nil {
  506. var scope *engine.RuleScope
  507. event := engine.NewEvent(
  508. fmt.Sprint(args[0]),
  509. strings.Split(fmt.Sprint(args[1]), "."),
  510. stateMap,
  511. )
  512. if len(args) > 3 {
  513. var scopeMap map[interface{}]interface{}
  514. // Add optional scope - if not specified it is { "": true }
  515. if scopeMap, err = rf.AssertMapParam(4, args[3]); err == nil {
  516. var scopeData = map[string]bool{}
  517. for k, v := range scopeMap {
  518. b, _ := strconv.ParseBool(fmt.Sprint(v))
  519. scopeData[fmt.Sprint(k)] = b
  520. }
  521. scope = engine.NewRuleScope(scopeData)
  522. }
  523. }
  524. if err == nil {
  525. res, err = addFunc(proc, event, scope)
  526. }
  527. }
  528. }
  529. return res, err
  530. }
  531. /*
  532. DocString returns a descriptive string.
  533. */
  534. func (rf *addevent) DocString() (string, error) {
  535. return "AddEvent adds an event to trigger sinks. This function will return " +
  536. "immediately and not wait for the event cascade to finish.", nil
  537. }
  538. // addEventAndWait
  539. // ===============
  540. /*
  541. addeventandwait adds an event to trigger sinks. This function will return once
  542. the event cascade has finished and return all errors.
  543. */
  544. type addeventandwait struct {
  545. *addevent
  546. }
  547. /*
  548. Run executes this function.
  549. */
  550. func (rf *addeventandwait) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  551. return rf.addEvent(func(proc engine.Processor, event *engine.Event, scope *engine.RuleScope) (interface{}, error) {
  552. var res []interface{}
  553. rm := proc.NewRootMonitor(nil, scope)
  554. m, err := proc.AddEventAndWait(event, rm)
  555. if m != nil {
  556. allErrors := m.(*engine.RootMonitor).AllErrors()
  557. for _, e := range allErrors {
  558. errors := map[interface{}]interface{}{}
  559. for k, v := range e.ErrorMap {
  560. se := v.(*util.RuntimeErrorWithDetail)
  561. // Note: The variable scope of the sink (se.environment)
  562. // was also captured - for now it is not exposed to the
  563. // language environment
  564. errors[k] = map[interface{}]interface{}{
  565. "error": se.Error(),
  566. "type": se.Type.Error(),
  567. "detail": se.Detail,
  568. "data": se.Data,
  569. }
  570. }
  571. item := map[interface{}]interface{}{
  572. "event": map[interface{}]interface{}{
  573. "name": e.Event.Name(),
  574. "kind": strings.Join(e.Event.Kind(), "."),
  575. "state": e.Event.State(),
  576. },
  577. "errors": errors,
  578. }
  579. res = append(res, item)
  580. }
  581. }
  582. return res, err
  583. }, is, args)
  584. }
  585. /*
  586. DocString returns a descriptive string.
  587. */
  588. func (rf *addeventandwait) DocString() (string, error) {
  589. return "AddEventAndWait adds an event to trigger sinks. This function will " +
  590. "return once the event cascade has finished.", nil
  591. }
  592. // setCronTrigger
  593. // ==============
  594. /*
  595. setCronTrigger adds a periodic cron job which fires events.
  596. */
  597. type setCronTrigger struct {
  598. *inbuildBaseFunc
  599. }
  600. /*
  601. Run executes this function.
  602. */
  603. func (ct *setCronTrigger) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  604. var res interface{}
  605. err := fmt.Errorf("Need a cronspec, an event name and an event scope as parameters")
  606. if len(args) > 2 {
  607. var cs *timeutil.CronSpec
  608. cronspec := fmt.Sprint(args[0])
  609. eventname := fmt.Sprint(args[1])
  610. eventkind := strings.Split(fmt.Sprint(args[2]), ".")
  611. erp := is["erp"].(*ECALRuntimeProvider)
  612. proc := erp.Processor
  613. if proc.Stopped() {
  614. proc.Start()
  615. }
  616. if cs, err = timeutil.NewCronSpec(cronspec); err == nil {
  617. res = cs.String()
  618. tick := 0
  619. erp.Cron.RegisterSpec(cs, func() {
  620. tick += 1
  621. now := erp.Cron.NowFunc()
  622. event := engine.NewEvent(eventname, eventkind, map[interface{}]interface{}{
  623. "time": now,
  624. "timestamp": fmt.Sprintf("%d", now.UnixNano()/int64(time.Millisecond)),
  625. "tick": float64(tick),
  626. })
  627. monitor := proc.NewRootMonitor(nil, nil)
  628. _, err := proc.AddEvent(event, monitor)
  629. errorutil.AssertTrue(err == nil,
  630. fmt.Sprintf("Could not add cron event for trigger %v %v %v: %v",
  631. cronspec, eventname, eventkind, err))
  632. })
  633. }
  634. }
  635. return res, err
  636. }
  637. /*
  638. DocString returns a descriptive string.
  639. */
  640. func (ct *setCronTrigger) DocString() (string, error) {
  641. return "setCronTrigger adds a periodic cron job which fires events.", nil
  642. }
  643. // setPulseTrigger
  644. // ==============
  645. /*
  646. setPulseTrigger adds recurring events in very short intervals.
  647. */
  648. type setPulseTrigger struct {
  649. *inbuildBaseFunc
  650. }
  651. /*
  652. Run executes this function.
  653. */
  654. func (pt *setPulseTrigger) Run(instanceID string, vs parser.Scope, is map[string]interface{}, args []interface{}) (interface{}, error) {
  655. err := fmt.Errorf("Need micro second interval, an event name and an event scope as parameters")
  656. if len(args) > 2 {
  657. var micros float64
  658. micros, err = pt.AssertNumParam(1, args[0])
  659. if err == nil {
  660. eventname := fmt.Sprint(args[1])
  661. eventkind := strings.Split(fmt.Sprint(args[2]), ".")
  662. erp := is["erp"].(*ECALRuntimeProvider)
  663. proc := erp.Processor
  664. if proc.Stopped() {
  665. proc.Start()
  666. }
  667. tick := 0
  668. go func() {
  669. var lastmicros int64
  670. for {
  671. time.Sleep(time.Duration(micros) * time.Microsecond)
  672. tick += 1
  673. now := time.Now()
  674. micros := now.UnixNano() / int64(time.Microsecond)
  675. event := engine.NewEvent(eventname, eventkind, map[interface{}]interface{}{
  676. "currentMicros": float64(micros),
  677. "lastMicros": float64(lastmicros),
  678. "timestamp": fmt.Sprintf("%d", now.UnixNano()/int64(time.Microsecond)),
  679. "tick": float64(tick),
  680. })
  681. lastmicros = micros
  682. monitor := proc.NewRootMonitor(nil, nil)
  683. _, err := proc.AddEvent(event, monitor)
  684. if proc.Stopped() {
  685. break
  686. }
  687. errorutil.AssertTrue(err == nil,
  688. fmt.Sprintf("Could not add pulse event for trigger %v %v %v: %v",
  689. micros, eventname, eventkind, err))
  690. }
  691. }()
  692. }
  693. }
  694. return nil, err
  695. }
  696. /*
  697. DocString returns a descriptive string.
  698. */
  699. func (pt *setPulseTrigger) DocString() (string, error) {
  700. return "setPulseTrigger adds recurring events in microsecond intervals.", nil
  701. }