executor.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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. injectSystemArgs(req)
  527. if !hasBindingAndAction(req) {
  528. return fail(req, fmt.Errorf("cannot parse arguments: Binding or Action is nil"))
  529. }
  530. filterToDefinedArgumentsOnly(req)
  531. mangleInvalidArgumentValues(req)
  532. if hasExec(req) {
  533. return handleExecBranch(req)
  534. } else {
  535. return handleShellBranch(req)
  536. }
  537. }
  538. func handleExecBranch(req *ExecutionRequest) bool {
  539. args, err := parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
  540. if err != nil {
  541. return fail(req, err)
  542. }
  543. req.useDirectExec = true
  544. req.execArgs = args
  545. return true
  546. }
  547. func handleShellBranch(req *ExecutionRequest) bool {
  548. if hasWebhookTag(req) {
  549. return fail(req, fmt.Errorf("webhooks cannot use Shell execution; use exec instead. See https://docs.olivetin.app/action_execution/shellvsexec.html"))
  550. }
  551. if err := checkShellArgumentSafety(req.Binding.Action); err != nil {
  552. return fail(req, err)
  553. }
  554. cmd, err := parseActionArguments(req)
  555. if err != nil {
  556. return fail(req, err)
  557. }
  558. req.useDirectExec = false
  559. req.finalParsedCommand = cmd
  560. return true
  561. }
  562. func ensureArgumentMap(req *ExecutionRequest) {
  563. if req.Arguments == nil {
  564. req.Arguments = make(map[string]string)
  565. }
  566. }
  567. func filterToDefinedArgumentsOnly(req *ExecutionRequest) {
  568. definedNames := make(map[string]struct{})
  569. for _, arg := range req.Binding.Action.Arguments {
  570. definedNames[arg.Name] = struct{}{}
  571. }
  572. filtered := make(map[string]string)
  573. for k, v := range req.Arguments {
  574. if keepArgument(k, definedNames) {
  575. filtered[k] = v
  576. }
  577. }
  578. req.Arguments = filtered
  579. }
  580. func keepArgument(name string, definedNames map[string]struct{}) bool {
  581. _, ok := definedNames[name]
  582. return ok || strings.HasPrefix(name, "ot_")
  583. }
  584. func hasWebhookTag(req *ExecutionRequest) bool {
  585. for _, tag := range req.Tags {
  586. if tag == "webhook" {
  587. return true
  588. }
  589. }
  590. return false
  591. }
  592. func injectSystemArgs(req *ExecutionRequest) {
  593. req.Arguments["ot_executionTrackingId"] = req.TrackingID
  594. req.Arguments["ot_username"] = req.AuthenticatedUser.Username
  595. }
  596. func hasBindingAndAction(req *ExecutionRequest) bool {
  597. return !(req.Binding == nil || req.Binding.Action == nil)
  598. }
  599. func hasExec(req *ExecutionRequest) bool {
  600. return len(req.Binding.Action.Exec) > 0
  601. }
  602. func fail(req *ExecutionRequest, err error) bool {
  603. req.logEntry.Output = err.Error()
  604. log.Warn(err.Error())
  605. return false
  606. }
  607. func stepRequestAction(req *ExecutionRequest) bool {
  608. metricActionsRequested.Inc()
  609. if !stepRequestActionHasBinding(req) {
  610. return false
  611. }
  612. stepRequestActionPopulateLogEntry(req)
  613. stepRequestActionRegisterLog(req)
  614. log.WithFields(log.Fields{
  615. "actionTitle": req.logEntry.ActionTitle,
  616. "tags": req.Tags,
  617. }).Infof("Action requested")
  618. notifyListenersStarted(req)
  619. return true
  620. }
  621. func stepRequestActionHasBinding(req *ExecutionRequest) bool {
  622. if req.Binding == nil || req.Binding.Action == nil {
  623. log.Warnf("Action request has no binding/action; skipping execution")
  624. return false
  625. }
  626. return true
  627. }
  628. func stepRequestActionPopulateLogEntry(req *ExecutionRequest) {
  629. req.logEntry.Binding = req.Binding
  630. req.logEntry.ActionConfigTitle = req.Binding.Action.Title
  631. req.logEntry.ActionTitle = tpl.ParseTemplateOfActionBeforeExec(req.Binding.Action.Title, req.Binding.Entity)
  632. req.logEntry.ActionIcon = req.Binding.Action.Icon
  633. req.logEntry.Tags = req.Tags
  634. if req.Binding.Entity != nil {
  635. req.logEntry.EntityPrefix = req.Binding.Entity.UniqueKey
  636. }
  637. }
  638. func stepRequestActionRegisterLog(req *ExecutionRequest) {
  639. req.executor.logmutex.Lock()
  640. defer req.executor.logmutex.Unlock()
  641. if _, containsKey := req.executor.LogsByBindingId[req.Binding.ID]; !containsKey {
  642. req.executor.LogsByBindingId[req.Binding.ID] = make([]*InternalLogEntry, 0)
  643. }
  644. req.executor.LogsByBindingId[req.Binding.ID] = append(req.executor.LogsByBindingId[req.Binding.ID], req.logEntry)
  645. }
  646. func stepLogStart(req *ExecutionRequest) bool {
  647. log.WithFields(log.Fields{
  648. "actionTitle": req.logEntry.ActionTitle,
  649. "timeout": req.Binding.Action.Timeout,
  650. }).Infof("Action started")
  651. return true
  652. }
  653. func stepLogFinish(req *ExecutionRequest) bool {
  654. req.logEntry.ExecutionFinished = true
  655. log.WithFields(log.Fields{
  656. "actionTitle": req.logEntry.ActionTitle,
  657. "outputLength": len(req.logEntry.Output),
  658. "timedOut": req.logEntry.TimedOut,
  659. "exit": req.logEntry.ExitCode,
  660. }).Infof("Action finished")
  661. return true
  662. }
  663. func notifyListenersFinished(req *ExecutionRequest) {
  664. for _, listener := range req.executor.listeners {
  665. listener.OnExecutionFinished(req.logEntry)
  666. }
  667. }
  668. func notifyListenersStarted(req *ExecutionRequest) {
  669. for _, listener := range req.executor.listeners {
  670. listener.OnExecutionStarted(req.logEntry)
  671. }
  672. }
  673. func appendErrorToStderr(err error, logEntry *InternalLogEntry) {
  674. if err != nil {
  675. logEntry.Output = err.Error() + "\n\n" + logEntry.Output
  676. }
  677. }
  678. type OutputStreamer struct {
  679. Req *ExecutionRequest
  680. output bytes.Buffer
  681. }
  682. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  683. for _, listener := range ost.Req.executor.listeners {
  684. listener.OnOutputChunk(o, ost.Req.TrackingID)
  685. }
  686. return ost.output.Write(o)
  687. }
  688. func (ost *OutputStreamer) String() string {
  689. return ost.output.String()
  690. }
  691. func buildEnv(args map[string]string) []string {
  692. ret := append(os.Environ(), "OLIVETIN=1")
  693. for k, v := range args {
  694. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  695. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  696. if varName == "" {
  697. continue
  698. }
  699. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  700. }
  701. return ret
  702. }
  703. func stepExec(req *ExecutionRequest) bool {
  704. ctx, cancel := newTimeoutContext(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second, req.executor)
  705. defer cancel()
  706. streamer := &OutputStreamer{Req: req}
  707. cmd := buildCommand(ctx, req)
  708. if cmd == nil {
  709. req.logEntry.Output = "Cannot execute: no command arguments provided"
  710. log.Warn("Cannot execute: no command arguments provided")
  711. return false
  712. }
  713. prepareCommand(cmd, streamer, req)
  714. runerr := cmd.Start()
  715. req.logEntry.Process = cmd.Process
  716. ctx.setProcess(cmd.Process)
  717. waiterr := cmd.Wait()
  718. req.logEntry.ExitCode = int32(cmd.ProcessState.ExitCode())
  719. req.logEntry.Output = streamer.String()
  720. appendErrorToStderr(runerr, req.logEntry)
  721. appendErrorToStderr(waiterr, req.logEntry)
  722. if ctx.Err() == context.DeadlineExceeded {
  723. log.WithFields(log.Fields{
  724. "actionTitle": req.logEntry.ActionTitle,
  725. }).Warnf("Action timed out")
  726. req.logEntry.TimedOut = true
  727. 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."
  728. }
  729. req.logEntry.DatetimeFinished = time.Now()
  730. return true
  731. }
  732. func buildCommand(ctx context.Context, req *ExecutionRequest) *exec.Cmd {
  733. if req.useDirectExec {
  734. return wrapCommandDirect(ctx, req.execArgs)
  735. }
  736. return wrapCommandInShell(ctx, req.finalParsedCommand)
  737. }
  738. func prepareCommand(cmd *exec.Cmd, streamer *OutputStreamer, req *ExecutionRequest) {
  739. cmd.Stdout = streamer
  740. cmd.Stderr = streamer
  741. cmd.Env = buildEnv(req.Arguments)
  742. req.logEntry.ExecutionStarted = true
  743. }
  744. func stepExecAfter(req *ExecutionRequest) bool {
  745. if req.Binding.Action.ShellAfterCompleted == "" {
  746. return true
  747. }
  748. ctx, cancel := newTimeoutContext(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second, req.executor)
  749. defer cancel()
  750. var stdout bytes.Buffer
  751. var stderr bytes.Buffer
  752. args := map[string]string{
  753. "output": req.logEntry.Output,
  754. "exitCode": fmt.Sprintf("%v", req.logEntry.ExitCode),
  755. "ot_executionTrackingId": req.TrackingID,
  756. "ot_username": req.AuthenticatedUser.Username,
  757. }
  758. finalParsedCommand, err := tpl.ParseTemplateWithActionContext(req.Binding.Action.ShellAfterCompleted, req.Binding.Entity, args)
  759. if err != nil {
  760. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  761. req.logEntry.Output += msg
  762. log.Warn(msg)
  763. return true
  764. }
  765. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  766. cmd.Stdout = &stdout
  767. cmd.Stderr = &stderr
  768. cmd.Env = buildEnv(args)
  769. runerr := cmd.Start()
  770. ctx.setProcess(cmd.Process)
  771. waiterr := cmd.Wait()
  772. req.logEntry.Output += "\n"
  773. req.logEntry.Output += "OliveTin::shellAfterCompleted stdout\n"
  774. req.logEntry.Output += stdout.String()
  775. req.logEntry.Output += "OliveTin::shellAfterCompleted stderr\n"
  776. req.logEntry.Output += stderr.String()
  777. req.logEntry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  778. appendErrorToStderr(runerr, req.logEntry)
  779. appendErrorToStderr(waiterr, req.logEntry)
  780. if ctx.Err() == context.DeadlineExceeded {
  781. req.logEntry.Output += "Your shellAfterCompleted command timed out."
  782. }
  783. req.logEntry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", cmd.ProcessState.ExitCode())
  784. req.logEntry.Output += "OliveTin::shellAfterCompleted output complete\n"
  785. return true
  786. }
  787. //gocyclo:ignore
  788. func stepTrigger(req *ExecutionRequest) bool {
  789. if req.Binding.Action.Triggers == nil {
  790. return true
  791. }
  792. if req.TriggerDepth >= MaxTriggerDepth {
  793. log.WithFields(log.Fields{
  794. "actionTitle": req.logEntry.ActionTitle,
  795. "depth": req.TriggerDepth,
  796. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  797. req.logEntry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  798. return true
  799. }
  800. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  801. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  802. }
  803. triggerLoop(req)
  804. return true
  805. }
  806. func triggerLoop(req *ExecutionRequest) {
  807. for _, triggerTitle := range req.Binding.Action.Triggers {
  808. binding := req.executor.findBindingByActionTitle(triggerTitle, "")
  809. if binding == nil {
  810. log.WithFields(log.Fields{
  811. "triggerTitle": triggerTitle,
  812. "fromAction": req.logEntry.ActionTitle,
  813. }).Warnf("Trigger references unknown action title; skipping")
  814. continue
  815. }
  816. trigger := &ExecutionRequest{
  817. Binding: binding,
  818. TrackingID: uuid.NewString(),
  819. Tags: []string{"trigger"},
  820. AuthenticatedUser: req.AuthenticatedUser,
  821. Arguments: req.Arguments,
  822. Cfg: req.Cfg,
  823. TriggerDepth: req.TriggerDepth + 1,
  824. }
  825. req.executor.ExecRequest(trigger)
  826. }
  827. }
  828. func stepSaveLog(req *ExecutionRequest) bool {
  829. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  830. saveLogResults(req, filename)
  831. saveLogOutput(req, filename)
  832. return true
  833. }
  834. func firstNonEmpty(one, two string) string {
  835. if one != "" {
  836. return one
  837. }
  838. return two
  839. }
  840. func saveLogResults(req *ExecutionRequest, filename string) {
  841. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  842. if dir != "" {
  843. data, err := yaml.Marshal(req.logEntry)
  844. if err != nil {
  845. log.Warnf("%v", err)
  846. }
  847. filepath := path.Join(dir, filename+".yaml")
  848. err = os.WriteFile(filepath, data, 0600)
  849. if err != nil {
  850. log.Warnf("%v", err)
  851. }
  852. }
  853. }
  854. func saveLogOutput(req *ExecutionRequest, filename string) {
  855. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  856. if dir != "" {
  857. data := req.logEntry.Output
  858. filepath := path.Join(dir, filename+".log")
  859. err := os.WriteFile(filepath, []byte(data), 0600)
  860. if err != nil {
  861. log.Warnf("%v", err)
  862. }
  863. }
  864. }