executor.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. package executor
  2. import (
  3. acl "github.com/OliveTin/OliveTin/internal/acl"
  4. config "github.com/OliveTin/OliveTin/internal/config"
  5. "github.com/OliveTin/OliveTin/internal/entities"
  6. "github.com/google/uuid"
  7. log "github.com/sirupsen/logrus"
  8. "github.com/prometheus/client_golang/prometheus"
  9. "github.com/prometheus/client_golang/prometheus/promauto"
  10. "gopkg.in/yaml.v3"
  11. "bytes"
  12. "context"
  13. "fmt"
  14. "os"
  15. "os/exec"
  16. "path"
  17. "strings"
  18. "sync"
  19. "time"
  20. )
  21. const (
  22. DefaultExitCodeNotExecuted = -1337
  23. MaxTriggerDepth = 10
  24. )
  25. var (
  26. metricActionsRequested = promauto.NewCounter(prometheus.CounterOpts{
  27. Name: "olivetin_actions_requested_count",
  28. Help: "The actions requested count",
  29. })
  30. )
  31. type ActionBinding struct {
  32. ID string
  33. Action *config.Action
  34. Entity *entities.Entity
  35. ConfigOrder int
  36. IsOnDashboard bool
  37. }
  38. // Executor represents a helper class for executing commands. It's main method
  39. // is ExecRequest
  40. type Executor struct {
  41. logs map[string]*InternalLogEntry
  42. logsTrackingIdsByDate []string
  43. LogsByActionId map[string][]*InternalLogEntry
  44. logmutex sync.RWMutex
  45. MapActionIdToBinding map[string]*ActionBinding
  46. MapActionIdToBindingLock sync.RWMutex
  47. Cfg *config.Config
  48. listeners []listener
  49. chainOfCommand []executorStepFunc
  50. }
  51. // ExecutionRequest is a request to execute an action. It's passed to an
  52. // Executor. They're created from the api.
  53. type ExecutionRequest struct {
  54. Binding *ActionBinding
  55. Arguments map[string]string
  56. TrackingID string
  57. Tags []string
  58. Cfg *config.Config
  59. AuthenticatedUser *acl.AuthenticatedUser
  60. TriggerDepth int
  61. logEntry *InternalLogEntry
  62. finalParsedCommand string
  63. execArgs []string
  64. useDirectExec bool
  65. executor *Executor
  66. }
  67. // InternalLogEntry objects are created by an Executor, and represent the final
  68. // state of execution (even if the command is not executed). It's designed to be
  69. // easily serializable.
  70. type InternalLogEntry struct {
  71. Binding *ActionBinding
  72. BindingID string
  73. DatetimeStarted time.Time
  74. DatetimeFinished time.Time
  75. Output string
  76. TimedOut bool
  77. Blocked bool
  78. ExitCode int32
  79. Tags []string
  80. ExecutionStarted bool
  81. ExecutionFinished bool
  82. ExecutionTrackingID string
  83. Process *os.Process
  84. Username string
  85. Index int64
  86. EntityPrefix string
  87. ActionConfigTitle string // This is the title of the action as defined in the config, not the final parsed title.
  88. /*
  89. The following 3 properties are obviously on Action normally, but it's useful
  90. that logs are lightweight (so we don't need to have an action associated to
  91. logs, etc. Therefore, we duplicate those values here.
  92. */
  93. ActionTitle string
  94. ActionIcon string
  95. ActionId string
  96. }
  97. type executorStepFunc func(*ExecutionRequest) bool
  98. // DefaultExecutor returns an Executor, with a sensible "chain of command" for
  99. // executing actions.
  100. func DefaultExecutor(cfg *config.Config) *Executor {
  101. e := Executor{}
  102. e.Cfg = cfg
  103. e.logs = make(map[string]*InternalLogEntry)
  104. e.logsTrackingIdsByDate = make([]string, 0)
  105. e.LogsByActionId = make(map[string][]*InternalLogEntry)
  106. e.MapActionIdToBinding = make(map[string]*ActionBinding)
  107. e.chainOfCommand = []executorStepFunc{
  108. stepRequestAction,
  109. stepConcurrencyCheck,
  110. stepRateCheck,
  111. stepACLCheck,
  112. stepParseArgs,
  113. stepLogStart,
  114. stepExec,
  115. stepExecAfter,
  116. stepLogFinish,
  117. stepSaveLog,
  118. stepTrigger,
  119. }
  120. return &e
  121. }
  122. type listener interface {
  123. OnExecutionStarted(logEntry *InternalLogEntry)
  124. OnExecutionFinished(logEntry *InternalLogEntry)
  125. OnOutputChunk(o []byte, executionTrackingId string)
  126. OnActionMapRebuilt()
  127. }
  128. func (e *Executor) AddListener(m listener) {
  129. e.listeners = append(e.listeners, m)
  130. }
  131. // getPagingStartIndex calculates the starting index for log pagination.
  132. // Parameters:
  133. //
  134. // startOffset: The offset from the most recent log (0 means start from the most recent)
  135. // totalLogCount: Total number of logs available
  136. // count: Number of logs to retrieve
  137. //
  138. // Returns: The calculated starting index for pagination
  139. func getPagingStartIndex(startOffset int64, totalLogCount int64) int64 {
  140. var startIndex int64
  141. if startOffset <= 0 {
  142. startIndex = totalLogCount
  143. } else {
  144. startIndex = (totalLogCount - startOffset)
  145. if startIndex < 0 {
  146. startIndex = 1
  147. }
  148. }
  149. return startIndex - 1
  150. }
  151. type PagingResult struct {
  152. CountRemaining int64
  153. PageSize int64
  154. TotalCount int64
  155. StartOffset int64
  156. }
  157. func (e *Executor) GetLogTrackingIds(startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  158. pagingResult := &PagingResult{
  159. CountRemaining: 0,
  160. PageSize: pageCount,
  161. TotalCount: 0,
  162. StartOffset: startOffset,
  163. }
  164. e.logmutex.RLock()
  165. totalLogCount := int64(len(e.logsTrackingIdsByDate))
  166. pagingResult.TotalCount = totalLogCount
  167. startIndex := getPagingStartIndex(startOffset, totalLogCount)
  168. pageCount = min(totalLogCount, pageCount)
  169. endIndex := max(0, (startIndex-pageCount)+1)
  170. log.WithFields(log.Fields{
  171. "startOffset": startOffset,
  172. "pageCount": pageCount,
  173. "total": totalLogCount,
  174. "startIndex": startIndex,
  175. "endIndex": endIndex,
  176. }).Tracef("GetLogTrackingIds")
  177. trackingIds := make([]*InternalLogEntry, 0, pageCount)
  178. if totalLogCount > 0 {
  179. for i := endIndex; i <= startIndex; i++ {
  180. trackingIds = append(trackingIds, e.logs[e.logsTrackingIdsByDate[i]])
  181. }
  182. }
  183. e.logmutex.RUnlock()
  184. pagingResult.CountRemaining = endIndex
  185. return trackingIds, pagingResult
  186. }
  187. func (e *Executor) GetLog(trackingID string) (*InternalLogEntry, bool) {
  188. e.logmutex.RLock()
  189. entry, found := e.logs[trackingID]
  190. e.logmutex.RUnlock()
  191. return entry, found
  192. }
  193. func (e *Executor) GetLogsByActionId(actionId string) []*InternalLogEntry {
  194. e.logmutex.RLock()
  195. logs, found := e.LogsByActionId[actionId]
  196. e.logmutex.RUnlock()
  197. if !found {
  198. return make([]*InternalLogEntry, 0)
  199. }
  200. return logs
  201. }
  202. func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) {
  203. e.logmutex.Lock()
  204. entry.Index = int64(len(e.logsTrackingIdsByDate))
  205. e.logs[trackingID] = entry
  206. e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
  207. e.logmutex.Unlock()
  208. }
  209. // ExecRequest processes an ExecutionRequest
  210. func (e *Executor) ExecRequest(req *ExecutionRequest) (*sync.WaitGroup, string) {
  211. if req.AuthenticatedUser == nil {
  212. req.AuthenticatedUser = acl.UserGuest(req.Cfg)
  213. }
  214. req.executor = e
  215. req.logEntry = &InternalLogEntry{
  216. Binding: req.Binding,
  217. DatetimeStarted: time.Now(),
  218. ExecutionTrackingID: req.TrackingID,
  219. Output: "",
  220. ExitCode: DefaultExitCodeNotExecuted,
  221. ExecutionStarted: false,
  222. ExecutionFinished: false,
  223. ActionId: "",
  224. ActionTitle: "notfound",
  225. ActionIcon: "&#x1f4a9;",
  226. Username: req.AuthenticatedUser.Username,
  227. }
  228. _, isDuplicate := e.GetLog(req.TrackingID)
  229. if isDuplicate || req.TrackingID == "" {
  230. req.TrackingID = uuid.NewString()
  231. }
  232. // Update the log entry with the final tracking ID
  233. req.logEntry.ExecutionTrackingID = req.TrackingID
  234. log.Tracef("executor.ExecRequest(): %v", req)
  235. e.SetLog(req.TrackingID, req.logEntry)
  236. wg := new(sync.WaitGroup)
  237. wg.Add(1)
  238. go func() {
  239. e.execChain(req)
  240. defer wg.Done()
  241. }()
  242. return wg, req.TrackingID
  243. }
  244. func (e *Executor) execChain(req *ExecutionRequest) {
  245. for _, step := range e.chainOfCommand {
  246. if !step(req) {
  247. break
  248. }
  249. }
  250. req.logEntry.ExecutionFinished = true
  251. // This isn't a step, because we want to notify all listeners, irrespective
  252. // of how many steps were actually executed.
  253. notifyListenersFinished(req)
  254. }
  255. func getConcurrentCount(req *ExecutionRequest) int {
  256. concurrentCount := 0
  257. req.executor.logmutex.RLock()
  258. for _, log := range req.executor.GetLogsByActionId(req.Binding.Action.ID) {
  259. if !log.ExecutionFinished {
  260. concurrentCount += 1
  261. }
  262. }
  263. req.executor.logmutex.RUnlock()
  264. return concurrentCount
  265. }
  266. func stepConcurrencyCheck(req *ExecutionRequest) bool {
  267. concurrentCount := getConcurrentCount(req)
  268. // Note that the current execution is counted int the logs, so when checking we +1
  269. if concurrentCount >= (req.Binding.Action.MaxConcurrent + 1) {
  270. log.WithFields(log.Fields{
  271. "actionTitle": req.logEntry.ActionTitle,
  272. "concurrentCount": concurrentCount,
  273. "maxConcurrent": req.Binding.Action.MaxConcurrent,
  274. }).Warnf("Blocked from executing due to concurrency limit")
  275. req.logEntry.Output = "Blocked from executing due to concurrency limit"
  276. req.logEntry.Blocked = true
  277. return false
  278. }
  279. return true
  280. }
  281. func parseDuration(rate config.RateSpec) time.Duration {
  282. duration, err := time.ParseDuration(rate.Duration)
  283. if err != nil {
  284. log.Warnf("Could not parse duration: %v", rate.Duration)
  285. return -1 * time.Minute
  286. }
  287. return duration
  288. }
  289. //gocyclo:ignore
  290. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  291. executions := -1 // Because we will find ourself when checking execution logs
  292. duration := parseDuration(rate)
  293. then := time.Now().Add(-duration)
  294. for _, logEntry := range req.executor.GetLogsByActionId(req.Binding.Action.ID) {
  295. // FIXME
  296. /*
  297. if logEntry.EntityPrefix != req.EntityPrefix {
  298. continue
  299. }
  300. */
  301. if logEntry.DatetimeStarted.After(then) && !logEntry.Blocked {
  302. executions += 1
  303. }
  304. }
  305. return executions
  306. }
  307. func stepRateCheck(req *ExecutionRequest) bool {
  308. for _, rate := range req.Binding.Action.MaxRate {
  309. executions := getExecutionsCount(rate, req)
  310. if executions >= rate.Limit {
  311. log.WithFields(log.Fields{
  312. "actionTitle": req.logEntry.ActionTitle,
  313. "executions": executions,
  314. "limit": rate.Limit,
  315. "duration": rate.Duration,
  316. }).Infof("Blocked from executing due to rate limit")
  317. req.logEntry.Output = "Blocked from executing due to rate limit"
  318. req.logEntry.Blocked = true
  319. return false
  320. }
  321. }
  322. return true
  323. }
  324. func stepACLCheck(req *ExecutionRequest) bool {
  325. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Binding.Action)
  326. if !canExec {
  327. req.logEntry.Output = "ACL check failed. Blocked from executing."
  328. req.logEntry.Blocked = true
  329. log.WithFields(log.Fields{
  330. "actionTitle": req.logEntry.ActionTitle,
  331. }).Warnf("ACL check failed. Blocked from executing.")
  332. }
  333. return canExec
  334. }
  335. func stepParseArgs(req *ExecutionRequest) bool {
  336. var err error
  337. if req.Arguments == nil {
  338. req.Arguments = make(map[string]string)
  339. }
  340. req.Arguments["ot_executionTrackingId"] = req.TrackingID
  341. req.Arguments["ot_username"] = req.AuthenticatedUser.Username
  342. mangleInvalidArgumentValues(req)
  343. if req.Binding == nil || req.Binding.Action == nil {
  344. err = fmt.Errorf("cannot parse arguments: Binding or Action is nil")
  345. req.logEntry.Output = err.Error()
  346. log.Warn(err.Error())
  347. return false
  348. }
  349. if len(req.Binding.Action.Exec) > 0 {
  350. req.useDirectExec = true
  351. req.execArgs, err = parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
  352. } else {
  353. req.useDirectExec = false
  354. err = checkShellArgumentSafety(req.Binding.Action)
  355. if err != nil {
  356. req.logEntry.Output = err.Error()
  357. log.Warn(err.Error())
  358. return false
  359. }
  360. req.finalParsedCommand, err = parseActionArguments(req.Arguments, req.Binding.Action, req.Binding.Entity)
  361. }
  362. if err != nil {
  363. req.logEntry.Output = err.Error()
  364. log.Warn(err.Error())
  365. return false
  366. }
  367. return true
  368. }
  369. func stepRequestAction(req *ExecutionRequest) bool {
  370. metricActionsRequested.Inc()
  371. // If there is no binding or action, do not proceed. Leave default
  372. // log entry values (icon/title/id) and stop execution gracefully.
  373. if req.Binding == nil || req.Binding.Action == nil {
  374. log.Warnf("Action request has no binding/action; skipping execution")
  375. return false
  376. }
  377. req.logEntry.Binding = req.Binding
  378. req.logEntry.ActionConfigTitle = req.Binding.Action.Title
  379. req.logEntry.ActionTitle = entities.ParseTemplateWith(req.Binding.Action.Title, req.Binding.Entity)
  380. req.logEntry.ActionIcon = req.Binding.Action.Icon
  381. req.logEntry.ActionId = req.Binding.Action.ID
  382. req.logEntry.Tags = req.Tags
  383. req.executor.logmutex.Lock()
  384. if _, containsKey := req.executor.LogsByActionId[req.Binding.Action.ID]; !containsKey {
  385. req.executor.LogsByActionId[req.Binding.Action.ID] = make([]*InternalLogEntry, 0)
  386. }
  387. req.executor.LogsByActionId[req.Binding.Action.ID] = append(req.executor.LogsByActionId[req.Binding.Action.ID], req.logEntry)
  388. req.executor.logmutex.Unlock()
  389. log.WithFields(log.Fields{
  390. "actionTitle": req.logEntry.ActionTitle,
  391. "tags": req.Tags,
  392. }).Infof("Action requested")
  393. notifyListenersStarted(req)
  394. return true
  395. }
  396. func stepLogStart(req *ExecutionRequest) bool {
  397. log.WithFields(log.Fields{
  398. "actionTitle": req.logEntry.ActionTitle,
  399. "timeout": req.Binding.Action.Timeout,
  400. }).Infof("Action started")
  401. return true
  402. }
  403. func stepLogFinish(req *ExecutionRequest) bool {
  404. req.logEntry.ExecutionFinished = true
  405. log.WithFields(log.Fields{
  406. "actionTitle": req.logEntry.ActionTitle,
  407. "outputLength": len(req.logEntry.Output),
  408. "timedOut": req.logEntry.TimedOut,
  409. "exit": req.logEntry.ExitCode,
  410. }).Infof("Action finished")
  411. return true
  412. }
  413. func notifyListenersFinished(req *ExecutionRequest) {
  414. for _, listener := range req.executor.listeners {
  415. listener.OnExecutionFinished(req.logEntry)
  416. }
  417. }
  418. func notifyListenersStarted(req *ExecutionRequest) {
  419. for _, listener := range req.executor.listeners {
  420. listener.OnExecutionStarted(req.logEntry)
  421. }
  422. }
  423. func appendErrorToStderr(err error, logEntry *InternalLogEntry) {
  424. if err != nil {
  425. logEntry.Output = err.Error() + "\n\n" + logEntry.Output
  426. }
  427. }
  428. type OutputStreamer struct {
  429. Req *ExecutionRequest
  430. output bytes.Buffer
  431. }
  432. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  433. for _, listener := range ost.Req.executor.listeners {
  434. listener.OnOutputChunk(o, ost.Req.TrackingID)
  435. }
  436. return ost.output.Write(o)
  437. }
  438. func (ost *OutputStreamer) String() string {
  439. return ost.output.String()
  440. }
  441. func buildEnv(args map[string]string) []string {
  442. ret := append(os.Environ(), "OLIVETIN=1")
  443. for k, v := range args {
  444. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  445. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  446. if varName == "" {
  447. continue
  448. }
  449. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  450. }
  451. return ret
  452. }
  453. func stepExec(req *ExecutionRequest) bool {
  454. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  455. defer cancel()
  456. streamer := &OutputStreamer{Req: req}
  457. var cmd *exec.Cmd
  458. if req.useDirectExec {
  459. cmd = wrapCommandDirect(ctx, req.execArgs)
  460. } else {
  461. cmd = wrapCommandInShell(ctx, req.finalParsedCommand)
  462. }
  463. if cmd == nil {
  464. req.logEntry.Output = "Cannot execute: no command arguments provided"
  465. log.Warn("Cannot execute: no command arguments provided")
  466. return false
  467. }
  468. cmd.Stdout = streamer
  469. cmd.Stderr = streamer
  470. cmd.Env = buildEnv(req.Arguments)
  471. req.logEntry.ExecutionStarted = true
  472. runerr := cmd.Start()
  473. req.logEntry.Process = cmd.Process
  474. waiterr := cmd.Wait()
  475. req.logEntry.ExitCode = int32(cmd.ProcessState.ExitCode())
  476. req.logEntry.Output = streamer.String()
  477. appendErrorToStderr(runerr, req.logEntry)
  478. appendErrorToStderr(waiterr, req.logEntry)
  479. if ctx.Err() == context.DeadlineExceeded {
  480. log.WithFields(log.Fields{
  481. "actionTitle": req.logEntry.ActionTitle,
  482. }).Warnf("Action timed out")
  483. // The context timeout should kill the process, but let's make sure.
  484. err := req.executor.Kill(req.logEntry)
  485. if err != nil {
  486. log.WithFields(log.Fields{
  487. "actionTitle": req.logEntry.ActionTitle,
  488. }).Warnf("could not kill process: %v", err)
  489. }
  490. req.logEntry.TimedOut = true
  491. req.logEntry.Output += "OliveTin::timeout - this action timed out after " + fmt.Sprintf("%v", req.Binding.Action.Timeout) + " seconds. If you need more time for this action, set a longer timeout. See https://docs.olivetin.app/action_customization/timeouts.html for more help."
  492. }
  493. req.logEntry.DatetimeFinished = time.Now()
  494. return true
  495. }
  496. func stepExecAfter(req *ExecutionRequest) bool {
  497. if req.Binding.Action.ShellAfterCompleted == "" {
  498. return true
  499. }
  500. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  501. defer cancel()
  502. var stdout bytes.Buffer
  503. var stderr bytes.Buffer
  504. args := map[string]string{
  505. "output": req.logEntry.Output,
  506. "exitCode": fmt.Sprintf("%v", req.logEntry.ExitCode),
  507. "ot_executionTrackingId": req.TrackingID,
  508. "ot_username": req.AuthenticatedUser.Username,
  509. }
  510. finalParsedCommand, err := parseCommandForReplacements(req.Binding.Action.ShellAfterCompleted, args, req.Binding.Entity)
  511. if err != nil {
  512. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  513. req.logEntry.Output += msg
  514. log.Warn(msg)
  515. return true
  516. }
  517. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  518. cmd.Stdout = &stdout
  519. cmd.Stderr = &stderr
  520. cmd.Env = buildEnv(args)
  521. runerr := cmd.Start()
  522. waiterr := cmd.Wait()
  523. req.logEntry.Output += "\n"
  524. req.logEntry.Output += "OliveTin::shellAfterCompleted stdout\n"
  525. req.logEntry.Output += stdout.String()
  526. req.logEntry.Output += "OliveTin::shellAfterCompleted stderr\n"
  527. req.logEntry.Output += stderr.String()
  528. req.logEntry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  529. appendErrorToStderr(runerr, req.logEntry)
  530. appendErrorToStderr(waiterr, req.logEntry)
  531. if ctx.Err() == context.DeadlineExceeded {
  532. req.logEntry.Output += "Your shellAfterCompleted command timed out."
  533. }
  534. req.logEntry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", cmd.ProcessState.ExitCode())
  535. req.logEntry.Output += "OliveTin::shellAfterCompleted output complete\n"
  536. return true
  537. }
  538. //gocyclo:ignore
  539. func stepTrigger(req *ExecutionRequest) bool {
  540. if req.Binding.Action.Triggers == nil {
  541. return true
  542. }
  543. if req.TriggerDepth >= MaxTriggerDepth {
  544. log.WithFields(log.Fields{
  545. "actionTitle": req.logEntry.ActionTitle,
  546. "depth": req.TriggerDepth,
  547. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  548. req.logEntry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  549. return true
  550. }
  551. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  552. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  553. }
  554. triggerLoop(req)
  555. return true
  556. }
  557. func triggerLoop(req *ExecutionRequest) {
  558. for _, triggerReq := range req.Binding.Action.Triggers {
  559. binding := req.executor.FindBindingByID(triggerReq)
  560. trigger := &ExecutionRequest{
  561. Binding: binding,
  562. TrackingID: uuid.NewString(),
  563. Tags: []string{"trigger"},
  564. AuthenticatedUser: req.AuthenticatedUser,
  565. Arguments: req.Arguments,
  566. Cfg: req.Cfg,
  567. TriggerDepth: req.TriggerDepth + 1,
  568. }
  569. req.executor.ExecRequest(trigger)
  570. }
  571. }
  572. func stepSaveLog(req *ExecutionRequest) bool {
  573. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  574. saveLogResults(req, filename)
  575. saveLogOutput(req, filename)
  576. return true
  577. }
  578. func firstNonEmpty(one, two string) string {
  579. if one != "" {
  580. return one
  581. }
  582. return two
  583. }
  584. func saveLogResults(req *ExecutionRequest, filename string) {
  585. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  586. if dir != "" {
  587. data, err := yaml.Marshal(req.logEntry)
  588. if err != nil {
  589. log.Warnf("%v", err)
  590. }
  591. filepath := path.Join(dir, filename+".yaml")
  592. err = os.WriteFile(filepath, data, 0644)
  593. if err != nil {
  594. log.Warnf("%v", err)
  595. }
  596. }
  597. }
  598. func saveLogOutput(req *ExecutionRequest, filename string) {
  599. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  600. if dir != "" {
  601. data := req.logEntry.Output
  602. filepath := path.Join(dir, filename+".log")
  603. err := os.WriteFile(filepath, []byte(data), 0644)
  604. if err != nil {
  605. log.Warnf("%v", err)
  606. }
  607. }
  608. }