executor.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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. // GetLogTrackingIdsACL returns logs filtered by ACL visibility for the user and
  188. // paginated correctly based on the filtered set.
  189. func (e *Executor) GetLogTrackingIdsACL(cfg *config.Config, user *acl.AuthenticatedUser, startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  190. // Build filtered list in reverse-chronological order (matching GetLogTrackingIds)
  191. filtered := make([]*InternalLogEntry, 0)
  192. e.logmutex.RLock()
  193. for i := len(e.logsTrackingIdsByDate) - 1; i >= 0; i-- {
  194. entry := e.logs[e.logsTrackingIdsByDate[i]]
  195. if entry == nil || entry.Binding == nil || entry.Binding.Action == nil {
  196. continue
  197. }
  198. if acl.IsAllowedLogs(cfg, user, entry.Binding.Action) {
  199. filtered = append(filtered, entry)
  200. }
  201. }
  202. e.logmutex.RUnlock()
  203. total := int64(len(filtered))
  204. paging := &PagingResult{PageSize: pageCount, TotalCount: total, StartOffset: startOffset}
  205. if total == 0 {
  206. paging.CountRemaining = 0
  207. return []*InternalLogEntry{}, paging
  208. }
  209. // Compute start/end indices using the same semantics as GetLogTrackingIds,
  210. // but over the filtered slice
  211. startIndex := getPagingStartIndex(startOffset, total)
  212. pageCount = min(total, pageCount)
  213. endIndex := max(0, (startIndex-pageCount)+1)
  214. // Slice is inclusive of both ends in original logic, so iterate and collect
  215. out := make([]*InternalLogEntry, 0, pageCount)
  216. for i := endIndex; i <= startIndex && i < int64(len(filtered)); i++ {
  217. out = append(out, filtered[i])
  218. }
  219. paging.CountRemaining = endIndex
  220. return out, paging
  221. }
  222. func (e *Executor) GetLog(trackingID string) (*InternalLogEntry, bool) {
  223. e.logmutex.RLock()
  224. entry, found := e.logs[trackingID]
  225. e.logmutex.RUnlock()
  226. return entry, found
  227. }
  228. func (e *Executor) GetLogsByActionId(actionId string) []*InternalLogEntry {
  229. e.logmutex.RLock()
  230. logs, found := e.LogsByActionId[actionId]
  231. e.logmutex.RUnlock()
  232. if !found {
  233. return make([]*InternalLogEntry, 0)
  234. }
  235. return logs
  236. }
  237. func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) {
  238. e.logmutex.Lock()
  239. entry.Index = int64(len(e.logsTrackingIdsByDate))
  240. e.logs[trackingID] = entry
  241. e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
  242. e.logmutex.Unlock()
  243. }
  244. // ExecRequest processes an ExecutionRequest
  245. func (e *Executor) ExecRequest(req *ExecutionRequest) (*sync.WaitGroup, string) {
  246. if req.AuthenticatedUser == nil {
  247. req.AuthenticatedUser = acl.UserGuest(req.Cfg)
  248. }
  249. req.executor = e
  250. req.logEntry = &InternalLogEntry{
  251. Binding: req.Binding,
  252. DatetimeStarted: time.Now(),
  253. ExecutionTrackingID: req.TrackingID,
  254. Output: "",
  255. ExitCode: DefaultExitCodeNotExecuted,
  256. ExecutionStarted: false,
  257. ExecutionFinished: false,
  258. ActionId: "",
  259. ActionTitle: "notfound",
  260. ActionIcon: "&#x1f4a9;",
  261. Username: req.AuthenticatedUser.Username,
  262. }
  263. _, isDuplicate := e.GetLog(req.TrackingID)
  264. if isDuplicate || req.TrackingID == "" {
  265. req.TrackingID = uuid.NewString()
  266. }
  267. // Update the log entry with the final tracking ID
  268. req.logEntry.ExecutionTrackingID = req.TrackingID
  269. log.Tracef("executor.ExecRequest(): %v", req)
  270. e.SetLog(req.TrackingID, req.logEntry)
  271. wg := new(sync.WaitGroup)
  272. wg.Add(1)
  273. go func() {
  274. e.execChain(req)
  275. defer wg.Done()
  276. }()
  277. return wg, req.TrackingID
  278. }
  279. func (e *Executor) execChain(req *ExecutionRequest) {
  280. for _, step := range e.chainOfCommand {
  281. if !step(req) {
  282. break
  283. }
  284. }
  285. req.logEntry.ExecutionFinished = true
  286. // This isn't a step, because we want to notify all listeners, irrespective
  287. // of how many steps were actually executed.
  288. notifyListenersFinished(req)
  289. }
  290. func getConcurrentCount(req *ExecutionRequest) int {
  291. concurrentCount := 0
  292. req.executor.logmutex.RLock()
  293. for _, log := range req.executor.GetLogsByActionId(req.Binding.Action.ID) {
  294. if !log.ExecutionFinished {
  295. concurrentCount += 1
  296. }
  297. }
  298. req.executor.logmutex.RUnlock()
  299. return concurrentCount
  300. }
  301. func stepConcurrencyCheck(req *ExecutionRequest) bool {
  302. concurrentCount := getConcurrentCount(req)
  303. // Note that the current execution is counted int the logs, so when checking we +1
  304. if concurrentCount >= (req.Binding.Action.MaxConcurrent + 1) {
  305. log.WithFields(log.Fields{
  306. "actionTitle": req.logEntry.ActionTitle,
  307. "concurrentCount": concurrentCount,
  308. "maxConcurrent": req.Binding.Action.MaxConcurrent,
  309. }).Warnf("Blocked from executing due to concurrency limit")
  310. req.logEntry.Output = "Blocked from executing due to concurrency limit"
  311. req.logEntry.Blocked = true
  312. return false
  313. }
  314. return true
  315. }
  316. func parseDuration(rate config.RateSpec) time.Duration {
  317. duration, err := time.ParseDuration(rate.Duration)
  318. if err != nil {
  319. log.Warnf("Could not parse duration: %v", rate.Duration)
  320. return -1 * time.Minute
  321. }
  322. return duration
  323. }
  324. //gocyclo:ignore
  325. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  326. executions := -1 // Because we will find ourself when checking execution logs
  327. duration := parseDuration(rate)
  328. then := time.Now().Add(-duration)
  329. for _, logEntry := range req.executor.GetLogsByActionId(req.Binding.Action.ID) {
  330. // FIXME
  331. /*
  332. if logEntry.EntityPrefix != req.EntityPrefix {
  333. continue
  334. }
  335. */
  336. if logEntry.DatetimeStarted.After(then) && !logEntry.Blocked {
  337. executions += 1
  338. }
  339. }
  340. return executions
  341. }
  342. func stepRateCheck(req *ExecutionRequest) bool {
  343. for _, rate := range req.Binding.Action.MaxRate {
  344. executions := getExecutionsCount(rate, req)
  345. if executions >= rate.Limit {
  346. log.WithFields(log.Fields{
  347. "actionTitle": req.logEntry.ActionTitle,
  348. "executions": executions,
  349. "limit": rate.Limit,
  350. "duration": rate.Duration,
  351. }).Infof("Blocked from executing due to rate limit")
  352. req.logEntry.Output = "Blocked from executing due to rate limit"
  353. req.logEntry.Blocked = true
  354. return false
  355. }
  356. }
  357. return true
  358. }
  359. func stepACLCheck(req *ExecutionRequest) bool {
  360. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Binding.Action)
  361. if !canExec {
  362. req.logEntry.Output = "ACL check failed. Blocked from executing."
  363. req.logEntry.Blocked = true
  364. log.WithFields(log.Fields{
  365. "actionTitle": req.logEntry.ActionTitle,
  366. }).Warnf("ACL check failed. Blocked from executing.")
  367. }
  368. return canExec
  369. }
  370. func stepParseArgs(req *ExecutionRequest) bool {
  371. ensureArgumentMap(req)
  372. injectSystemArgs(req)
  373. if !hasBindingAndAction(req) {
  374. return fail(req, fmt.Errorf("cannot parse arguments: Binding or Action is nil"))
  375. }
  376. mangleInvalidArgumentValues(req)
  377. if hasExec(req) {
  378. return handleExecBranch(req)
  379. } else {
  380. return handleShellBranch(req)
  381. }
  382. }
  383. func handleExecBranch(req *ExecutionRequest) bool {
  384. args, err := parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
  385. if err != nil {
  386. return fail(req, err)
  387. }
  388. req.useDirectExec = true
  389. req.execArgs = args
  390. return true
  391. }
  392. func handleShellBranch(req *ExecutionRequest) bool {
  393. if err := checkShellArgumentSafety(req.Binding.Action); err != nil {
  394. return fail(req, err)
  395. }
  396. cmd, err := parseActionArguments(req.Arguments, req.Binding.Action, req.Binding.Entity)
  397. if err != nil {
  398. return fail(req, err)
  399. }
  400. req.useDirectExec = false
  401. req.finalParsedCommand = cmd
  402. return true
  403. }
  404. func ensureArgumentMap(req *ExecutionRequest) {
  405. if req.Arguments == nil {
  406. req.Arguments = make(map[string]string)
  407. }
  408. }
  409. func injectSystemArgs(req *ExecutionRequest) {
  410. req.Arguments["ot_executionTrackingId"] = req.TrackingID
  411. req.Arguments["ot_username"] = req.AuthenticatedUser.Username
  412. }
  413. func hasBindingAndAction(req *ExecutionRequest) bool {
  414. return !(req.Binding == nil || req.Binding.Action == nil)
  415. }
  416. func hasExec(req *ExecutionRequest) bool {
  417. return len(req.Binding.Action.Exec) > 0
  418. }
  419. func fail(req *ExecutionRequest, err error) bool {
  420. req.logEntry.Output = err.Error()
  421. log.Warn(err.Error())
  422. return false
  423. }
  424. func stepRequestAction(req *ExecutionRequest) bool {
  425. metricActionsRequested.Inc()
  426. // If there is no binding or action, do not proceed. Leave default
  427. // log entry values (icon/title/id) and stop execution gracefully.
  428. if req.Binding == nil || req.Binding.Action == nil {
  429. log.Warnf("Action request has no binding/action; skipping execution")
  430. return false
  431. }
  432. req.logEntry.Binding = req.Binding
  433. req.logEntry.ActionConfigTitle = req.Binding.Action.Title
  434. req.logEntry.ActionTitle = entities.ParseTemplateWith(req.Binding.Action.Title, req.Binding.Entity)
  435. req.logEntry.ActionIcon = req.Binding.Action.Icon
  436. req.logEntry.ActionId = req.Binding.Action.ID
  437. req.logEntry.Tags = req.Tags
  438. req.executor.logmutex.Lock()
  439. if _, containsKey := req.executor.LogsByActionId[req.Binding.Action.ID]; !containsKey {
  440. req.executor.LogsByActionId[req.Binding.Action.ID] = make([]*InternalLogEntry, 0)
  441. }
  442. req.executor.LogsByActionId[req.Binding.Action.ID] = append(req.executor.LogsByActionId[req.Binding.Action.ID], req.logEntry)
  443. req.executor.logmutex.Unlock()
  444. log.WithFields(log.Fields{
  445. "actionTitle": req.logEntry.ActionTitle,
  446. "tags": req.Tags,
  447. }).Infof("Action requested")
  448. notifyListenersStarted(req)
  449. return true
  450. }
  451. func stepLogStart(req *ExecutionRequest) bool {
  452. log.WithFields(log.Fields{
  453. "actionTitle": req.logEntry.ActionTitle,
  454. "timeout": req.Binding.Action.Timeout,
  455. }).Infof("Action started")
  456. return true
  457. }
  458. func stepLogFinish(req *ExecutionRequest) bool {
  459. req.logEntry.ExecutionFinished = true
  460. log.WithFields(log.Fields{
  461. "actionTitle": req.logEntry.ActionTitle,
  462. "outputLength": len(req.logEntry.Output),
  463. "timedOut": req.logEntry.TimedOut,
  464. "exit": req.logEntry.ExitCode,
  465. }).Infof("Action finished")
  466. return true
  467. }
  468. func notifyListenersFinished(req *ExecutionRequest) {
  469. for _, listener := range req.executor.listeners {
  470. listener.OnExecutionFinished(req.logEntry)
  471. }
  472. }
  473. func notifyListenersStarted(req *ExecutionRequest) {
  474. for _, listener := range req.executor.listeners {
  475. listener.OnExecutionStarted(req.logEntry)
  476. }
  477. }
  478. func appendErrorToStderr(err error, logEntry *InternalLogEntry) {
  479. if err != nil {
  480. logEntry.Output = err.Error() + "\n\n" + logEntry.Output
  481. }
  482. }
  483. type OutputStreamer struct {
  484. Req *ExecutionRequest
  485. output bytes.Buffer
  486. }
  487. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  488. for _, listener := range ost.Req.executor.listeners {
  489. listener.OnOutputChunk(o, ost.Req.TrackingID)
  490. }
  491. return ost.output.Write(o)
  492. }
  493. func (ost *OutputStreamer) String() string {
  494. return ost.output.String()
  495. }
  496. func buildEnv(args map[string]string) []string {
  497. ret := append(os.Environ(), "OLIVETIN=1")
  498. for k, v := range args {
  499. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  500. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  501. if varName == "" {
  502. continue
  503. }
  504. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  505. }
  506. return ret
  507. }
  508. func stepExec(req *ExecutionRequest) bool {
  509. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  510. defer cancel()
  511. streamer := &OutputStreamer{Req: req}
  512. cmd := buildCommand(ctx, req)
  513. if cmd == nil {
  514. req.logEntry.Output = "Cannot execute: no command arguments provided"
  515. log.Warn("Cannot execute: no command arguments provided")
  516. return false
  517. }
  518. prepareCommand(cmd, streamer, req)
  519. runerr := cmd.Start()
  520. req.logEntry.Process = cmd.Process
  521. waiterr := cmd.Wait()
  522. req.logEntry.ExitCode = int32(cmd.ProcessState.ExitCode())
  523. req.logEntry.Output = streamer.String()
  524. appendErrorToStderr(runerr, req.logEntry)
  525. appendErrorToStderr(waiterr, req.logEntry)
  526. if ctx.Err() == context.DeadlineExceeded {
  527. log.WithFields(log.Fields{
  528. "actionTitle": req.logEntry.ActionTitle,
  529. }).Warnf("Action timed out")
  530. // The context timeout should kill the process, but let's make sure.
  531. err := req.executor.Kill(req.logEntry)
  532. if err != nil {
  533. log.WithFields(log.Fields{
  534. "actionTitle": req.logEntry.ActionTitle,
  535. }).Warnf("could not kill process: %v", err)
  536. }
  537. req.logEntry.TimedOut = true
  538. 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."
  539. }
  540. req.logEntry.DatetimeFinished = time.Now()
  541. return true
  542. }
  543. func buildCommand(ctx context.Context, req *ExecutionRequest) *exec.Cmd {
  544. if req.useDirectExec {
  545. return wrapCommandDirect(ctx, req.execArgs)
  546. }
  547. return wrapCommandInShell(ctx, req.finalParsedCommand)
  548. }
  549. func prepareCommand(cmd *exec.Cmd, streamer *OutputStreamer, req *ExecutionRequest) {
  550. cmd.Stdout = streamer
  551. cmd.Stderr = streamer
  552. cmd.Env = buildEnv(req.Arguments)
  553. req.logEntry.ExecutionStarted = true
  554. }
  555. func stepExecAfter(req *ExecutionRequest) bool {
  556. if req.Binding.Action.ShellAfterCompleted == "" {
  557. return true
  558. }
  559. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  560. defer cancel()
  561. var stdout bytes.Buffer
  562. var stderr bytes.Buffer
  563. args := map[string]string{
  564. "output": req.logEntry.Output,
  565. "exitCode": fmt.Sprintf("%v", req.logEntry.ExitCode),
  566. "ot_executionTrackingId": req.TrackingID,
  567. "ot_username": req.AuthenticatedUser.Username,
  568. }
  569. finalParsedCommand, err := parseCommandForReplacements(req.Binding.Action.ShellAfterCompleted, args, req.Binding.Entity)
  570. if err != nil {
  571. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  572. req.logEntry.Output += msg
  573. log.Warn(msg)
  574. return true
  575. }
  576. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  577. cmd.Stdout = &stdout
  578. cmd.Stderr = &stderr
  579. cmd.Env = buildEnv(args)
  580. runerr := cmd.Start()
  581. waiterr := cmd.Wait()
  582. req.logEntry.Output += "\n"
  583. req.logEntry.Output += "OliveTin::shellAfterCompleted stdout\n"
  584. req.logEntry.Output += stdout.String()
  585. req.logEntry.Output += "OliveTin::shellAfterCompleted stderr\n"
  586. req.logEntry.Output += stderr.String()
  587. req.logEntry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  588. appendErrorToStderr(runerr, req.logEntry)
  589. appendErrorToStderr(waiterr, req.logEntry)
  590. if ctx.Err() == context.DeadlineExceeded {
  591. req.logEntry.Output += "Your shellAfterCompleted command timed out."
  592. }
  593. req.logEntry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", cmd.ProcessState.ExitCode())
  594. req.logEntry.Output += "OliveTin::shellAfterCompleted output complete\n"
  595. return true
  596. }
  597. //gocyclo:ignore
  598. func stepTrigger(req *ExecutionRequest) bool {
  599. if req.Binding.Action.Triggers == nil {
  600. return true
  601. }
  602. if req.TriggerDepth >= MaxTriggerDepth {
  603. log.WithFields(log.Fields{
  604. "actionTitle": req.logEntry.ActionTitle,
  605. "depth": req.TriggerDepth,
  606. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  607. req.logEntry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  608. return true
  609. }
  610. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  611. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  612. }
  613. triggerLoop(req)
  614. return true
  615. }
  616. func triggerLoop(req *ExecutionRequest) {
  617. for _, triggerReq := range req.Binding.Action.Triggers {
  618. binding := req.executor.FindBindingByID(triggerReq)
  619. trigger := &ExecutionRequest{
  620. Binding: binding,
  621. TrackingID: uuid.NewString(),
  622. Tags: []string{"trigger"},
  623. AuthenticatedUser: req.AuthenticatedUser,
  624. Arguments: req.Arguments,
  625. Cfg: req.Cfg,
  626. TriggerDepth: req.TriggerDepth + 1,
  627. }
  628. req.executor.ExecRequest(trigger)
  629. }
  630. }
  631. func stepSaveLog(req *ExecutionRequest) bool {
  632. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  633. saveLogResults(req, filename)
  634. saveLogOutput(req, filename)
  635. return true
  636. }
  637. func firstNonEmpty(one, two string) string {
  638. if one != "" {
  639. return one
  640. }
  641. return two
  642. }
  643. func saveLogResults(req *ExecutionRequest, filename string) {
  644. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  645. if dir != "" {
  646. data, err := yaml.Marshal(req.logEntry)
  647. if err != nil {
  648. log.Warnf("%v", err)
  649. }
  650. filepath := path.Join(dir, filename+".yaml")
  651. err = os.WriteFile(filepath, data, 0644)
  652. if err != nil {
  653. log.Warnf("%v", err)
  654. }
  655. }
  656. }
  657. func saveLogOutput(req *ExecutionRequest, filename string) {
  658. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  659. if dir != "" {
  660. data := req.logEntry.Output
  661. filepath := path.Join(dir, filename+".log")
  662. err := os.WriteFile(filepath, []byte(data), 0644)
  663. if err != nil {
  664. log.Warnf("%v", err)
  665. }
  666. }
  667. }