executor.go 40 KB

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