executor.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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/google/uuid"
  9. log "github.com/sirupsen/logrus"
  10. "github.com/prometheus/client_golang/prometheus"
  11. "github.com/prometheus/client_golang/prometheus/promauto"
  12. "gopkg.in/yaml.v3"
  13. "bytes"
  14. "context"
  15. "fmt"
  16. "os"
  17. "os/exec"
  18. "path"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. const (
  24. DefaultExitCodeNotExecuted = -1337
  25. MaxTriggerDepth = 10
  26. )
  27. var (
  28. metricActionsRequested = promauto.NewCounter(prometheus.CounterOpts{
  29. Name: "olivetin_actions_requested_count",
  30. Help: "The actions requested count",
  31. })
  32. )
  33. type ActionBinding struct {
  34. ID string
  35. Action *config.Action
  36. Entity *entities.Entity
  37. ConfigOrder int
  38. IsOnDashboard bool
  39. }
  40. // Executor represents a helper class for executing commands. It's main method
  41. // is ExecRequest
  42. type Executor struct {
  43. logs map[string]*InternalLogEntry
  44. logsTrackingIdsByDate []string
  45. LogsByBindingId map[string][]*InternalLogEntry
  46. logmutex sync.RWMutex
  47. MapActionBindings map[string]*ActionBinding
  48. MapActionBindingsLock sync.RWMutex
  49. Cfg *config.Config
  50. listeners []listener
  51. chainOfCommand []executorStepFunc
  52. }
  53. // ExecutionRequest is a request to execute an action. It's passed to an
  54. // Executor. They're created from the api.
  55. type ExecutionRequest struct {
  56. Binding *ActionBinding
  57. Arguments map[string]string
  58. TrackingID string
  59. Tags []string
  60. Cfg *config.Config
  61. AuthenticatedUser *authpublic.AuthenticatedUser
  62. TriggerDepth int
  63. logEntry *InternalLogEntry
  64. finalParsedCommand string
  65. execArgs []string
  66. useDirectExec bool
  67. executor *Executor
  68. }
  69. // InternalLogEntry objects are created by an Executor, and represent the final
  70. // state of execution (even if the command is not executed). It's designed to be
  71. // easily serializable.
  72. type InternalLogEntry struct {
  73. Binding *ActionBinding
  74. DatetimeStarted time.Time
  75. DatetimeFinished time.Time
  76. Output string
  77. TimedOut bool
  78. Blocked bool
  79. ExitCode int32
  80. Tags []string
  81. ExecutionStarted bool
  82. ExecutionFinished bool
  83. ExecutionTrackingID string
  84. Process *os.Process
  85. Username string
  86. Index int64
  87. EntityPrefix string
  88. ActionConfigTitle string // This is the title of the action as defined in the config, not the final parsed title.
  89. /*
  90. The following 3 properties are obviously on Action normally, but it's useful
  91. that logs are lightweight (so we don't need to have an action associated to
  92. logs, etc. Therefore, we duplicate those values here.
  93. */
  94. ActionTitle string
  95. ActionIcon string
  96. }
  97. type executorStepFunc func(*ExecutionRequest) bool
  98. // DefaultExecutor returns an Executor, with a sensible "chain of command" for
  99. // executing actions.
  100. func DefaultExecutor(cfg *config.Config) *Executor {
  101. e := Executor{}
  102. e.Cfg = cfg
  103. e.logs = make(map[string]*InternalLogEntry)
  104. e.logsTrackingIdsByDate = make([]string, 0)
  105. e.LogsByBindingId = make(map[string][]*InternalLogEntry)
  106. e.MapActionBindings = make(map[string]*ActionBinding)
  107. e.chainOfCommand = []executorStepFunc{
  108. stepRequestAction,
  109. stepConcurrencyCheck,
  110. stepRateCheck,
  111. stepACLCheck,
  112. stepParseArgs,
  113. stepLogStart,
  114. stepExec,
  115. stepExecAfter,
  116. stepLogFinish,
  117. stepSaveLog,
  118. stepTrigger,
  119. }
  120. return &e
  121. }
  122. type listener interface {
  123. OnExecutionStarted(logEntry *InternalLogEntry)
  124. OnExecutionFinished(logEntry *InternalLogEntry)
  125. OnOutputChunk(o []byte, executionTrackingId string)
  126. OnActionMapRebuilt()
  127. }
  128. func (e *Executor) AddListener(m listener) {
  129. e.listeners = append(e.listeners, m)
  130. }
  131. // getPagingStartIndex calculates the starting index for log pagination.
  132. // Parameters:
  133. //
  134. // startOffset: The offset from the most recent log (0 means start from the most recent)
  135. // totalLogCount: Total number of logs available
  136. // count: Number of logs to retrieve
  137. //
  138. // Returns: The calculated starting index for pagination
  139. func getPagingStartIndex(startOffset int64, totalLogCount int64) int64 {
  140. var startIndex int64
  141. if startOffset <= 0 {
  142. startIndex = totalLogCount
  143. } else {
  144. startIndex = (totalLogCount - startOffset)
  145. if startIndex < 0 {
  146. startIndex = 1
  147. }
  148. }
  149. return startIndex - 1
  150. }
  151. type PagingResult struct {
  152. CountRemaining int64
  153. PageSize int64
  154. TotalCount int64
  155. StartOffset int64
  156. }
  157. func (e *Executor) GetLogTrackingIds(startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  158. pagingResult := &PagingResult{
  159. CountRemaining: 0,
  160. PageSize: pageCount,
  161. TotalCount: 0,
  162. StartOffset: startOffset,
  163. }
  164. e.logmutex.RLock()
  165. totalLogCount := int64(len(e.logsTrackingIdsByDate))
  166. pagingResult.TotalCount = totalLogCount
  167. startIndex := getPagingStartIndex(startOffset, totalLogCount)
  168. pageCount = min(totalLogCount, pageCount)
  169. endIndex := max(0, (startIndex-pageCount)+1)
  170. log.WithFields(log.Fields{
  171. "startOffset": startOffset,
  172. "pageCount": pageCount,
  173. "total": totalLogCount,
  174. "startIndex": startIndex,
  175. "endIndex": endIndex,
  176. }).Tracef("GetLogTrackingIds")
  177. trackingIds := make([]*InternalLogEntry, 0, pageCount)
  178. if totalLogCount > 0 {
  179. for i := endIndex; i <= startIndex; i++ {
  180. trackingIds = append(trackingIds, e.logs[e.logsTrackingIdsByDate[i]])
  181. }
  182. }
  183. e.logmutex.RUnlock()
  184. pagingResult.CountRemaining = endIndex
  185. return trackingIds, pagingResult
  186. }
  187. // isValidLogEntryForACL checks if a log entry has all required fields for ACL checking.
  188. func isValidLogEntryForACL(entry *InternalLogEntry) bool {
  189. return entry != nil && entry.Binding != nil && entry.Binding.Action != nil
  190. }
  191. // isLogEntryAllowedByACL checks if a log entry is allowed to be viewed by the user.
  192. func isLogEntryAllowedByACL(cfg *config.Config, user *authpublic.AuthenticatedUser, entry *InternalLogEntry) bool {
  193. return acl.IsAllowedLogs(cfg, user, entry.Binding.Action)
  194. }
  195. // parseDateFilter parses a date filter string and returns the parsed date and validity.
  196. func parseDateFilter(dateFilter string) (time.Time, bool) {
  197. if dateFilter == "" {
  198. return time.Time{}, false
  199. }
  200. parsedDate, err := time.Parse("2006-01-02", dateFilter)
  201. if err != nil {
  202. log.WithFields(log.Fields{
  203. "dateFilter": dateFilter,
  204. "error": err,
  205. }).Errorf("Failed to parse date filter, expected format YYYY-MM-DD")
  206. return time.Time{}, false
  207. }
  208. return parsedDate, true
  209. }
  210. // matchesDateFilter checks if an entry matches the date filter criteria.
  211. func matchesDateFilter(entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  212. if !hasDateFilter {
  213. return true
  214. }
  215. entryDate := entry.DatetimeStarted.UTC().Truncate(24 * time.Hour)
  216. filterDateUTC := filterDate.UTC().Truncate(24 * time.Hour)
  217. return entryDate.Equal(filterDateUTC)
  218. }
  219. // shouldIncludeLogEntry determines if a log entry should be included in filtered results.
  220. func shouldIncludeLogEntry(cfg *config.Config, user *authpublic.AuthenticatedUser, entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  221. if !isValidLogEntryForACL(entry) {
  222. return false
  223. }
  224. if !isLogEntryAllowedByACL(cfg, user, entry) {
  225. return false
  226. }
  227. return matchesDateFilter(entry, filterDate, hasDateFilter)
  228. }
  229. func (e *Executor) filterLogsByACL(cfg *config.Config, user *authpublic.AuthenticatedUser, dateFilter string) []*InternalLogEntry {
  230. e.logmutex.RLock()
  231. defer e.logmutex.RUnlock()
  232. filtered := make([]*InternalLogEntry, 0, len(e.logsTrackingIdsByDate))
  233. filterDate, hasDateFilter := parseDateFilter(dateFilter)
  234. for _, trackingId := range e.logsTrackingIdsByDate {
  235. entry := e.logs[trackingId]
  236. if shouldIncludeLogEntry(cfg, user, entry, filterDate, hasDateFilter) {
  237. filtered = append(filtered, entry)
  238. }
  239. }
  240. return filtered
  241. }
  242. // parseDateFilter parses the date filter string and returns filter information.
  243. func parseDateFilter(dateFilter string) (filterDate time.Time, hasDateFilter bool) {
  244. if dateFilter == "" {
  245. return time.Time{}, false
  246. }
  247. parsedDate, err := time.Parse("2006-01-02", dateFilter)
  248. if err != nil {
  249. log.WithFields(log.Fields{
  250. "dateFilter": dateFilter,
  251. "error": err,
  252. }).Errorf("Failed to parse date filter, expected format YYYY-MM-DD")
  253. return time.Time{}, false
  254. }
  255. return parsedDate, true
  256. }
  257. // shouldIncludeLogEntry determines if a log entry should be included based on ACL and date filter.
  258. func shouldIncludeLogEntry(cfg *config.Config, user *authpublic.AuthenticatedUser, entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  259. if !isValidLogEntryForACL(entry) {
  260. return false
  261. }
  262. if !isLogEntryAllowedByACL(cfg, user, entry) {
  263. return false
  264. }
  265. return matchesDateFilter(entry, filterDate, hasDateFilter)
  266. }
  267. // matchesDateFilter checks if the log entry matches the date filter.
  268. func matchesDateFilter(entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  269. if !hasDateFilter {
  270. return true
  271. }
  272. entryDate := entry.DatetimeStarted.UTC().Truncate(24 * time.Hour)
  273. filterDateUTC := filterDate.UTC().Truncate(24 * time.Hour)
  274. return entryDate.Equal(filterDateUTC)
  275. }
  276. // paginateFilteredLogs applies pagination to a filtered list of logs and returns
  277. // the paginated results along with pagination metadata.
  278. func paginateFilteredLogs(filtered []*InternalLogEntry, startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  279. total := int64(len(filtered))
  280. paging := &PagingResult{PageSize: pageCount, TotalCount: total, StartOffset: startOffset}
  281. if total == 0 {
  282. paging.CountRemaining = 0
  283. return []*InternalLogEntry{}, paging
  284. }
  285. startIndex := getPagingStartIndex(startOffset, total)
  286. pageCount = min(total, pageCount)
  287. endIndex := max(0, (startIndex-pageCount)+1)
  288. out := make([]*InternalLogEntry, 0, pageCount)
  289. for i := endIndex; i <= startIndex && i < int64(len(filtered)); i++ {
  290. out = append(out, filtered[i])
  291. }
  292. paging.CountRemaining = endIndex
  293. return out, paging
  294. }
  295. // GetLogTrackingIdsACL returns logs filtered by ACL visibility for the user and
  296. // paginated correctly based on the filtered set.
  297. // dateFilter is optional and should be in YYYY-MM-DD format. If empty, no date filtering is applied.
  298. func (e *Executor) GetLogTrackingIdsACL(cfg *config.Config, user *authpublic.AuthenticatedUser, startOffset int64, pageCount int64, dateFilter string) ([]*InternalLogEntry, *PagingResult) {
  299. filtered := e.filterLogsByACL(cfg, user, dateFilter)
  300. return paginateFilteredLogs(filtered, startOffset, pageCount)
  301. }
  302. func (e *Executor) GetLog(trackingID string) (*InternalLogEntry, bool) {
  303. e.logmutex.RLock()
  304. entry, found := e.logs[trackingID]
  305. e.logmutex.RUnlock()
  306. return entry, found
  307. }
  308. func (e *Executor) GetLogsByBindingId(bindingId string) []*InternalLogEntry {
  309. e.logmutex.RLock()
  310. logs, found := e.LogsByBindingId[bindingId]
  311. e.logmutex.RUnlock()
  312. if !found {
  313. return make([]*InternalLogEntry, 0)
  314. }
  315. return logs
  316. }
  317. // shouldCountExecution checks if a log entry should be counted for rate limiting.
  318. func shouldCountExecution(logEntry *InternalLogEntry, windowStart time.Time) bool {
  319. return !logEntry.Blocked && logEntry.DatetimeStarted.After(windowStart)
  320. }
  321. // updateOldestExecution updates the oldest execution time if this entry is older.
  322. func updateOldestExecution(oldestExecutionTime **time.Time, logEntry *InternalLogEntry) {
  323. if *oldestExecutionTime == nil {
  324. *oldestExecutionTime = &logEntry.DatetimeStarted
  325. } else if logEntry.DatetimeStarted.Before(**oldestExecutionTime) {
  326. *oldestExecutionTime = &logEntry.DatetimeStarted
  327. }
  328. }
  329. // findOldestExecutionInWindow finds the oldest execution within the time window and counts executions.
  330. // Returns the count of executions and the oldest execution time, or nil if none found.
  331. func findOldestExecutionInWindow(logs []*InternalLogEntry, windowStart time.Time) (int, *time.Time) {
  332. executions := 0
  333. var oldestExecutionTime *time.Time
  334. for _, logEntry := range logs {
  335. if !shouldCountExecution(logEntry, windowStart) {
  336. continue
  337. }
  338. executions++
  339. updateOldestExecution(&oldestExecutionTime, logEntry)
  340. }
  341. return executions, oldestExecutionTime
  342. }
  343. // calculateExpiryTime calculates when the oldest execution will fall outside the rate limit window.
  344. func calculateExpiryTime(oldestExecutionTime time.Time, duration time.Duration, now time.Time) time.Time {
  345. expiryTime := oldestExecutionTime.Add(duration)
  346. if !expiryTime.After(now) {
  347. return time.Time{}
  348. }
  349. return expiryTime
  350. }
  351. // updateMaxExpiryTime updates maxExpiryTime if expiryTime is later.
  352. func updateMaxExpiryTime(maxExpiryTime *time.Time, expiryTime time.Time) {
  353. if expiryTime.IsZero() {
  354. return
  355. }
  356. if maxExpiryTime.IsZero() || expiryTime.After(*maxExpiryTime) {
  357. *maxExpiryTime = expiryTime
  358. }
  359. }
  360. // calculateExpiryForRate calculates the expiry time for a single rate limit rule.
  361. // Returns the expiry time if the rate limit is exceeded, or zero time if not.
  362. func calculateExpiryForRate(rate config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  363. duration := parseDuration(rate)
  364. if duration <= 0 {
  365. return time.Time{}
  366. }
  367. windowStart := now.Add(-duration)
  368. executions, oldestExecutionTime := findOldestExecutionInWindow(logs, windowStart)
  369. if executions < rate.Limit || oldestExecutionTime == nil {
  370. return time.Time{}
  371. }
  372. return calculateExpiryTime(*oldestExecutionTime, duration, now)
  373. }
  374. // getLogsForBinding retrieves logs for a binding ID.
  375. func (e *Executor) getLogsForBinding(bindingId string) []*InternalLogEntry {
  376. e.logmutex.RLock()
  377. logs, found := e.LogsByBindingId[bindingId]
  378. e.logmutex.RUnlock()
  379. if !found || len(logs) == 0 {
  380. return nil
  381. }
  382. return logs
  383. }
  384. // calculateMaxExpiryTimeFromRates calculates the maximum expiry time across all rate limit rules.
  385. func calculateMaxExpiryTimeFromRates(rates []config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  386. var maxExpiryTime time.Time
  387. for _, rate := range rates {
  388. expiryTime := calculateExpiryForRate(rate, logs, now)
  389. updateMaxExpiryTime(&maxExpiryTime, expiryTime)
  390. }
  391. return maxExpiryTime
  392. }
  393. // GetTimeUntilAvailable calculates when an action will be available again based on rate limits.
  394. // Returns the Unix timestamp in seconds when the rate limit expires, or 0 if the action is available now.
  395. func (e *Executor) GetTimeUntilAvailable(binding *ActionBinding) int64 {
  396. if len(binding.Action.MaxRate) == 0 {
  397. return 0
  398. }
  399. logs := e.getLogsForBinding(binding.ID)
  400. if logs == nil {
  401. return 0
  402. }
  403. maxExpiryTime := calculateMaxExpiryTimeFromRates(binding.Action.MaxRate, logs, time.Now())
  404. if maxExpiryTime.IsZero() {
  405. return 0
  406. }
  407. return maxExpiryTime.Unix()
  408. }
  409. func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) {
  410. e.logmutex.Lock()
  411. entry.Index = int64(len(e.logsTrackingIdsByDate))
  412. e.logs[trackingID] = entry
  413. e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
  414. e.logmutex.Unlock()
  415. }
  416. // ExecRequest processes an ExecutionRequest
  417. func (e *Executor) ExecRequest(req *ExecutionRequest) (*sync.WaitGroup, string) {
  418. if req.AuthenticatedUser == nil {
  419. req.AuthenticatedUser = auth.UserGuest(req.Cfg)
  420. }
  421. req.executor = e
  422. req.logEntry = &InternalLogEntry{
  423. Binding: req.Binding,
  424. DatetimeStarted: time.Now(),
  425. ExecutionTrackingID: req.TrackingID,
  426. Output: "",
  427. ExitCode: DefaultExitCodeNotExecuted,
  428. ExecutionStarted: false,
  429. ExecutionFinished: false,
  430. ActionTitle: "notfound",
  431. ActionIcon: "&#x1f4a9;",
  432. Username: req.AuthenticatedUser.Username,
  433. }
  434. _, isDuplicate := e.GetLog(req.TrackingID)
  435. if isDuplicate || req.TrackingID == "" {
  436. req.TrackingID = uuid.NewString()
  437. }
  438. // Update the log entry with the final tracking ID
  439. req.logEntry.ExecutionTrackingID = req.TrackingID
  440. log.Tracef("executor.ExecRequest(): %v", req)
  441. e.SetLog(req.TrackingID, req.logEntry)
  442. wg := new(sync.WaitGroup)
  443. wg.Add(1)
  444. go func() {
  445. e.execChain(req)
  446. defer wg.Done()
  447. }()
  448. return wg, req.TrackingID
  449. }
  450. func (e *Executor) execChain(req *ExecutionRequest) {
  451. for _, step := range e.chainOfCommand {
  452. if !step(req) {
  453. break
  454. }
  455. }
  456. // Ensure DatetimeFinished is set even if execution was blocked early
  457. if req.logEntry.DatetimeFinished.IsZero() {
  458. req.logEntry.DatetimeFinished = time.Now()
  459. }
  460. req.logEntry.ExecutionFinished = true
  461. // This isn't a step, because we want to notify all listeners, irrespective
  462. // of how many steps were actually executed.
  463. notifyListenersFinished(req)
  464. }
  465. func getConcurrentCount(req *ExecutionRequest) int {
  466. concurrentCount := 0
  467. req.executor.logmutex.RLock()
  468. for _, log := range req.executor.GetLogsByBindingId(req.Binding.ID) {
  469. if !log.ExecutionFinished {
  470. concurrentCount += 1
  471. }
  472. }
  473. req.executor.logmutex.RUnlock()
  474. return concurrentCount
  475. }
  476. func stepConcurrencyCheck(req *ExecutionRequest) bool {
  477. concurrentCount := getConcurrentCount(req)
  478. // Note that the current execution is counted int the logs, so when checking we +1
  479. if concurrentCount >= (req.Binding.Action.MaxConcurrent + 1) {
  480. log.WithFields(log.Fields{
  481. "actionTitle": req.logEntry.ActionTitle,
  482. "concurrentCount": concurrentCount,
  483. "maxConcurrent": req.Binding.Action.MaxConcurrent,
  484. }).Warnf("Blocked from executing due to concurrency limit")
  485. req.logEntry.Output = "Blocked from executing due to concurrency limit"
  486. req.logEntry.Blocked = true
  487. return false
  488. }
  489. return true
  490. }
  491. func parseDuration(rate config.RateSpec) time.Duration {
  492. duration, err := time.ParseDuration(rate.Duration)
  493. if err != nil {
  494. log.Warnf("Could not parse duration: %v", rate.Duration)
  495. return -1 * time.Minute
  496. }
  497. return duration
  498. }
  499. //gocyclo:ignore
  500. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  501. executions := -1 // Because we will find ourself when checking execution logs
  502. duration := parseDuration(rate)
  503. then := time.Now().Add(-duration)
  504. for _, logEntry := range req.executor.GetLogsByBindingId(req.Binding.ID) {
  505. // FIXME
  506. /*
  507. if logEntry.EntityPrefix != req.EntityPrefix {
  508. continue
  509. }
  510. */
  511. if logEntry.DatetimeStarted.After(then) && !logEntry.Blocked {
  512. executions += 1
  513. }
  514. }
  515. return executions
  516. }
  517. func stepRateCheck(req *ExecutionRequest) bool {
  518. for _, rate := range req.Binding.Action.MaxRate {
  519. executions := getExecutionsCount(rate, req)
  520. if executions >= rate.Limit {
  521. log.WithFields(log.Fields{
  522. "actionTitle": req.logEntry.ActionTitle,
  523. "executions": executions,
  524. "limit": rate.Limit,
  525. "duration": rate.Duration,
  526. }).Infof("Blocked from executing due to rate limit")
  527. req.logEntry.Output = "Blocked from executing due to rate limit"
  528. req.logEntry.Blocked = true
  529. return false
  530. }
  531. }
  532. return true
  533. }
  534. func stepACLCheck(req *ExecutionRequest) bool {
  535. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Binding.Action)
  536. if !canExec {
  537. req.logEntry.Output = "ACL check failed. Blocked from executing."
  538. req.logEntry.Blocked = true
  539. log.WithFields(log.Fields{
  540. "actionTitle": req.logEntry.ActionTitle,
  541. }).Warnf("ACL check failed. Blocked from executing.")
  542. }
  543. return canExec
  544. }
  545. func stepParseArgs(req *ExecutionRequest) bool {
  546. ensureArgumentMap(req)
  547. injectSystemArgs(req)
  548. if !hasBindingAndAction(req) {
  549. return fail(req, fmt.Errorf("cannot parse arguments: Binding or Action is nil"))
  550. }
  551. mangleInvalidArgumentValues(req)
  552. if hasExec(req) {
  553. return handleExecBranch(req)
  554. } else {
  555. return handleShellBranch(req)
  556. }
  557. }
  558. func handleExecBranch(req *ExecutionRequest) bool {
  559. args, err := parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
  560. if err != nil {
  561. return fail(req, err)
  562. }
  563. req.useDirectExec = true
  564. req.execArgs = args
  565. return true
  566. }
  567. func handleShellBranch(req *ExecutionRequest) bool {
  568. if err := checkShellArgumentSafety(req.Binding.Action); err != nil {
  569. return fail(req, err)
  570. }
  571. cmd, err := parseActionArguments(req.Arguments, req.Binding.Action, req.Binding.Entity)
  572. if err != nil {
  573. return fail(req, err)
  574. }
  575. req.useDirectExec = false
  576. req.finalParsedCommand = cmd
  577. return true
  578. }
  579. func ensureArgumentMap(req *ExecutionRequest) {
  580. if req.Arguments == nil {
  581. req.Arguments = make(map[string]string)
  582. }
  583. }
  584. func injectSystemArgs(req *ExecutionRequest) {
  585. req.Arguments["ot_executionTrackingId"] = req.TrackingID
  586. req.Arguments["ot_username"] = req.AuthenticatedUser.Username
  587. }
  588. func hasBindingAndAction(req *ExecutionRequest) bool {
  589. return !(req.Binding == nil || req.Binding.Action == nil)
  590. }
  591. func hasExec(req *ExecutionRequest) bool {
  592. return len(req.Binding.Action.Exec) > 0
  593. }
  594. func fail(req *ExecutionRequest, err error) bool {
  595. req.logEntry.Output = err.Error()
  596. log.Warn(err.Error())
  597. return false
  598. }
  599. func stepRequestAction(req *ExecutionRequest) bool {
  600. metricActionsRequested.Inc()
  601. // If there is no binding or action, do not proceed. Leave default
  602. // log entry values (icon/title/id) and stop execution gracefully.
  603. if req.Binding == nil || req.Binding.Action == nil {
  604. log.Warnf("Action request has no binding/action; skipping execution")
  605. return false
  606. }
  607. req.logEntry.Binding = req.Binding
  608. req.logEntry.ActionConfigTitle = req.Binding.Action.Title
  609. req.logEntry.ActionTitle = entities.ParseTemplateWith(req.Binding.Action.Title, req.Binding.Entity)
  610. req.logEntry.ActionIcon = req.Binding.Action.Icon
  611. req.logEntry.Tags = req.Tags
  612. req.executor.logmutex.Lock()
  613. if _, containsKey := req.executor.LogsByBindingId[req.Binding.ID]; !containsKey {
  614. req.executor.LogsByBindingId[req.Binding.ID] = make([]*InternalLogEntry, 0)
  615. }
  616. req.executor.LogsByBindingId[req.Binding.ID] = append(req.executor.LogsByBindingId[req.Binding.ID], req.logEntry)
  617. req.executor.logmutex.Unlock()
  618. log.WithFields(log.Fields{
  619. "actionTitle": req.logEntry.ActionTitle,
  620. "tags": req.Tags,
  621. }).Infof("Action requested")
  622. notifyListenersStarted(req)
  623. return true
  624. }
  625. func stepLogStart(req *ExecutionRequest) bool {
  626. log.WithFields(log.Fields{
  627. "actionTitle": req.logEntry.ActionTitle,
  628. "timeout": req.Binding.Action.Timeout,
  629. }).Infof("Action started")
  630. return true
  631. }
  632. func stepLogFinish(req *ExecutionRequest) bool {
  633. req.logEntry.ExecutionFinished = true
  634. log.WithFields(log.Fields{
  635. "actionTitle": req.logEntry.ActionTitle,
  636. "outputLength": len(req.logEntry.Output),
  637. "timedOut": req.logEntry.TimedOut,
  638. "exit": req.logEntry.ExitCode,
  639. }).Infof("Action finished")
  640. return true
  641. }
  642. func notifyListenersFinished(req *ExecutionRequest) {
  643. for _, listener := range req.executor.listeners {
  644. listener.OnExecutionFinished(req.logEntry)
  645. }
  646. }
  647. func notifyListenersStarted(req *ExecutionRequest) {
  648. for _, listener := range req.executor.listeners {
  649. listener.OnExecutionStarted(req.logEntry)
  650. }
  651. }
  652. func appendErrorToStderr(err error, logEntry *InternalLogEntry) {
  653. if err != nil {
  654. logEntry.Output = err.Error() + "\n\n" + logEntry.Output
  655. }
  656. }
  657. type OutputStreamer struct {
  658. Req *ExecutionRequest
  659. output bytes.Buffer
  660. }
  661. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  662. for _, listener := range ost.Req.executor.listeners {
  663. listener.OnOutputChunk(o, ost.Req.TrackingID)
  664. }
  665. return ost.output.Write(o)
  666. }
  667. func (ost *OutputStreamer) String() string {
  668. return ost.output.String()
  669. }
  670. func buildEnv(args map[string]string) []string {
  671. ret := append(os.Environ(), "OLIVETIN=1")
  672. for k, v := range args {
  673. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  674. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  675. if varName == "" {
  676. continue
  677. }
  678. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  679. }
  680. return ret
  681. }
  682. func stepExec(req *ExecutionRequest) bool {
  683. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  684. defer cancel()
  685. streamer := &OutputStreamer{Req: req}
  686. cmd := buildCommand(ctx, req)
  687. if cmd == nil {
  688. req.logEntry.Output = "Cannot execute: no command arguments provided"
  689. log.Warn("Cannot execute: no command arguments provided")
  690. return false
  691. }
  692. prepareCommand(cmd, streamer, req)
  693. runerr := cmd.Start()
  694. req.logEntry.Process = cmd.Process
  695. waiterr := cmd.Wait()
  696. req.logEntry.ExitCode = int32(cmd.ProcessState.ExitCode())
  697. req.logEntry.Output = streamer.String()
  698. appendErrorToStderr(runerr, req.logEntry)
  699. appendErrorToStderr(waiterr, req.logEntry)
  700. if ctx.Err() == context.DeadlineExceeded {
  701. log.WithFields(log.Fields{
  702. "actionTitle": req.logEntry.ActionTitle,
  703. }).Warnf("Action timed out")
  704. // The context timeout should kill the process, but let's make sure.
  705. err := req.executor.Kill(req.logEntry)
  706. if err != nil {
  707. log.WithFields(log.Fields{
  708. "actionTitle": req.logEntry.ActionTitle,
  709. }).Warnf("could not kill process: %v", err)
  710. }
  711. req.logEntry.TimedOut = true
  712. req.logEntry.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."
  713. }
  714. req.logEntry.DatetimeFinished = time.Now()
  715. return true
  716. }
  717. func buildCommand(ctx context.Context, req *ExecutionRequest) *exec.Cmd {
  718. if req.useDirectExec {
  719. return wrapCommandDirect(ctx, req.execArgs)
  720. }
  721. return wrapCommandInShell(ctx, req.finalParsedCommand)
  722. }
  723. func prepareCommand(cmd *exec.Cmd, streamer *OutputStreamer, req *ExecutionRequest) {
  724. cmd.Stdout = streamer
  725. cmd.Stderr = streamer
  726. cmd.Env = buildEnv(req.Arguments)
  727. req.logEntry.ExecutionStarted = true
  728. }
  729. func stepExecAfter(req *ExecutionRequest) bool {
  730. if req.Binding.Action.ShellAfterCompleted == "" {
  731. return true
  732. }
  733. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  734. defer cancel()
  735. var stdout bytes.Buffer
  736. var stderr bytes.Buffer
  737. args := map[string]string{
  738. "output": req.logEntry.Output,
  739. "exitCode": fmt.Sprintf("%v", req.logEntry.ExitCode),
  740. "ot_executionTrackingId": req.TrackingID,
  741. "ot_username": req.AuthenticatedUser.Username,
  742. }
  743. finalParsedCommand, err := parseCommandForReplacements(req.Binding.Action.ShellAfterCompleted, args, req.Binding.Entity)
  744. if err != nil {
  745. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  746. req.logEntry.Output += msg
  747. log.Warn(msg)
  748. return true
  749. }
  750. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  751. cmd.Stdout = &stdout
  752. cmd.Stderr = &stderr
  753. cmd.Env = buildEnv(args)
  754. runerr := cmd.Start()
  755. waiterr := cmd.Wait()
  756. req.logEntry.Output += "\n"
  757. req.logEntry.Output += "OliveTin::shellAfterCompleted stdout\n"
  758. req.logEntry.Output += stdout.String()
  759. req.logEntry.Output += "OliveTin::shellAfterCompleted stderr\n"
  760. req.logEntry.Output += stderr.String()
  761. req.logEntry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  762. appendErrorToStderr(runerr, req.logEntry)
  763. appendErrorToStderr(waiterr, req.logEntry)
  764. if ctx.Err() == context.DeadlineExceeded {
  765. req.logEntry.Output += "Your shellAfterCompleted command timed out."
  766. }
  767. req.logEntry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", cmd.ProcessState.ExitCode())
  768. req.logEntry.Output += "OliveTin::shellAfterCompleted output complete\n"
  769. return true
  770. }
  771. //gocyclo:ignore
  772. func stepTrigger(req *ExecutionRequest) bool {
  773. if req.Binding.Action.Triggers == nil {
  774. return true
  775. }
  776. if req.TriggerDepth >= MaxTriggerDepth {
  777. log.WithFields(log.Fields{
  778. "actionTitle": req.logEntry.ActionTitle,
  779. "depth": req.TriggerDepth,
  780. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  781. req.logEntry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  782. return true
  783. }
  784. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  785. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  786. }
  787. triggerLoop(req)
  788. return true
  789. }
  790. func triggerLoop(req *ExecutionRequest) {
  791. for _, triggerReq := range req.Binding.Action.Triggers {
  792. binding := req.executor.FindBindingByID(triggerReq)
  793. trigger := &ExecutionRequest{
  794. Binding: binding,
  795. TrackingID: uuid.NewString(),
  796. Tags: []string{"trigger"},
  797. AuthenticatedUser: req.AuthenticatedUser,
  798. Arguments: req.Arguments,
  799. Cfg: req.Cfg,
  800. TriggerDepth: req.TriggerDepth + 1,
  801. }
  802. req.executor.ExecRequest(trigger)
  803. }
  804. }
  805. func stepSaveLog(req *ExecutionRequest) bool {
  806. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  807. saveLogResults(req, filename)
  808. saveLogOutput(req, filename)
  809. return true
  810. }
  811. func firstNonEmpty(one, two string) string {
  812. if one != "" {
  813. return one
  814. }
  815. return two
  816. }
  817. func saveLogResults(req *ExecutionRequest, filename string) {
  818. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  819. if dir != "" {
  820. data, err := yaml.Marshal(req.logEntry)
  821. if err != nil {
  822. log.Warnf("%v", err)
  823. }
  824. filepath := path.Join(dir, filename+".yaml")
  825. err = os.WriteFile(filepath, data, 0644)
  826. if err != nil {
  827. log.Warnf("%v", err)
  828. }
  829. }
  830. }
  831. func saveLogOutput(req *ExecutionRequest, filename string) {
  832. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  833. if dir != "" {
  834. data := req.logEntry.Output
  835. filepath := path.Join(dir, filename+".log")
  836. err := os.WriteFile(filepath, []byte(data), 0644)
  837. if err != nil {
  838. log.Warnf("%v", err)
  839. }
  840. }
  841. }