executor.go 42 KB

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