executor.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. package executor
  2. import (
  3. acl "github.com/OliveTin/OliveTin/internal/acl"
  4. "github.com/OliveTin/OliveTin/internal/auth"
  5. authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
  6. config "github.com/OliveTin/OliveTin/internal/config"
  7. "github.com/OliveTin/OliveTin/internal/entities"
  8. "github.com/OliveTin/OliveTin/internal/logfilter"
  9. "github.com/OliveTin/OliveTin/internal/tpl"
  10. "github.com/google/uuid"
  11. log "github.com/sirupsen/logrus"
  12. "gopkg.in/yaml.v3"
  13. "bytes"
  14. "context"
  15. "fmt"
  16. "os"
  17. "os/exec"
  18. "path"
  19. "regexp"
  20. "strings"
  21. "sync"
  22. "time"
  23. )
  24. const (
  25. DefaultExitCodeNotExecuted = -1337
  26. MaxTriggerDepth = 10
  27. )
  28. var validTrackingIDPattern = regexp.MustCompile(`^[a-fA-F0-9\-]+$`)
  29. func isValidTrackingID(id string) bool {
  30. const MaxTrackingIDLength = 36
  31. return id != "" && len(id) <= MaxTrackingIDLength && validTrackingIDPattern.MatchString(id)
  32. }
  33. type ActionBinding struct {
  34. ID string
  35. Action *config.Action
  36. Entity *entities.Entity
  37. ConfigOrder int
  38. OnDashboards []DashboardNavigationTarget
  39. }
  40. // Executor represents a helper class for executing commands. It's main method
  41. // is ExecRequest
  42. type Executor struct {
  43. logs map[string]*InternalLogEntry
  44. logsTrackingIdsByDate []string
  45. LogsByBindingId map[string][]*InternalLogEntry
  46. logmutex sync.RWMutex
  47. MapActionBindings map[string]*ActionBinding
  48. MapActionBindingsLock sync.RWMutex
  49. Cfg *config.Config
  50. listeners []listener
  51. listenersMu sync.RWMutex
  52. chainOfCommand []executorStepFunc
  53. groupQueue []*queuedExecution
  54. groupQueueMu sync.Mutex
  55. }
  56. // ExecutionRequest is a request to execute an action. It's passed to an
  57. // Executor. They're created from the api.
  58. type ExecutionRequest struct {
  59. Binding *ActionBinding
  60. Arguments map[string]string
  61. TrackingID string
  62. Tags []string
  63. Cfg *config.Config
  64. AuthenticatedUser *authpublic.AuthenticatedUser
  65. TriggerDepth int
  66. Justification string
  67. logEntry *InternalLogEntry
  68. finalParsedCommand string
  69. execArgs []string
  70. useDirectExec bool
  71. executor *Executor
  72. skipRequestRegistration bool
  73. }
  74. func (req *ExecutionRequest) mutateLogEntry(mutator func(*InternalLogEntry)) {
  75. if req.executor == nil {
  76. mutator(req.logEntry)
  77. return
  78. }
  79. req.executor.logmutex.Lock()
  80. defer req.executor.logmutex.Unlock()
  81. mutator(req.logEntry)
  82. }
  83. // LogEntrySnapshot is a copy of selected log entry fields for race-safe reads.
  84. type LogEntrySnapshot struct {
  85. Queued bool
  86. Blocked bool
  87. ExecutionStarted bool
  88. ExecutionFinished bool
  89. ExitCode int32
  90. Output string
  91. }
  92. // SnapshotLog returns a copy of selected log entry fields under read lock.
  93. func (e *Executor) SnapshotLog(trackingID string) (LogEntrySnapshot, bool) {
  94. e.logmutex.RLock()
  95. defer e.logmutex.RUnlock()
  96. entry, found := e.logs[trackingID]
  97. if !found {
  98. return LogEntrySnapshot{}, false
  99. }
  100. return LogEntrySnapshot{
  101. Queued: entry.Queued,
  102. Blocked: entry.Blocked,
  103. ExecutionStarted: entry.ExecutionStarted,
  104. ExecutionFinished: entry.ExecutionFinished,
  105. ExitCode: entry.ExitCode,
  106. Output: entry.Output,
  107. }, true
  108. }
  109. // InternalLogEntry objects are created by an Executor, and represent the final
  110. // state of execution (even if the command is not executed). It's designed to be
  111. // easily serializable.
  112. type InternalLogEntry struct {
  113. Binding *ActionBinding
  114. DatetimeStarted time.Time
  115. DatetimeFinished time.Time
  116. Output string
  117. TimedOut bool
  118. Blocked bool
  119. Queued bool
  120. QueuedForGroup string
  121. ExitCode int32
  122. Tags []string
  123. ExecutionStarted bool
  124. ExecutionFinished bool
  125. ExecutionTrackingID string
  126. Process *os.Process
  127. Username string
  128. Index int64
  129. EntityPrefix string
  130. ActionConfigTitle string // This is the title of the action as defined in the config, not the final parsed title.
  131. /*
  132. The following 3 properties are obviously on Action normally, but it's useful
  133. that logs are lightweight (so we don't need to have an action associated to
  134. logs, etc. Therefore, we duplicate those values here.
  135. */
  136. ActionTitle string
  137. ActionIcon string
  138. Justification string
  139. }
  140. // .Binding can be nil, so we need to handle that.
  141. func (e *InternalLogEntry) GetBindingId() string {
  142. if e.Binding == nil {
  143. return ""
  144. }
  145. return e.Binding.ID
  146. }
  147. type executorStepFunc func(*ExecutionRequest) bool
  148. // DefaultExecutor returns an Executor, with a sensible "chain of command" for
  149. // executing actions.
  150. func DefaultExecutor(cfg *config.Config) *Executor {
  151. e := Executor{}
  152. e.Cfg = cfg
  153. e.logs = make(map[string]*InternalLogEntry)
  154. e.logsTrackingIdsByDate = make([]string, 0)
  155. e.LogsByBindingId = make(map[string][]*InternalLogEntry)
  156. e.MapActionBindings = make(map[string]*ActionBinding)
  157. e.chainOfCommand = []executorStepFunc{
  158. stepRequestAction,
  159. stepConcurrencyCheck,
  160. stepRateCheck,
  161. stepACLCheck,
  162. stepParseArgs,
  163. stepLogStart,
  164. stepExec,
  165. stepExecAfter,
  166. stepLogFinish,
  167. stepSaveLog,
  168. stepTrigger,
  169. }
  170. return &e
  171. }
  172. type listener interface {
  173. OnExecutionStarted(logEntry *InternalLogEntry)
  174. OnExecutionFinished(logEntry *InternalLogEntry)
  175. OnOutputChunk(o []byte, executionTrackingId string)
  176. OnActionMapRebuilt()
  177. }
  178. func (e *Executor) AddListener(m listener) {
  179. e.listenersMu.Lock()
  180. defer e.listenersMu.Unlock()
  181. e.listeners = append(e.listeners, m)
  182. }
  183. func (e *Executor) copyListeners() []listener {
  184. e.listenersMu.RLock()
  185. defer e.listenersMu.RUnlock()
  186. out := make([]listener, len(e.listeners))
  187. copy(out, e.listeners)
  188. return out
  189. }
  190. // getPagingStartIndex calculates the starting index for log pagination.
  191. // Parameters:
  192. //
  193. // startOffset: The offset from the most recent log (0 means start from the most recent)
  194. // totalLogCount: Total number of logs available
  195. // count: Number of logs to retrieve
  196. //
  197. // Returns: The calculated starting index for pagination
  198. func getPagingStartIndex(startOffset int64, totalLogCount int64) int64 {
  199. var startIndex int64
  200. if startOffset <= 0 {
  201. startIndex = totalLogCount
  202. } else {
  203. startIndex = (totalLogCount - startOffset)
  204. if startIndex < 0 {
  205. startIndex = 1
  206. }
  207. }
  208. return startIndex - 1
  209. }
  210. type PagingResult struct {
  211. CountRemaining int64
  212. PageSize int64
  213. TotalCount int64
  214. StartOffset int64
  215. }
  216. func (e *Executor) GetLogTrackingIds(startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  217. pagingResult := &PagingResult{
  218. CountRemaining: 0,
  219. PageSize: pageCount,
  220. TotalCount: 0,
  221. StartOffset: startOffset,
  222. }
  223. e.logmutex.RLock()
  224. totalLogCount := int64(len(e.logsTrackingIdsByDate))
  225. pagingResult.TotalCount = totalLogCount
  226. startIndex := getPagingStartIndex(startOffset, totalLogCount)
  227. pageCount = min(totalLogCount, pageCount)
  228. endIndex := max(0, (startIndex-pageCount)+1)
  229. log.WithFields(log.Fields{
  230. "startOffset": startOffset,
  231. "pageCount": pageCount,
  232. "total": totalLogCount,
  233. "startIndex": startIndex,
  234. "endIndex": endIndex,
  235. }).Tracef("GetLogTrackingIds")
  236. trackingIds := make([]*InternalLogEntry, 0, pageCount)
  237. if totalLogCount > 0 {
  238. for i := startIndex; i >= endIndex; i-- {
  239. trackingIds = append(trackingIds, e.logs[e.logsTrackingIdsByDate[i]])
  240. }
  241. }
  242. e.logmutex.RUnlock()
  243. pagingResult.CountRemaining = endIndex
  244. return trackingIds, pagingResult
  245. }
  246. func isValidLogEntryForACL(entry *InternalLogEntry) bool {
  247. return entry != nil && entry.Binding != nil && entry.Binding.Action != nil
  248. }
  249. func isLogEntryAllowedByACL(cfg *config.Config, user *authpublic.AuthenticatedUser, entry *InternalLogEntry) bool {
  250. return acl.IsAllowedLogs(cfg, user, entry.Binding.Action)
  251. }
  252. func (e *Executor) filterLogsByACL(cfg *config.Config, user *authpublic.AuthenticatedUser, dateFilter string) []*InternalLogEntry {
  253. e.logmutex.RLock()
  254. defer e.logmutex.RUnlock()
  255. filtered := make([]*InternalLogEntry, 0, len(e.logsTrackingIdsByDate))
  256. filterDate, hasDateFilter := parseDateFilter(dateFilter)
  257. for _, trackingId := range e.logsTrackingIdsByDate {
  258. entry := e.logs[trackingId]
  259. if shouldIncludeLogEntry(cfg, user, entry, filterDate, hasDateFilter) {
  260. filtered = append(filtered, entry)
  261. }
  262. }
  263. return filtered
  264. }
  265. // parseDateFilter parses the date filter string and returns filter information.
  266. func parseDateFilter(dateFilter string) (filterDate time.Time, hasDateFilter bool) {
  267. if dateFilter == "" {
  268. return time.Time{}, false
  269. }
  270. parsedDate, err := time.Parse("2006-01-02", dateFilter)
  271. if err != nil {
  272. log.WithFields(log.Fields{
  273. "dateFilter": dateFilter,
  274. "error": err,
  275. }).Errorf("Failed to parse date filter, expected format YYYY-MM-DD")
  276. return time.Time{}, false
  277. }
  278. return parsedDate, true
  279. }
  280. // shouldIncludeLogEntry determines if a log entry should be included based on ACL and date filter.
  281. func shouldIncludeLogEntry(cfg *config.Config, user *authpublic.AuthenticatedUser, entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  282. if !isValidLogEntryForACL(entry) {
  283. return false
  284. }
  285. if !isLogEntryAllowedByACL(cfg, user, entry) {
  286. return false
  287. }
  288. return matchesDateFilter(entry, filterDate, hasDateFilter)
  289. }
  290. // matchesDateFilter checks if the log entry matches the date filter.
  291. func matchesDateFilter(entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  292. if !hasDateFilter {
  293. return true
  294. }
  295. entryDate := entry.DatetimeStarted.UTC().Truncate(24 * time.Hour)
  296. filterDateUTC := filterDate.UTC().Truncate(24 * time.Hour)
  297. return entryDate.Equal(filterDateUTC)
  298. }
  299. // paginateFilteredLogs applies pagination to a filtered list of logs and returns
  300. // the paginated results along with pagination metadata.
  301. func paginateFilteredLogs(filtered []*InternalLogEntry, startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  302. total := int64(len(filtered))
  303. paging := &PagingResult{PageSize: pageCount, TotalCount: total, StartOffset: startOffset}
  304. if total == 0 {
  305. paging.CountRemaining = 0
  306. return []*InternalLogEntry{}, paging
  307. }
  308. startIndex := getPagingStartIndex(startOffset, total)
  309. pageCount = min(total, pageCount)
  310. endIndex := max(0, (startIndex-pageCount)+1)
  311. out := make([]*InternalLogEntry, 0, pageCount)
  312. for i := startIndex; i >= endIndex && i < int64(len(filtered)); i-- {
  313. out = append(out, filtered[i])
  314. }
  315. paging.CountRemaining = endIndex
  316. return out, paging
  317. }
  318. // GetLogTrackingIdsACL returns logs filtered by ACL visibility for the user and
  319. // paginated correctly based on the filtered set.
  320. // dateFilter is optional and should be in YYYY-MM-DD format. If empty, no date filtering is applied.
  321. // expressionFilter is an optional filter expression applied after ACL checks.
  322. func (e *Executor) GetLogTrackingIdsACL(cfg *config.Config, user *authpublic.AuthenticatedUser, startOffset int64, pageCount int64, dateFilter string, expressionFilter string) ([]*InternalLogEntry, *PagingResult, error) {
  323. filtered := e.filterLogsByACL(cfg, user, dateFilter)
  324. program, err := logfilter.Compile(expressionFilter)
  325. if err != nil {
  326. return nil, nil, err
  327. }
  328. filtered, err = applyLogFilter(filtered, program)
  329. if err != nil {
  330. return nil, nil, err
  331. }
  332. logs, paging := paginateFilteredLogs(filtered, startOffset, pageCount)
  333. return logs, paging, nil
  334. }
  335. func (e *Executor) GetLog(trackingID string) (*InternalLogEntry, bool) {
  336. e.logmutex.RLock()
  337. entry, found := e.logs[trackingID]
  338. e.logmutex.RUnlock()
  339. return entry, found
  340. }
  341. func (e *Executor) GetLogsByBindingId(bindingId string) []*InternalLogEntry {
  342. e.logmutex.RLock()
  343. logs, found := e.LogsByBindingId[bindingId]
  344. e.logmutex.RUnlock()
  345. if !found {
  346. return make([]*InternalLogEntry, 0)
  347. }
  348. return logs
  349. }
  350. // shouldCountExecution checks if a log entry should be counted for rate limiting.
  351. func shouldCountExecution(logEntry *InternalLogEntry, windowStart time.Time) bool {
  352. return !logEntry.Blocked && !logEntry.Queued && logEntry.DatetimeStarted.After(windowStart)
  353. }
  354. // updateOldestExecution updates the oldest execution time if this entry is older.
  355. func updateOldestExecution(oldestExecutionTime **time.Time, logEntry *InternalLogEntry) {
  356. if *oldestExecutionTime == nil {
  357. *oldestExecutionTime = &logEntry.DatetimeStarted
  358. } else if logEntry.DatetimeStarted.Before(**oldestExecutionTime) {
  359. *oldestExecutionTime = &logEntry.DatetimeStarted
  360. }
  361. }
  362. // findOldestExecutionInWindow finds the oldest execution within the time window and counts executions.
  363. // Returns the count of executions and the oldest execution time, or nil if none found.
  364. func findOldestExecutionInWindow(logs []*InternalLogEntry, windowStart time.Time) (int, *time.Time) {
  365. executions := 0
  366. var oldestExecutionTime *time.Time
  367. for _, logEntry := range logs {
  368. if !shouldCountExecution(logEntry, windowStart) {
  369. continue
  370. }
  371. executions++
  372. updateOldestExecution(&oldestExecutionTime, logEntry)
  373. }
  374. return executions, oldestExecutionTime
  375. }
  376. // calculateExpiryTime calculates when the oldest execution will fall outside the rate limit window.
  377. func calculateExpiryTime(oldestExecutionTime time.Time, duration time.Duration, now time.Time) time.Time {
  378. expiryTime := oldestExecutionTime.Add(duration)
  379. if !expiryTime.After(now) {
  380. return time.Time{}
  381. }
  382. return expiryTime
  383. }
  384. // updateMaxExpiryTime updates maxExpiryTime if expiryTime is later.
  385. func updateMaxExpiryTime(maxExpiryTime *time.Time, expiryTime time.Time) {
  386. if expiryTime.IsZero() {
  387. return
  388. }
  389. if maxExpiryTime.IsZero() || expiryTime.After(*maxExpiryTime) {
  390. *maxExpiryTime = expiryTime
  391. }
  392. }
  393. // calculateExpiryForRate calculates the expiry time for a single rate limit rule.
  394. // Returns the expiry time if the rate limit is exceeded, or zero time if not.
  395. func calculateExpiryForRate(rate config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  396. duration := parseDuration(rate)
  397. if duration <= 0 {
  398. return time.Time{}
  399. }
  400. windowStart := now.Add(-duration)
  401. executions, oldestExecutionTime := findOldestExecutionInWindow(logs, windowStart)
  402. if executions < rate.Limit || oldestExecutionTime == nil {
  403. return time.Time{}
  404. }
  405. return calculateExpiryTime(*oldestExecutionTime, duration, now)
  406. }
  407. // getLogsForBinding retrieves logs for a binding ID.
  408. func (e *Executor) getLogsForBinding(bindingId string) []*InternalLogEntry {
  409. e.logmutex.RLock()
  410. logs, found := e.LogsByBindingId[bindingId]
  411. e.logmutex.RUnlock()
  412. if !found || len(logs) == 0 {
  413. return nil
  414. }
  415. return logs
  416. }
  417. // calculateMaxExpiryTimeFromRates calculates the maximum expiry time across all rate limit rules.
  418. func calculateMaxExpiryTimeFromRates(rates []config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  419. var maxExpiryTime time.Time
  420. for _, rate := range rates {
  421. expiryTime := calculateExpiryForRate(rate, logs, now)
  422. updateMaxExpiryTime(&maxExpiryTime, expiryTime)
  423. }
  424. return maxExpiryTime
  425. }
  426. // GetTimeUntilAvailable calculates when an action will be available again based on rate limits.
  427. // Returns the Unix timestamp in seconds when the rate limit expires, or 0 if the action is available now.
  428. func (e *Executor) GetTimeUntilAvailable(binding *ActionBinding) int64 {
  429. if len(binding.Action.MaxRate) == 0 {
  430. return 0
  431. }
  432. logs := e.getLogsForBinding(binding.ID)
  433. if logs == nil {
  434. return 0
  435. }
  436. maxExpiryTime := calculateMaxExpiryTimeFromRates(binding.Action.MaxRate, logs, time.Now())
  437. if maxExpiryTime.IsZero() {
  438. return 0
  439. }
  440. return maxExpiryTime.Unix()
  441. }
  442. func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) string {
  443. e.logmutex.Lock()
  444. defer e.logmutex.Unlock()
  445. if _, found := e.logs[trackingID]; found || !isValidTrackingID(trackingID) {
  446. trackingID = uuid.NewString()
  447. entry.ExecutionTrackingID = trackingID
  448. }
  449. entry.Index = int64(len(e.logsTrackingIdsByDate))
  450. e.logs[trackingID] = entry
  451. e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
  452. return trackingID
  453. }
  454. // ExecRequest processes an ExecutionRequest
  455. func (e *Executor) ExecRequest(req *ExecutionRequest) (*sync.WaitGroup, string) {
  456. e.initializeExecRequest(req)
  457. log.Tracef("executor.ExecRequest(): trackingID=%s bindingID=%s", req.TrackingID, bindingIDForTrace(req))
  458. req.TrackingID = e.SetLog(req.TrackingID, req.logEntry)
  459. wg := new(sync.WaitGroup)
  460. wg.Add(1)
  461. go func() {
  462. queued := e.execChain(req, wg)
  463. if !queued {
  464. wg.Done()
  465. }
  466. }()
  467. return wg, req.TrackingID
  468. }
  469. func (e *Executor) initializeExecRequest(req *ExecutionRequest) {
  470. if req.AuthenticatedUser == nil {
  471. req.AuthenticatedUser = auth.UserGuest(req.Cfg)
  472. }
  473. req.executor = e
  474. req.logEntry = &InternalLogEntry{
  475. Binding: req.Binding,
  476. DatetimeStarted: time.Now(),
  477. ExecutionTrackingID: req.TrackingID,
  478. Output: "",
  479. ExitCode: DefaultExitCodeNotExecuted,
  480. ExecutionStarted: false,
  481. ExecutionFinished: false,
  482. ActionTitle: "notfound",
  483. ActionIcon: "&#x1f4a9;",
  484. Username: req.AuthenticatedUser.Username,
  485. }
  486. }
  487. func bindingIDForTrace(req *ExecutionRequest) string {
  488. if req.Binding == nil {
  489. return ""
  490. }
  491. return req.Binding.ID
  492. }
  493. func (e *Executor) execChain(req *ExecutionRequest, wg *sync.WaitGroup) bool {
  494. if !req.skipRequestRegistration {
  495. finished, queued := e.registerOrQueueRequest(req, wg)
  496. if finished || queued {
  497. return queued
  498. }
  499. }
  500. e.runExecutionSteps(req)
  501. e.finishExecChain(req)
  502. return false
  503. }
  504. func (e *Executor) registerOrQueueRequest(req *ExecutionRequest, wg *sync.WaitGroup) (finished bool, queued bool) {
  505. if !stepRequestAction(req) {
  506. e.finishExecChain(req)
  507. return true, false
  508. }
  509. if e.finishIfConcurrencyBlocked(req) {
  510. return true, false
  511. }
  512. return e.queueRequestIfGroupLimited(req, wg)
  513. }
  514. func (e *Executor) finishIfConcurrencyBlocked(req *ExecutionRequest) bool {
  515. if actionNeedsGroupLimit(req) {
  516. return false
  517. }
  518. if stepConcurrencyCheck(req) {
  519. return false
  520. }
  521. e.finishExecChain(req)
  522. return true
  523. }
  524. func (e *Executor) queueRequestIfGroupLimited(req *ExecutionRequest, wg *sync.WaitGroup) (finished bool, queued bool) {
  525. if !actionNeedsGroupLimit(req) || e.groupsHaveCapacityForActive(req) {
  526. return false, false
  527. }
  528. return e.queueRequestAfterACL(req, wg)
  529. }
  530. func (e *Executor) queueRequestAfterACL(req *ExecutionRequest, wg *sync.WaitGroup) (finished bool, queued bool) {
  531. if !stepACLCheck(req) {
  532. e.finishExecChain(req)
  533. return true, false
  534. }
  535. if e.queueRequest(req, wg) {
  536. e.finishExecChain(req)
  537. return true, false
  538. }
  539. notifyListenersStarted(req)
  540. return false, true
  541. }
  542. func (e *Executor) runExecutionSteps(req *ExecutionRequest) {
  543. for _, step := range e.chainOfCommand[1:] {
  544. if !step(req) {
  545. break
  546. }
  547. }
  548. }
  549. func (e *Executor) finishExecChain(req *ExecutionRequest) {
  550. req.mutateLogEntry(func(entry *InternalLogEntry) {
  551. if entry.DatetimeFinished.IsZero() {
  552. entry.DatetimeFinished = time.Now()
  553. }
  554. entry.ExecutionFinished = true
  555. })
  556. recordExecutionMetrics(req.logEntry)
  557. notifyListenersFinished(req)
  558. e.drainGroupQueue()
  559. }
  560. func getConcurrentCount(req *ExecutionRequest) int {
  561. concurrentCount := 0
  562. req.executor.logmutex.RLock()
  563. logs := req.executor.LogsByBindingId[req.Binding.ID]
  564. for _, logEntry := range logs {
  565. if !logEntry.ExecutionFinished && !logEntry.Queued {
  566. concurrentCount += 1
  567. }
  568. }
  569. req.executor.logmutex.RUnlock()
  570. return concurrentCount
  571. }
  572. func stepConcurrencyCheck(req *ExecutionRequest) bool {
  573. if actionNeedsGroupLimit(req) {
  574. return true
  575. }
  576. concurrentCount := getConcurrentCount(req)
  577. // Note that the current execution is counted int the logs, so when checking we +1
  578. if concurrentCount >= (req.Binding.Action.MaxConcurrent + 1) {
  579. log.WithFields(log.Fields{
  580. "actionTitle": req.logEntry.ActionTitle,
  581. "concurrentCount": concurrentCount,
  582. "maxConcurrent": req.Binding.Action.MaxConcurrent,
  583. }).Warnf("Blocked from executing due to concurrency limit")
  584. req.mutateLogEntry(func(entry *InternalLogEntry) {
  585. entry.Output = "Blocked from executing due to concurrency limit"
  586. entry.Blocked = true
  587. })
  588. return false
  589. }
  590. return true
  591. }
  592. func parseDuration(rate config.RateSpec) time.Duration {
  593. duration, err := time.ParseDuration(rate.Duration)
  594. if err != nil {
  595. log.Warnf("Could not parse duration: %v", rate.Duration)
  596. return -1 * time.Minute
  597. }
  598. return duration
  599. }
  600. func entityPrefixForRequest(req *ExecutionRequest) string {
  601. if req.Binding != nil && req.Binding.Entity != nil {
  602. return req.Binding.Entity.UniqueKey
  603. }
  604. return ""
  605. }
  606. func rateExecutionMatchesScope(logEntry *InternalLogEntry, req *ExecutionRequest, entityPrefix string) bool {
  607. if logEntry.EntityPrefix != entityPrefix {
  608. return false
  609. }
  610. return !logEntry.Queued && logEntry.ExecutionTrackingID != req.TrackingID
  611. }
  612. func logEntryStartedInWindow(logEntry *InternalLogEntry, windowStart time.Time) bool {
  613. return logEntry.DatetimeStarted.After(windowStart) && !logEntry.Blocked
  614. }
  615. func rateExecutionCountsForRate(logEntry *InternalLogEntry, req *ExecutionRequest, entityPrefix string, windowStart time.Time) bool {
  616. return rateExecutionMatchesScope(logEntry, req, entityPrefix) && logEntryStartedInWindow(logEntry, windowStart)
  617. }
  618. func countRateExecutions(logs []*InternalLogEntry, req *ExecutionRequest, entityPrefix string, windowStart time.Time) int {
  619. executions := 0
  620. for _, logEntry := range logs {
  621. if rateExecutionCountsForRate(logEntry, req, entityPrefix, windowStart) {
  622. executions += 1
  623. }
  624. }
  625. return executions
  626. }
  627. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  628. duration := parseDuration(rate)
  629. then := time.Now().Add(-duration)
  630. req.executor.logmutex.RLock()
  631. logs := req.executor.LogsByBindingId[req.Binding.ID]
  632. executions := countRateExecutions(logs, req, entityPrefixForRequest(req), then)
  633. req.executor.logmutex.RUnlock()
  634. return executions
  635. }
  636. func stepRateCheck(req *ExecutionRequest) bool {
  637. for _, rate := range req.Binding.Action.MaxRate {
  638. executions := getExecutionsCount(rate, req)
  639. if executions >= rate.Limit {
  640. log.WithFields(log.Fields{
  641. "actionTitle": req.logEntry.ActionTitle,
  642. "executions": executions,
  643. "limit": rate.Limit,
  644. "duration": rate.Duration,
  645. }).Infof("Blocked from executing due to rate limit")
  646. req.mutateLogEntry(func(entry *InternalLogEntry) {
  647. entry.Output = "Blocked from executing due to rate limit"
  648. entry.Blocked = true
  649. })
  650. return false
  651. }
  652. }
  653. return true
  654. }
  655. func stepACLCheck(req *ExecutionRequest) bool {
  656. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Binding.Action)
  657. if !canExec {
  658. req.mutateLogEntry(func(entry *InternalLogEntry) {
  659. entry.Output = "ACL check failed. Blocked from executing."
  660. entry.Blocked = true
  661. })
  662. log.WithFields(log.Fields{
  663. "actionTitle": req.logEntry.ActionTitle,
  664. }).Warnf("ACL check failed. Blocked from executing.")
  665. }
  666. return canExec
  667. }
  668. func stepParseArgs(req *ExecutionRequest) bool {
  669. ensureArgumentMap(req)
  670. if !hasBindingAndAction(req) {
  671. return fail(req, fmt.Errorf("cannot parse arguments: Binding or Action is nil"))
  672. }
  673. filterToDefinedArgumentsOnly(req)
  674. if err := injectSystemArgs(req); err != nil {
  675. return fail(req, err)
  676. }
  677. mangleInvalidArgumentValues(req)
  678. if hasExec(req) {
  679. return handleExecBranch(req)
  680. } else {
  681. return handleShellBranch(req)
  682. }
  683. }
  684. func handleExecBranch(req *ExecutionRequest) bool {
  685. args, err := parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
  686. if err != nil {
  687. return fail(req, err)
  688. }
  689. req.useDirectExec = true
  690. req.execArgs = args
  691. return true
  692. }
  693. func handleShellBranch(req *ExecutionRequest) bool {
  694. if hasWebhookTag(req) {
  695. return fail(req, fmt.Errorf("webhooks cannot use Shell execution; use exec instead. See https://docs.olivetin.app/action_execution/shellvsexec.html"))
  696. }
  697. if err := checkShellArgumentSafety(req.Binding.Action); err != nil {
  698. return fail(req, err)
  699. }
  700. cmd, err := parseActionArguments(req)
  701. if err != nil {
  702. return fail(req, err)
  703. }
  704. req.useDirectExec = false
  705. req.finalParsedCommand = cmd
  706. return true
  707. }
  708. func ensureArgumentMap(req *ExecutionRequest) {
  709. if req.Arguments == nil {
  710. req.Arguments = make(map[string]string)
  711. }
  712. }
  713. func filterToDefinedArgumentsOnly(req *ExecutionRequest) {
  714. definedNames := make(map[string]struct{})
  715. for _, arg := range req.Binding.Action.Arguments {
  716. definedNames[arg.Name] = struct{}{}
  717. }
  718. filtered := make(map[string]string)
  719. for k, v := range req.Arguments {
  720. if keepArgument(k, definedNames) {
  721. filtered[k] = v
  722. }
  723. }
  724. req.Arguments = filtered
  725. }
  726. func keepArgument(name string, definedNames map[string]struct{}) bool {
  727. _, ok := definedNames[name]
  728. return ok
  729. }
  730. func hasWebhookTag(req *ExecutionRequest) bool {
  731. for _, tag := range req.Tags {
  732. if tag == "webhook" {
  733. return true
  734. }
  735. }
  736. return false
  737. }
  738. var systemArgumentDefinitions = []config.ActionArgument{
  739. {Name: "ot_executionTrackingId", Type: "ascii_identifier", RejectNull: true},
  740. {Name: "ot_username", Type: "shell_safe_identifier", RejectNull: true},
  741. }
  742. func injectSystemArgs(req *ExecutionRequest) error {
  743. args, err := validatedSystemArgs(req)
  744. if err != nil {
  745. return err
  746. }
  747. for name, value := range args {
  748. req.Arguments[name] = value
  749. }
  750. return nil
  751. }
  752. func validatedSystemArgs(req *ExecutionRequest) (map[string]string, error) {
  753. values := map[string]string{
  754. "ot_executionTrackingId": req.TrackingID,
  755. "ot_username": req.AuthenticatedUser.Username,
  756. }
  757. for i := range systemArgumentDefinitions {
  758. arg := &systemArgumentDefinitions[i]
  759. if err := ValidateArgument(arg, values[arg.Name], req.Binding.Action); err != nil {
  760. return nil, fmt.Errorf("system argument %q failed validation: %w", arg.Name, err)
  761. }
  762. }
  763. return values, nil
  764. }
  765. func hasBindingAndAction(req *ExecutionRequest) bool {
  766. return !(req.Binding == nil || req.Binding.Action == nil)
  767. }
  768. func hasExec(req *ExecutionRequest) bool {
  769. return len(req.Binding.Action.Exec) > 0
  770. }
  771. func fail(req *ExecutionRequest, err error) bool {
  772. req.mutateLogEntry(func(entry *InternalLogEntry) {
  773. entry.Output = err.Error()
  774. })
  775. log.Warn(err.Error())
  776. return false
  777. }
  778. func stepRequestAction(req *ExecutionRequest) bool {
  779. metricActionsRequested.Inc()
  780. if !stepRequestActionHasBinding(req) {
  781. return false
  782. }
  783. stepRequestActionPopulateLogEntry(req)
  784. stepRequestActionRegisterLog(req)
  785. log.WithFields(log.Fields{
  786. "actionTitle": req.logEntry.ActionTitle,
  787. "tags": req.Tags,
  788. }).Infof("Action requested")
  789. notifyListenersStarted(req)
  790. return true
  791. }
  792. func stepRequestActionHasBinding(req *ExecutionRequest) bool {
  793. if req.Binding == nil || req.Binding.Action == nil {
  794. log.Warnf("Action request has no binding/action; skipping execution")
  795. return false
  796. }
  797. return true
  798. }
  799. func stepRequestActionPopulateLogEntry(req *ExecutionRequest) {
  800. req.mutateLogEntry(func(entry *InternalLogEntry) {
  801. entry.Binding = req.Binding
  802. entry.ActionConfigTitle = req.Binding.Action.Title
  803. entry.ActionTitle = tpl.ParseTemplateOfActionBeforeExec(req.Binding.Action.Title, req.Binding.Entity)
  804. entry.ActionIcon = tpl.ParseTemplateOfActionBeforeExec(req.Binding.Action.Icon, req.Binding.Entity)
  805. entry.Tags = req.Tags
  806. entry.Justification = ResolveJustification(req)
  807. if req.Binding.Entity != nil {
  808. entry.EntityPrefix = req.Binding.Entity.UniqueKey
  809. }
  810. })
  811. }
  812. func stepRequestActionRegisterLog(req *ExecutionRequest) {
  813. req.executor.logmutex.Lock()
  814. defer req.executor.logmutex.Unlock()
  815. if _, containsKey := req.executor.LogsByBindingId[req.Binding.ID]; !containsKey {
  816. req.executor.LogsByBindingId[req.Binding.ID] = make([]*InternalLogEntry, 0)
  817. }
  818. req.executor.LogsByBindingId[req.Binding.ID] = append(req.executor.LogsByBindingId[req.Binding.ID], req.logEntry)
  819. }
  820. func stepLogStart(req *ExecutionRequest) bool {
  821. log.WithFields(log.Fields{
  822. "actionTitle": req.logEntry.ActionTitle,
  823. "timeout": req.Binding.Action.Timeout,
  824. }).Infof("Action started")
  825. return true
  826. }
  827. func stepLogFinish(req *ExecutionRequest) bool {
  828. req.mutateLogEntry(func(entry *InternalLogEntry) {
  829. entry.ExecutionFinished = true
  830. })
  831. log.WithFields(log.Fields{
  832. "actionTitle": req.logEntry.ActionTitle,
  833. "outputLength": len(req.logEntry.Output),
  834. "timedOut": req.logEntry.TimedOut,
  835. "exit": req.logEntry.ExitCode,
  836. }).Infof("Action finished")
  837. return true
  838. }
  839. func notifyListenersFinished(req *ExecutionRequest) {
  840. for _, listener := range req.executor.copyListeners() {
  841. listener.OnExecutionFinished(req.logEntry)
  842. }
  843. }
  844. func notifyListenersStarted(req *ExecutionRequest) {
  845. for _, listener := range req.executor.copyListeners() {
  846. listener.OnExecutionStarted(req.logEntry)
  847. }
  848. }
  849. func appendErrorToStderr(req *ExecutionRequest, err error) {
  850. if err == nil {
  851. return
  852. }
  853. req.mutateLogEntry(func(entry *InternalLogEntry) {
  854. entry.Output = err.Error() + "\n\n" + entry.Output
  855. })
  856. }
  857. type OutputStreamer struct {
  858. Req *ExecutionRequest
  859. output bytes.Buffer
  860. }
  861. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  862. for _, listener := range ost.Req.executor.copyListeners() {
  863. listener.OnOutputChunk(o, ost.Req.TrackingID)
  864. }
  865. return ost.output.Write(o)
  866. }
  867. func (ost *OutputStreamer) String() string {
  868. return ost.output.String()
  869. }
  870. func buildEnv(args map[string]string) []string {
  871. ret := append(os.Environ(), "OLIVETIN=1")
  872. for k, v := range args {
  873. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  874. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  875. if varName == "" {
  876. continue
  877. }
  878. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  879. }
  880. return ret
  881. }
  882. func commandExitCode(cmd *exec.Cmd) int {
  883. if cmd == nil || cmd.ProcessState == nil {
  884. return -1
  885. }
  886. return cmd.ProcessState.ExitCode()
  887. }
  888. func stepExec(req *ExecutionRequest) bool {
  889. ctx, cancel := newTimeoutContext(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second, req.executor)
  890. defer cancel()
  891. streamer := &OutputStreamer{Req: req}
  892. cmd := buildCommand(ctx, req)
  893. if cmd == nil {
  894. req.mutateLogEntry(func(entry *InternalLogEntry) {
  895. entry.Output = "Cannot execute: no command arguments provided"
  896. })
  897. log.Warn("Cannot execute: no command arguments provided")
  898. return false
  899. }
  900. prepareCommand(cmd, streamer, req)
  901. runerr := cmd.Start()
  902. req.mutateLogEntry(func(entry *InternalLogEntry) {
  903. entry.Process = cmd.Process
  904. })
  905. ctx.setProcess(cmd.Process)
  906. waiterr := cmd.Wait()
  907. req.mutateLogEntry(func(entry *InternalLogEntry) {
  908. entry.ExitCode = int32(commandExitCode(cmd))
  909. entry.Output = streamer.String()
  910. })
  911. appendErrorToStderr(req, runerr)
  912. appendErrorToStderr(req, waiterr)
  913. if ctx.Err() == context.DeadlineExceeded {
  914. log.WithFields(log.Fields{
  915. "actionTitle": req.logEntry.ActionTitle,
  916. }).Warnf("Action timed out")
  917. req.mutateLogEntry(func(entry *InternalLogEntry) {
  918. entry.TimedOut = true
  919. entry.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."
  920. })
  921. }
  922. req.mutateLogEntry(func(entry *InternalLogEntry) {
  923. entry.DatetimeFinished = time.Now()
  924. })
  925. return true
  926. }
  927. func buildCommand(ctx context.Context, req *ExecutionRequest) *exec.Cmd {
  928. if req.useDirectExec {
  929. return wrapCommandDirect(ctx, req.execArgs)
  930. }
  931. return wrapCommandInShell(ctx, req.finalParsedCommand)
  932. }
  933. func prepareCommand(cmd *exec.Cmd, streamer *OutputStreamer, req *ExecutionRequest) {
  934. cmd.Stdout = streamer
  935. cmd.Stderr = streamer
  936. cmd.Env = buildEnv(req.Arguments)
  937. started := false
  938. req.mutateLogEntry(func(entry *InternalLogEntry) {
  939. if entry.ExecutionStarted {
  940. return
  941. }
  942. entry.ExecutionStarted = true
  943. started = true
  944. })
  945. if started {
  946. notifyListenersStarted(req)
  947. }
  948. }
  949. func stepExecAfter(req *ExecutionRequest) bool {
  950. ctx, cancel := newTimeoutContext(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second, req.executor)
  951. defer cancel()
  952. var stdout bytes.Buffer
  953. var stderr bytes.Buffer
  954. cmd, args, err := buildShellAfterCommand(ctx, req, &stdout, &stderr)
  955. if err != nil {
  956. return fail(req, err)
  957. }
  958. if cmd == nil {
  959. return true
  960. }
  961. cmd.Env = buildEnv(args)
  962. runerr := cmd.Start()
  963. ctx.setProcess(cmd.Process)
  964. waiterr := cmd.Wait()
  965. req.mutateLogEntry(func(entry *InternalLogEntry) {
  966. entry.Output += "\n"
  967. entry.Output += "OliveTin::shellAfterCompleted stdout\n"
  968. entry.Output += stdout.String()
  969. entry.Output += "OliveTin::shellAfterCompleted stderr\n"
  970. entry.Output += stderr.String()
  971. entry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  972. })
  973. appendErrorToStderr(req, runerr)
  974. appendErrorToStderr(req, waiterr)
  975. if ctx.Err() == context.DeadlineExceeded {
  976. req.mutateLogEntry(func(entry *InternalLogEntry) {
  977. entry.Output += "Your shellAfterCompleted command timed out."
  978. })
  979. }
  980. req.mutateLogEntry(func(entry *InternalLogEntry) {
  981. entry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", commandExitCode(cmd))
  982. entry.Output += "OliveTin::shellAfterCompleted output complete\n"
  983. })
  984. return true
  985. }
  986. func buildShellAfterCommand(ctx context.Context, req *ExecutionRequest, stdout, stderr *bytes.Buffer) (*exec.Cmd, map[string]string, error) {
  987. if req.Binding.Action.ShellAfterCompleted == "" {
  988. return nil, nil, nil
  989. }
  990. args, err := buildShellAfterArgs(req)
  991. if err != nil {
  992. return nil, nil, err
  993. }
  994. finalParsedCommand, err := tpl.ParseTemplateWithActionContext(req.Binding.Action.ShellAfterCompleted, req.Binding.Entity, args)
  995. if err != nil {
  996. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  997. req.mutateLogEntry(func(entry *InternalLogEntry) {
  998. entry.Output += msg
  999. })
  1000. log.Warn(msg)
  1001. return nil, nil, nil
  1002. }
  1003. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  1004. cmd.Stdout = stdout
  1005. cmd.Stderr = stderr
  1006. return cmd, args, nil
  1007. }
  1008. func buildShellAfterArgs(req *ExecutionRequest) (map[string]string, error) {
  1009. args, err := validatedSystemArgs(req)
  1010. if err != nil {
  1011. return nil, err
  1012. }
  1013. args["output"] = req.logEntry.Output
  1014. args["exitCode"] = fmt.Sprintf("%v", req.logEntry.ExitCode)
  1015. return args, nil
  1016. }
  1017. //gocyclo:ignore
  1018. func stepTrigger(req *ExecutionRequest) bool {
  1019. if req.Binding.Action.Triggers == nil {
  1020. return true
  1021. }
  1022. if req.TriggerDepth >= MaxTriggerDepth {
  1023. log.WithFields(log.Fields{
  1024. "actionTitle": req.logEntry.ActionTitle,
  1025. "depth": req.TriggerDepth,
  1026. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  1027. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1028. entry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  1029. })
  1030. return true
  1031. }
  1032. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  1033. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  1034. }
  1035. triggerLoop(req)
  1036. return true
  1037. }
  1038. func triggerLoop(req *ExecutionRequest) {
  1039. for _, triggerTitle := range req.Binding.Action.Triggers {
  1040. binding := req.executor.findBindingByActionTitle(triggerTitle, "")
  1041. if binding == nil {
  1042. log.WithFields(log.Fields{
  1043. "triggerTitle": triggerTitle,
  1044. "fromAction": req.logEntry.ActionTitle,
  1045. }).Warnf("Trigger references unknown action title; skipping")
  1046. continue
  1047. }
  1048. trigger := &ExecutionRequest{
  1049. Binding: binding,
  1050. TrackingID: uuid.NewString(),
  1051. Tags: []string{"trigger"},
  1052. AuthenticatedUser: req.AuthenticatedUser,
  1053. Arguments: req.Arguments,
  1054. Cfg: req.Cfg,
  1055. TriggerDepth: req.TriggerDepth + 1,
  1056. Justification: fmt.Sprintf("Triggered by action: %s", req.logEntry.ActionTitle),
  1057. }
  1058. req.executor.ExecRequest(trigger)
  1059. }
  1060. }
  1061. func stepSaveLog(req *ExecutionRequest) bool {
  1062. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  1063. saveLogResults(req, filename)
  1064. saveLogOutput(req, filename)
  1065. return true
  1066. }
  1067. func firstNonEmpty(one, two string) string {
  1068. if one != "" {
  1069. return one
  1070. }
  1071. return two
  1072. }
  1073. func saveLogResults(req *ExecutionRequest, filename string) {
  1074. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  1075. if dir != "" {
  1076. data, err := yaml.Marshal(req.logEntry)
  1077. if err != nil {
  1078. log.Warnf("%v", err)
  1079. }
  1080. filepath := path.Join(dir, filename+".yaml")
  1081. err = os.WriteFile(filepath, data, 0600)
  1082. if err != nil {
  1083. log.Warnf("%v", err)
  1084. }
  1085. }
  1086. }
  1087. func saveLogOutput(req *ExecutionRequest, filename string) {
  1088. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  1089. if dir != "" {
  1090. data := req.logEntry.Output
  1091. filepath := path.Join(dir, filename+".log")
  1092. err := os.WriteFile(filepath, []byte(data), 0600)
  1093. if err != nil {
  1094. log.Warnf("%v", err)
  1095. }
  1096. }
  1097. }