executor.go 19 KB

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