4
0

executor.go 31 KB

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