executor.go 35 KB

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