executor.go 28 KB

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