executor.go 40 KB

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