executor.go 27 KB

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