executor.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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. func (e *Executor) filterLogsByACL(cfg *config.Config, user *authpublic.AuthenticatedUser, dateFilter string) []*InternalLogEntry {
  196. e.logmutex.RLock()
  197. defer e.logmutex.RUnlock()
  198. filtered := make([]*InternalLogEntry, 0, len(e.logsTrackingIdsByDate))
  199. filterDate, hasDateFilter := parseDateFilter(dateFilter)
  200. for _, trackingId := range e.logsTrackingIdsByDate {
  201. entry := e.logs[trackingId]
  202. if shouldIncludeLogEntry(cfg, user, entry, filterDate, hasDateFilter) {
  203. filtered = append(filtered, entry)
  204. }
  205. }
  206. return filtered
  207. }
  208. // parseDateFilter parses the date filter string and returns filter information.
  209. func parseDateFilter(dateFilter string) (filterDate time.Time, hasDateFilter bool) {
  210. if dateFilter == "" {
  211. return time.Time{}, false
  212. }
  213. parsedDate, err := time.Parse("2006-01-02", dateFilter)
  214. if err != nil {
  215. log.WithFields(log.Fields{
  216. "dateFilter": dateFilter,
  217. "error": err,
  218. }).Errorf("Failed to parse date filter, expected format YYYY-MM-DD")
  219. return time.Time{}, false
  220. }
  221. return parsedDate, true
  222. }
  223. // shouldIncludeLogEntry determines if a log entry should be included based on ACL and date filter.
  224. func shouldIncludeLogEntry(cfg *config.Config, user *authpublic.AuthenticatedUser, entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  225. if !isValidLogEntryForACL(entry) {
  226. return false
  227. }
  228. if !isLogEntryAllowedByACL(cfg, user, entry) {
  229. return false
  230. }
  231. return matchesDateFilter(entry, filterDate, hasDateFilter)
  232. }
  233. // matchesDateFilter checks if the log entry matches the date filter.
  234. func matchesDateFilter(entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  235. if !hasDateFilter {
  236. return true
  237. }
  238. entryDate := entry.DatetimeStarted.UTC().Truncate(24 * time.Hour)
  239. filterDateUTC := filterDate.UTC().Truncate(24 * time.Hour)
  240. return entryDate.Equal(filterDateUTC)
  241. }
  242. // paginateFilteredLogs applies pagination to a filtered list of logs and returns
  243. // the paginated results along with pagination metadata.
  244. func paginateFilteredLogs(filtered []*InternalLogEntry, startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  245. total := int64(len(filtered))
  246. paging := &PagingResult{PageSize: pageCount, TotalCount: total, StartOffset: startOffset}
  247. if total == 0 {
  248. paging.CountRemaining = 0
  249. return []*InternalLogEntry{}, paging
  250. }
  251. startIndex := getPagingStartIndex(startOffset, total)
  252. pageCount = min(total, pageCount)
  253. endIndex := max(0, (startIndex-pageCount)+1)
  254. out := make([]*InternalLogEntry, 0, pageCount)
  255. for i := endIndex; i <= startIndex && i < int64(len(filtered)); i++ {
  256. out = append(out, filtered[i])
  257. }
  258. paging.CountRemaining = endIndex
  259. return out, paging
  260. }
  261. // GetLogTrackingIdsACL returns logs filtered by ACL visibility for the user and
  262. // paginated correctly based on the filtered set.
  263. // dateFilter is optional and should be in YYYY-MM-DD format. If empty, no date filtering is applied.
  264. func (e *Executor) GetLogTrackingIdsACL(cfg *config.Config, user *authpublic.AuthenticatedUser, startOffset int64, pageCount int64, dateFilter string) ([]*InternalLogEntry, *PagingResult) {
  265. filtered := e.filterLogsByACL(cfg, user, dateFilter)
  266. return paginateFilteredLogs(filtered, startOffset, pageCount)
  267. }
  268. func (e *Executor) GetLog(trackingID string) (*InternalLogEntry, bool) {
  269. e.logmutex.RLock()
  270. entry, found := e.logs[trackingID]
  271. e.logmutex.RUnlock()
  272. return entry, found
  273. }
  274. func (e *Executor) GetLogsByBindingId(bindingId string) []*InternalLogEntry {
  275. e.logmutex.RLock()
  276. logs, found := e.LogsByBindingId[bindingId]
  277. e.logmutex.RUnlock()
  278. if !found {
  279. return make([]*InternalLogEntry, 0)
  280. }
  281. return logs
  282. }
  283. // shouldCountExecution checks if a log entry should be counted for rate limiting.
  284. func shouldCountExecution(logEntry *InternalLogEntry, windowStart time.Time) bool {
  285. return !logEntry.Blocked && logEntry.DatetimeStarted.After(windowStart)
  286. }
  287. // updateOldestExecution updates the oldest execution time if this entry is older.
  288. func updateOldestExecution(oldestExecutionTime **time.Time, logEntry *InternalLogEntry) {
  289. if *oldestExecutionTime == nil {
  290. *oldestExecutionTime = &logEntry.DatetimeStarted
  291. } else if logEntry.DatetimeStarted.Before(**oldestExecutionTime) {
  292. *oldestExecutionTime = &logEntry.DatetimeStarted
  293. }
  294. }
  295. // findOldestExecutionInWindow finds the oldest execution within the time window and counts executions.
  296. // Returns the count of executions and the oldest execution time, or nil if none found.
  297. func findOldestExecutionInWindow(logs []*InternalLogEntry, windowStart time.Time) (int, *time.Time) {
  298. executions := 0
  299. var oldestExecutionTime *time.Time
  300. for _, logEntry := range logs {
  301. if !shouldCountExecution(logEntry, windowStart) {
  302. continue
  303. }
  304. executions++
  305. updateOldestExecution(&oldestExecutionTime, logEntry)
  306. }
  307. return executions, oldestExecutionTime
  308. }
  309. // calculateExpiryTime calculates when the oldest execution will fall outside the rate limit window.
  310. func calculateExpiryTime(oldestExecutionTime time.Time, duration time.Duration, now time.Time) time.Time {
  311. expiryTime := oldestExecutionTime.Add(duration)
  312. if !expiryTime.After(now) {
  313. return time.Time{}
  314. }
  315. return expiryTime
  316. }
  317. // updateMaxExpiryTime updates maxExpiryTime if expiryTime is later.
  318. func updateMaxExpiryTime(maxExpiryTime *time.Time, expiryTime time.Time) {
  319. if expiryTime.IsZero() {
  320. return
  321. }
  322. if maxExpiryTime.IsZero() || expiryTime.After(*maxExpiryTime) {
  323. *maxExpiryTime = expiryTime
  324. }
  325. }
  326. // calculateExpiryForRate calculates the expiry time for a single rate limit rule.
  327. // Returns the expiry time if the rate limit is exceeded, or zero time if not.
  328. func calculateExpiryForRate(rate config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  329. duration := parseDuration(rate)
  330. if duration <= 0 {
  331. return time.Time{}
  332. }
  333. windowStart := now.Add(-duration)
  334. executions, oldestExecutionTime := findOldestExecutionInWindow(logs, windowStart)
  335. if executions < rate.Limit || oldestExecutionTime == nil {
  336. return time.Time{}
  337. }
  338. return calculateExpiryTime(*oldestExecutionTime, duration, now)
  339. }
  340. // getLogsForBinding retrieves logs for a binding ID.
  341. func (e *Executor) getLogsForBinding(bindingId string) []*InternalLogEntry {
  342. e.logmutex.RLock()
  343. logs, found := e.LogsByBindingId[bindingId]
  344. e.logmutex.RUnlock()
  345. if !found || len(logs) == 0 {
  346. return nil
  347. }
  348. return logs
  349. }
  350. // calculateMaxExpiryTimeFromRates calculates the maximum expiry time across all rate limit rules.
  351. func calculateMaxExpiryTimeFromRates(rates []config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  352. var maxExpiryTime time.Time
  353. for _, rate := range rates {
  354. expiryTime := calculateExpiryForRate(rate, logs, now)
  355. updateMaxExpiryTime(&maxExpiryTime, expiryTime)
  356. }
  357. return maxExpiryTime
  358. }
  359. // GetTimeUntilAvailable calculates when an action will be available again based on rate limits.
  360. // Returns the Unix timestamp in seconds when the rate limit expires, or 0 if the action is available now.
  361. func (e *Executor) GetTimeUntilAvailable(binding *ActionBinding) int64 {
  362. if len(binding.Action.MaxRate) == 0 {
  363. return 0
  364. }
  365. logs := e.getLogsForBinding(binding.ID)
  366. if logs == nil {
  367. return 0
  368. }
  369. maxExpiryTime := calculateMaxExpiryTimeFromRates(binding.Action.MaxRate, logs, time.Now())
  370. if maxExpiryTime.IsZero() {
  371. return 0
  372. }
  373. return maxExpiryTime.Unix()
  374. }
  375. func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) {
  376. e.logmutex.Lock()
  377. entry.Index = int64(len(e.logsTrackingIdsByDate))
  378. e.logs[trackingID] = entry
  379. e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
  380. e.logmutex.Unlock()
  381. }
  382. // ExecRequest processes an ExecutionRequest
  383. func (e *Executor) ExecRequest(req *ExecutionRequest) (*sync.WaitGroup, string) {
  384. if req.AuthenticatedUser == nil {
  385. req.AuthenticatedUser = auth.UserGuest(req.Cfg)
  386. }
  387. req.executor = e
  388. req.logEntry = &InternalLogEntry{
  389. Binding: req.Binding,
  390. DatetimeStarted: time.Now(),
  391. ExecutionTrackingID: req.TrackingID,
  392. Output: "",
  393. ExitCode: DefaultExitCodeNotExecuted,
  394. ExecutionStarted: false,
  395. ExecutionFinished: false,
  396. ActionTitle: "notfound",
  397. ActionIcon: "&#x1f4a9;",
  398. Username: req.AuthenticatedUser.Username,
  399. }
  400. _, isDuplicate := e.GetLog(req.TrackingID)
  401. if isDuplicate || req.TrackingID == "" {
  402. req.TrackingID = uuid.NewString()
  403. }
  404. // Update the log entry with the final tracking ID
  405. req.logEntry.ExecutionTrackingID = req.TrackingID
  406. log.Tracef("executor.ExecRequest(): %v", req)
  407. e.SetLog(req.TrackingID, req.logEntry)
  408. wg := new(sync.WaitGroup)
  409. wg.Add(1)
  410. go func() {
  411. e.execChain(req)
  412. defer wg.Done()
  413. }()
  414. return wg, req.TrackingID
  415. }
  416. func (e *Executor) execChain(req *ExecutionRequest) {
  417. for _, step := range e.chainOfCommand {
  418. if !step(req) {
  419. break
  420. }
  421. }
  422. // Ensure DatetimeFinished is set even if execution was blocked early
  423. if req.logEntry.DatetimeFinished.IsZero() {
  424. req.logEntry.DatetimeFinished = time.Now()
  425. }
  426. req.logEntry.ExecutionFinished = true
  427. // This isn't a step, because we want to notify all listeners, irrespective
  428. // of how many steps were actually executed.
  429. notifyListenersFinished(req)
  430. }
  431. func getConcurrentCount(req *ExecutionRequest) int {
  432. concurrentCount := 0
  433. req.executor.logmutex.RLock()
  434. for _, log := range req.executor.GetLogsByBindingId(req.Binding.ID) {
  435. if !log.ExecutionFinished {
  436. concurrentCount += 1
  437. }
  438. }
  439. req.executor.logmutex.RUnlock()
  440. return concurrentCount
  441. }
  442. func stepConcurrencyCheck(req *ExecutionRequest) bool {
  443. concurrentCount := getConcurrentCount(req)
  444. // Note that the current execution is counted int the logs, so when checking we +1
  445. if concurrentCount >= (req.Binding.Action.MaxConcurrent + 1) {
  446. log.WithFields(log.Fields{
  447. "actionTitle": req.logEntry.ActionTitle,
  448. "concurrentCount": concurrentCount,
  449. "maxConcurrent": req.Binding.Action.MaxConcurrent,
  450. }).Warnf("Blocked from executing due to concurrency limit")
  451. req.logEntry.Output = "Blocked from executing due to concurrency limit"
  452. req.logEntry.Blocked = true
  453. return false
  454. }
  455. return true
  456. }
  457. func parseDuration(rate config.RateSpec) time.Duration {
  458. duration, err := time.ParseDuration(rate.Duration)
  459. if err != nil {
  460. log.Warnf("Could not parse duration: %v", rate.Duration)
  461. return -1 * time.Minute
  462. }
  463. return duration
  464. }
  465. //gocyclo:ignore
  466. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  467. executions := -1 // Because we will find ourself when checking execution logs
  468. duration := parseDuration(rate)
  469. then := time.Now().Add(-duration)
  470. for _, logEntry := range req.executor.GetLogsByBindingId(req.Binding.ID) {
  471. // FIXME
  472. /*
  473. if logEntry.EntityPrefix != req.EntityPrefix {
  474. continue
  475. }
  476. */
  477. if logEntry.DatetimeStarted.After(then) && !logEntry.Blocked {
  478. executions += 1
  479. }
  480. }
  481. return executions
  482. }
  483. func stepRateCheck(req *ExecutionRequest) bool {
  484. for _, rate := range req.Binding.Action.MaxRate {
  485. executions := getExecutionsCount(rate, req)
  486. if executions >= rate.Limit {
  487. log.WithFields(log.Fields{
  488. "actionTitle": req.logEntry.ActionTitle,
  489. "executions": executions,
  490. "limit": rate.Limit,
  491. "duration": rate.Duration,
  492. }).Infof("Blocked from executing due to rate limit")
  493. req.logEntry.Output = "Blocked from executing due to rate limit"
  494. req.logEntry.Blocked = true
  495. return false
  496. }
  497. }
  498. return true
  499. }
  500. func stepACLCheck(req *ExecutionRequest) bool {
  501. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Binding.Action)
  502. if !canExec {
  503. req.logEntry.Output = "ACL check failed. Blocked from executing."
  504. req.logEntry.Blocked = true
  505. log.WithFields(log.Fields{
  506. "actionTitle": req.logEntry.ActionTitle,
  507. }).Warnf("ACL check failed. Blocked from executing.")
  508. }
  509. return canExec
  510. }
  511. func stepParseArgs(req *ExecutionRequest) bool {
  512. ensureArgumentMap(req)
  513. injectSystemArgs(req)
  514. if !hasBindingAndAction(req) {
  515. return fail(req, fmt.Errorf("cannot parse arguments: Binding or Action is nil"))
  516. }
  517. mangleInvalidArgumentValues(req)
  518. if hasExec(req) {
  519. return handleExecBranch(req)
  520. } else {
  521. return handleShellBranch(req)
  522. }
  523. }
  524. func handleExecBranch(req *ExecutionRequest) bool {
  525. args, err := parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
  526. if err != nil {
  527. return fail(req, err)
  528. }
  529. req.useDirectExec = true
  530. req.execArgs = args
  531. return true
  532. }
  533. func handleShellBranch(req *ExecutionRequest) bool {
  534. if err := checkShellArgumentSafety(req.Binding.Action); err != nil {
  535. return fail(req, err)
  536. }
  537. cmd, err := parseActionArguments(req.Arguments, req.Binding.Action, req.Binding.Entity)
  538. if err != nil {
  539. return fail(req, err)
  540. }
  541. req.useDirectExec = false
  542. req.finalParsedCommand = cmd
  543. return true
  544. }
  545. func ensureArgumentMap(req *ExecutionRequest) {
  546. if req.Arguments == nil {
  547. req.Arguments = make(map[string]string)
  548. }
  549. }
  550. func injectSystemArgs(req *ExecutionRequest) {
  551. req.Arguments["ot_executionTrackingId"] = req.TrackingID
  552. req.Arguments["ot_username"] = req.AuthenticatedUser.Username
  553. }
  554. func hasBindingAndAction(req *ExecutionRequest) bool {
  555. return !(req.Binding == nil || req.Binding.Action == nil)
  556. }
  557. func hasExec(req *ExecutionRequest) bool {
  558. return len(req.Binding.Action.Exec) > 0
  559. }
  560. func fail(req *ExecutionRequest, err error) bool {
  561. req.logEntry.Output = err.Error()
  562. log.Warn(err.Error())
  563. return false
  564. }
  565. func stepRequestAction(req *ExecutionRequest) bool {
  566. metricActionsRequested.Inc()
  567. // If there is no binding or action, do not proceed. Leave default
  568. // log entry values (icon/title/id) and stop execution gracefully.
  569. if req.Binding == nil || req.Binding.Action == nil {
  570. log.Warnf("Action request has no binding/action; skipping execution")
  571. return false
  572. }
  573. req.logEntry.Binding = req.Binding
  574. req.logEntry.ActionConfigTitle = req.Binding.Action.Title
  575. req.logEntry.ActionTitle = entities.ParseTemplateWith(req.Binding.Action.Title, req.Binding.Entity)
  576. req.logEntry.ActionIcon = req.Binding.Action.Icon
  577. req.logEntry.Tags = req.Tags
  578. req.executor.logmutex.Lock()
  579. if _, containsKey := req.executor.LogsByBindingId[req.Binding.ID]; !containsKey {
  580. req.executor.LogsByBindingId[req.Binding.ID] = make([]*InternalLogEntry, 0)
  581. }
  582. req.executor.LogsByBindingId[req.Binding.ID] = append(req.executor.LogsByBindingId[req.Binding.ID], req.logEntry)
  583. req.executor.logmutex.Unlock()
  584. log.WithFields(log.Fields{
  585. "actionTitle": req.logEntry.ActionTitle,
  586. "tags": req.Tags,
  587. }).Infof("Action requested")
  588. notifyListenersStarted(req)
  589. return true
  590. }
  591. func stepLogStart(req *ExecutionRequest) bool {
  592. log.WithFields(log.Fields{
  593. "actionTitle": req.logEntry.ActionTitle,
  594. "timeout": req.Binding.Action.Timeout,
  595. }).Infof("Action started")
  596. return true
  597. }
  598. func stepLogFinish(req *ExecutionRequest) bool {
  599. req.logEntry.ExecutionFinished = true
  600. log.WithFields(log.Fields{
  601. "actionTitle": req.logEntry.ActionTitle,
  602. "outputLength": len(req.logEntry.Output),
  603. "timedOut": req.logEntry.TimedOut,
  604. "exit": req.logEntry.ExitCode,
  605. }).Infof("Action finished")
  606. return true
  607. }
  608. func notifyListenersFinished(req *ExecutionRequest) {
  609. for _, listener := range req.executor.listeners {
  610. listener.OnExecutionFinished(req.logEntry)
  611. }
  612. }
  613. func notifyListenersStarted(req *ExecutionRequest) {
  614. for _, listener := range req.executor.listeners {
  615. listener.OnExecutionStarted(req.logEntry)
  616. }
  617. }
  618. func appendErrorToStderr(err error, logEntry *InternalLogEntry) {
  619. if err != nil {
  620. logEntry.Output = err.Error() + "\n\n" + logEntry.Output
  621. }
  622. }
  623. type OutputStreamer struct {
  624. Req *ExecutionRequest
  625. output bytes.Buffer
  626. }
  627. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  628. for _, listener := range ost.Req.executor.listeners {
  629. listener.OnOutputChunk(o, ost.Req.TrackingID)
  630. }
  631. return ost.output.Write(o)
  632. }
  633. func (ost *OutputStreamer) String() string {
  634. return ost.output.String()
  635. }
  636. func buildEnv(args map[string]string) []string {
  637. ret := append(os.Environ(), "OLIVETIN=1")
  638. for k, v := range args {
  639. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  640. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  641. if varName == "" {
  642. continue
  643. }
  644. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  645. }
  646. return ret
  647. }
  648. func stepExec(req *ExecutionRequest) bool {
  649. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  650. defer cancel()
  651. streamer := &OutputStreamer{Req: req}
  652. cmd := buildCommand(ctx, req)
  653. if cmd == nil {
  654. req.logEntry.Output = "Cannot execute: no command arguments provided"
  655. log.Warn("Cannot execute: no command arguments provided")
  656. return false
  657. }
  658. prepareCommand(cmd, streamer, req)
  659. runerr := cmd.Start()
  660. req.logEntry.Process = cmd.Process
  661. waiterr := cmd.Wait()
  662. req.logEntry.ExitCode = int32(cmd.ProcessState.ExitCode())
  663. req.logEntry.Output = streamer.String()
  664. appendErrorToStderr(runerr, req.logEntry)
  665. appendErrorToStderr(waiterr, req.logEntry)
  666. if ctx.Err() == context.DeadlineExceeded {
  667. log.WithFields(log.Fields{
  668. "actionTitle": req.logEntry.ActionTitle,
  669. }).Warnf("Action timed out")
  670. // The context timeout should kill the process, but let's make sure.
  671. err := req.executor.Kill(req.logEntry)
  672. if err != nil {
  673. log.WithFields(log.Fields{
  674. "actionTitle": req.logEntry.ActionTitle,
  675. }).Warnf("could not kill process: %v", err)
  676. }
  677. req.logEntry.TimedOut = true
  678. 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."
  679. }
  680. req.logEntry.DatetimeFinished = time.Now()
  681. return true
  682. }
  683. func buildCommand(ctx context.Context, req *ExecutionRequest) *exec.Cmd {
  684. if req.useDirectExec {
  685. return wrapCommandDirect(ctx, req.execArgs)
  686. }
  687. return wrapCommandInShell(ctx, req.finalParsedCommand)
  688. }
  689. func prepareCommand(cmd *exec.Cmd, streamer *OutputStreamer, req *ExecutionRequest) {
  690. cmd.Stdout = streamer
  691. cmd.Stderr = streamer
  692. cmd.Env = buildEnv(req.Arguments)
  693. req.logEntry.ExecutionStarted = true
  694. }
  695. func stepExecAfter(req *ExecutionRequest) bool {
  696. if req.Binding.Action.ShellAfterCompleted == "" {
  697. return true
  698. }
  699. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  700. defer cancel()
  701. var stdout bytes.Buffer
  702. var stderr bytes.Buffer
  703. args := map[string]string{
  704. "output": req.logEntry.Output,
  705. "exitCode": fmt.Sprintf("%v", req.logEntry.ExitCode),
  706. "ot_executionTrackingId": req.TrackingID,
  707. "ot_username": req.AuthenticatedUser.Username,
  708. }
  709. finalParsedCommand, err := parseCommandForReplacements(req.Binding.Action.ShellAfterCompleted, args, req.Binding.Entity)
  710. if err != nil {
  711. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  712. req.logEntry.Output += msg
  713. log.Warn(msg)
  714. return true
  715. }
  716. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  717. cmd.Stdout = &stdout
  718. cmd.Stderr = &stderr
  719. cmd.Env = buildEnv(args)
  720. runerr := cmd.Start()
  721. waiterr := cmd.Wait()
  722. req.logEntry.Output += "\n"
  723. req.logEntry.Output += "OliveTin::shellAfterCompleted stdout\n"
  724. req.logEntry.Output += stdout.String()
  725. req.logEntry.Output += "OliveTin::shellAfterCompleted stderr\n"
  726. req.logEntry.Output += stderr.String()
  727. req.logEntry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  728. appendErrorToStderr(runerr, req.logEntry)
  729. appendErrorToStderr(waiterr, req.logEntry)
  730. if ctx.Err() == context.DeadlineExceeded {
  731. req.logEntry.Output += "Your shellAfterCompleted command timed out."
  732. }
  733. req.logEntry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", cmd.ProcessState.ExitCode())
  734. req.logEntry.Output += "OliveTin::shellAfterCompleted output complete\n"
  735. return true
  736. }
  737. //gocyclo:ignore
  738. func stepTrigger(req *ExecutionRequest) bool {
  739. if req.Binding.Action.Triggers == nil {
  740. return true
  741. }
  742. if req.TriggerDepth >= MaxTriggerDepth {
  743. log.WithFields(log.Fields{
  744. "actionTitle": req.logEntry.ActionTitle,
  745. "depth": req.TriggerDepth,
  746. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  747. req.logEntry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  748. return true
  749. }
  750. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  751. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  752. }
  753. triggerLoop(req)
  754. return true
  755. }
  756. func triggerLoop(req *ExecutionRequest) {
  757. for _, triggerReq := range req.Binding.Action.Triggers {
  758. binding := req.executor.FindBindingByID(triggerReq)
  759. trigger := &ExecutionRequest{
  760. Binding: binding,
  761. TrackingID: uuid.NewString(),
  762. Tags: []string{"trigger"},
  763. AuthenticatedUser: req.AuthenticatedUser,
  764. Arguments: req.Arguments,
  765. Cfg: req.Cfg,
  766. TriggerDepth: req.TriggerDepth + 1,
  767. }
  768. req.executor.ExecRequest(trigger)
  769. }
  770. }
  771. func stepSaveLog(req *ExecutionRequest) bool {
  772. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  773. saveLogResults(req, filename)
  774. saveLogOutput(req, filename)
  775. return true
  776. }
  777. func firstNonEmpty(one, two string) string {
  778. if one != "" {
  779. return one
  780. }
  781. return two
  782. }
  783. func saveLogResults(req *ExecutionRequest, filename string) {
  784. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  785. if dir != "" {
  786. data, err := yaml.Marshal(req.logEntry)
  787. if err != nil {
  788. log.Warnf("%v", err)
  789. }
  790. filepath := path.Join(dir, filename+".yaml")
  791. err = os.WriteFile(filepath, data, 0644)
  792. if err != nil {
  793. log.Warnf("%v", err)
  794. }
  795. }
  796. }
  797. func saveLogOutput(req *ExecutionRequest, filename string) {
  798. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  799. if dir != "" {
  800. data := req.logEntry.Output
  801. filepath := path.Join(dir, filename+".log")
  802. err := os.WriteFile(filepath, []byte(data), 0644)
  803. if err != nil {
  804. log.Warnf("%v", err)
  805. }
  806. }
  807. }