executor.go 31 KB

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