executor.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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) []*InternalLogEntry {
  196. e.logmutex.RLock()
  197. defer e.logmutex.RUnlock()
  198. filtered := make([]*InternalLogEntry, 0, len(e.logsTrackingIdsByDate))
  199. for _, trackingId := range e.logsTrackingIdsByDate {
  200. entry := e.logs[trackingId]
  201. if !isValidLogEntryForACL(entry) {
  202. continue
  203. }
  204. if isLogEntryAllowedByACL(cfg, user, entry) {
  205. filtered = append(filtered, entry)
  206. }
  207. }
  208. return filtered
  209. }
  210. // paginateFilteredLogs applies pagination to a filtered list of logs and returns
  211. // the paginated results along with pagination metadata.
  212. func paginateFilteredLogs(filtered []*InternalLogEntry, startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  213. total := int64(len(filtered))
  214. paging := &PagingResult{PageSize: pageCount, TotalCount: total, StartOffset: startOffset}
  215. if total == 0 {
  216. paging.CountRemaining = 0
  217. return []*InternalLogEntry{}, paging
  218. }
  219. startIndex := getPagingStartIndex(startOffset, total)
  220. pageCount = min(total, pageCount)
  221. endIndex := max(0, (startIndex-pageCount)+1)
  222. out := make([]*InternalLogEntry, 0, pageCount)
  223. for i := endIndex; i <= startIndex && i < int64(len(filtered)); i++ {
  224. out = append(out, filtered[i])
  225. }
  226. paging.CountRemaining = endIndex
  227. return out, paging
  228. }
  229. // GetLogTrackingIdsACL returns logs filtered by ACL visibility for the user and
  230. // paginated correctly based on the filtered set.
  231. func (e *Executor) GetLogTrackingIdsACL(cfg *config.Config, user *authpublic.AuthenticatedUser, startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  232. filtered := e.filterLogsByACL(cfg, user)
  233. return paginateFilteredLogs(filtered, startOffset, pageCount)
  234. }
  235. func (e *Executor) GetLog(trackingID string) (*InternalLogEntry, bool) {
  236. e.logmutex.RLock()
  237. entry, found := e.logs[trackingID]
  238. e.logmutex.RUnlock()
  239. return entry, found
  240. }
  241. func (e *Executor) GetLogsByBindingId(bindingId string) []*InternalLogEntry {
  242. e.logmutex.RLock()
  243. logs, found := e.LogsByBindingId[bindingId]
  244. e.logmutex.RUnlock()
  245. if !found {
  246. return make([]*InternalLogEntry, 0)
  247. }
  248. return logs
  249. }
  250. // shouldCountExecution checks if a log entry should be counted for rate limiting.
  251. func shouldCountExecution(logEntry *InternalLogEntry, windowStart time.Time) bool {
  252. return !logEntry.Blocked && logEntry.DatetimeStarted.After(windowStart)
  253. }
  254. // updateOldestExecution updates the oldest execution time if this entry is older.
  255. func updateOldestExecution(oldestExecutionTime **time.Time, logEntry *InternalLogEntry) {
  256. if *oldestExecutionTime == nil {
  257. *oldestExecutionTime = &logEntry.DatetimeStarted
  258. } else if logEntry.DatetimeStarted.Before(**oldestExecutionTime) {
  259. *oldestExecutionTime = &logEntry.DatetimeStarted
  260. }
  261. }
  262. // findOldestExecutionInWindow finds the oldest execution within the time window and counts executions.
  263. // Returns the count of executions and the oldest execution time, or nil if none found.
  264. func findOldestExecutionInWindow(logs []*InternalLogEntry, windowStart time.Time) (int, *time.Time) {
  265. executions := 0
  266. var oldestExecutionTime *time.Time
  267. for _, logEntry := range logs {
  268. if !shouldCountExecution(logEntry, windowStart) {
  269. continue
  270. }
  271. executions++
  272. updateOldestExecution(&oldestExecutionTime, logEntry)
  273. }
  274. return executions, oldestExecutionTime
  275. }
  276. // calculateExpiryTime calculates when the oldest execution will fall outside the rate limit window.
  277. func calculateExpiryTime(oldestExecutionTime time.Time, duration time.Duration, now time.Time) time.Time {
  278. expiryTime := oldestExecutionTime.Add(duration)
  279. if !expiryTime.After(now) {
  280. return time.Time{}
  281. }
  282. return expiryTime
  283. }
  284. // updateMaxExpiryTime updates maxExpiryTime if expiryTime is later.
  285. func updateMaxExpiryTime(maxExpiryTime *time.Time, expiryTime time.Time) {
  286. if expiryTime.IsZero() {
  287. return
  288. }
  289. if maxExpiryTime.IsZero() || expiryTime.After(*maxExpiryTime) {
  290. *maxExpiryTime = expiryTime
  291. }
  292. }
  293. // calculateExpiryForRate calculates the expiry time for a single rate limit rule.
  294. // Returns the expiry time if the rate limit is exceeded, or zero time if not.
  295. func calculateExpiryForRate(rate config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  296. duration := parseDuration(rate)
  297. if duration <= 0 {
  298. return time.Time{}
  299. }
  300. windowStart := now.Add(-duration)
  301. executions, oldestExecutionTime := findOldestExecutionInWindow(logs, windowStart)
  302. if executions < rate.Limit || oldestExecutionTime == nil {
  303. return time.Time{}
  304. }
  305. return calculateExpiryTime(*oldestExecutionTime, duration, now)
  306. }
  307. // getLogsForBinding retrieves logs for a binding ID.
  308. func (e *Executor) getLogsForBinding(bindingId string) []*InternalLogEntry {
  309. e.logmutex.RLock()
  310. logs, found := e.LogsByBindingId[bindingId]
  311. e.logmutex.RUnlock()
  312. if !found || len(logs) == 0 {
  313. return nil
  314. }
  315. return logs
  316. }
  317. // calculateMaxExpiryTimeFromRates calculates the maximum expiry time across all rate limit rules.
  318. func calculateMaxExpiryTimeFromRates(rates []config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  319. var maxExpiryTime time.Time
  320. for _, rate := range rates {
  321. expiryTime := calculateExpiryForRate(rate, logs, now)
  322. updateMaxExpiryTime(&maxExpiryTime, expiryTime)
  323. }
  324. return maxExpiryTime
  325. }
  326. // GetTimeUntilAvailable calculates when an action will be available again based on rate limits.
  327. // Returns the Unix timestamp in seconds when the rate limit expires, or 0 if the action is available now.
  328. func (e *Executor) GetTimeUntilAvailable(binding *ActionBinding) int64 {
  329. if len(binding.Action.MaxRate) == 0 {
  330. return 0
  331. }
  332. logs := e.getLogsForBinding(binding.ID)
  333. if logs == nil {
  334. return 0
  335. }
  336. maxExpiryTime := calculateMaxExpiryTimeFromRates(binding.Action.MaxRate, logs, time.Now())
  337. if maxExpiryTime.IsZero() {
  338. return 0
  339. }
  340. return maxExpiryTime.Unix()
  341. }
  342. func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) {
  343. e.logmutex.Lock()
  344. entry.Index = int64(len(e.logsTrackingIdsByDate))
  345. e.logs[trackingID] = entry
  346. e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
  347. e.logmutex.Unlock()
  348. }
  349. // ExecRequest processes an ExecutionRequest
  350. func (e *Executor) ExecRequest(req *ExecutionRequest) (*sync.WaitGroup, string) {
  351. if req.AuthenticatedUser == nil {
  352. req.AuthenticatedUser = auth.UserGuest(req.Cfg)
  353. }
  354. req.executor = e
  355. req.logEntry = &InternalLogEntry{
  356. Binding: req.Binding,
  357. DatetimeStarted: time.Now(),
  358. ExecutionTrackingID: req.TrackingID,
  359. Output: "",
  360. ExitCode: DefaultExitCodeNotExecuted,
  361. ExecutionStarted: false,
  362. ExecutionFinished: false,
  363. ActionTitle: "notfound",
  364. ActionIcon: "&#x1f4a9;",
  365. Username: req.AuthenticatedUser.Username,
  366. }
  367. _, isDuplicate := e.GetLog(req.TrackingID)
  368. if isDuplicate || req.TrackingID == "" {
  369. req.TrackingID = uuid.NewString()
  370. }
  371. // Update the log entry with the final tracking ID
  372. req.logEntry.ExecutionTrackingID = req.TrackingID
  373. log.Tracef("executor.ExecRequest(): %v", req)
  374. e.SetLog(req.TrackingID, req.logEntry)
  375. wg := new(sync.WaitGroup)
  376. wg.Add(1)
  377. go func() {
  378. e.execChain(req)
  379. defer wg.Done()
  380. }()
  381. return wg, req.TrackingID
  382. }
  383. func (e *Executor) execChain(req *ExecutionRequest) {
  384. for _, step := range e.chainOfCommand {
  385. if !step(req) {
  386. break
  387. }
  388. }
  389. // Ensure DatetimeFinished is set even if execution was blocked early
  390. if req.logEntry.DatetimeFinished.IsZero() {
  391. req.logEntry.DatetimeFinished = time.Now()
  392. }
  393. req.logEntry.ExecutionFinished = true
  394. // This isn't a step, because we want to notify all listeners, irrespective
  395. // of how many steps were actually executed.
  396. notifyListenersFinished(req)
  397. }
  398. func getConcurrentCount(req *ExecutionRequest) int {
  399. concurrentCount := 0
  400. req.executor.logmutex.RLock()
  401. for _, log := range req.executor.GetLogsByBindingId(req.Binding.ID) {
  402. if !log.ExecutionFinished {
  403. concurrentCount += 1
  404. }
  405. }
  406. req.executor.logmutex.RUnlock()
  407. return concurrentCount
  408. }
  409. func stepConcurrencyCheck(req *ExecutionRequest) bool {
  410. concurrentCount := getConcurrentCount(req)
  411. // Note that the current execution is counted int the logs, so when checking we +1
  412. if concurrentCount >= (req.Binding.Action.MaxConcurrent + 1) {
  413. log.WithFields(log.Fields{
  414. "actionTitle": req.logEntry.ActionTitle,
  415. "concurrentCount": concurrentCount,
  416. "maxConcurrent": req.Binding.Action.MaxConcurrent,
  417. }).Warnf("Blocked from executing due to concurrency limit")
  418. req.logEntry.Output = "Blocked from executing due to concurrency limit"
  419. req.logEntry.Blocked = true
  420. return false
  421. }
  422. return true
  423. }
  424. func parseDuration(rate config.RateSpec) time.Duration {
  425. duration, err := time.ParseDuration(rate.Duration)
  426. if err != nil {
  427. log.Warnf("Could not parse duration: %v", rate.Duration)
  428. return -1 * time.Minute
  429. }
  430. return duration
  431. }
  432. //gocyclo:ignore
  433. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  434. executions := -1 // Because we will find ourself when checking execution logs
  435. duration := parseDuration(rate)
  436. then := time.Now().Add(-duration)
  437. for _, logEntry := range req.executor.GetLogsByBindingId(req.Binding.ID) {
  438. // FIXME
  439. /*
  440. if logEntry.EntityPrefix != req.EntityPrefix {
  441. continue
  442. }
  443. */
  444. if logEntry.DatetimeStarted.After(then) && !logEntry.Blocked {
  445. executions += 1
  446. }
  447. }
  448. return executions
  449. }
  450. func stepRateCheck(req *ExecutionRequest) bool {
  451. for _, rate := range req.Binding.Action.MaxRate {
  452. executions := getExecutionsCount(rate, req)
  453. if executions >= rate.Limit {
  454. log.WithFields(log.Fields{
  455. "actionTitle": req.logEntry.ActionTitle,
  456. "executions": executions,
  457. "limit": rate.Limit,
  458. "duration": rate.Duration,
  459. }).Infof("Blocked from executing due to rate limit")
  460. req.logEntry.Output = "Blocked from executing due to rate limit"
  461. req.logEntry.Blocked = true
  462. return false
  463. }
  464. }
  465. return true
  466. }
  467. func stepACLCheck(req *ExecutionRequest) bool {
  468. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Binding.Action)
  469. if !canExec {
  470. req.logEntry.Output = "ACL check failed. Blocked from executing."
  471. req.logEntry.Blocked = true
  472. log.WithFields(log.Fields{
  473. "actionTitle": req.logEntry.ActionTitle,
  474. }).Warnf("ACL check failed. Blocked from executing.")
  475. }
  476. return canExec
  477. }
  478. func stepParseArgs(req *ExecutionRequest) bool {
  479. ensureArgumentMap(req)
  480. injectSystemArgs(req)
  481. if !hasBindingAndAction(req) {
  482. return fail(req, fmt.Errorf("cannot parse arguments: Binding or Action is nil"))
  483. }
  484. mangleInvalidArgumentValues(req)
  485. if hasExec(req) {
  486. return handleExecBranch(req)
  487. } else {
  488. return handleShellBranch(req)
  489. }
  490. }
  491. func handleExecBranch(req *ExecutionRequest) bool {
  492. args, err := parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
  493. if err != nil {
  494. return fail(req, err)
  495. }
  496. req.useDirectExec = true
  497. req.execArgs = args
  498. return true
  499. }
  500. func handleShellBranch(req *ExecutionRequest) bool {
  501. if err := checkShellArgumentSafety(req.Binding.Action); err != nil {
  502. return fail(req, err)
  503. }
  504. cmd, err := parseActionArguments(req.Arguments, req.Binding.Action, req.Binding.Entity)
  505. if err != nil {
  506. return fail(req, err)
  507. }
  508. req.useDirectExec = false
  509. req.finalParsedCommand = cmd
  510. return true
  511. }
  512. func ensureArgumentMap(req *ExecutionRequest) {
  513. if req.Arguments == nil {
  514. req.Arguments = make(map[string]string)
  515. }
  516. }
  517. func injectSystemArgs(req *ExecutionRequest) {
  518. req.Arguments["ot_executionTrackingId"] = req.TrackingID
  519. req.Arguments["ot_username"] = req.AuthenticatedUser.Username
  520. }
  521. func hasBindingAndAction(req *ExecutionRequest) bool {
  522. return !(req.Binding == nil || req.Binding.Action == nil)
  523. }
  524. func hasExec(req *ExecutionRequest) bool {
  525. return len(req.Binding.Action.Exec) > 0
  526. }
  527. func fail(req *ExecutionRequest, err error) bool {
  528. req.logEntry.Output = err.Error()
  529. log.Warn(err.Error())
  530. return false
  531. }
  532. func stepRequestAction(req *ExecutionRequest) bool {
  533. metricActionsRequested.Inc()
  534. // If there is no binding or action, do not proceed. Leave default
  535. // log entry values (icon/title/id) and stop execution gracefully.
  536. if req.Binding == nil || req.Binding.Action == nil {
  537. log.Warnf("Action request has no binding/action; skipping execution")
  538. return false
  539. }
  540. req.logEntry.Binding = req.Binding
  541. req.logEntry.ActionConfigTitle = req.Binding.Action.Title
  542. req.logEntry.ActionTitle = entities.ParseTemplateWith(req.Binding.Action.Title, req.Binding.Entity)
  543. req.logEntry.ActionIcon = req.Binding.Action.Icon
  544. req.logEntry.Tags = req.Tags
  545. req.executor.logmutex.Lock()
  546. if _, containsKey := req.executor.LogsByBindingId[req.Binding.ID]; !containsKey {
  547. req.executor.LogsByBindingId[req.Binding.ID] = make([]*InternalLogEntry, 0)
  548. }
  549. req.executor.LogsByBindingId[req.Binding.ID] = append(req.executor.LogsByBindingId[req.Binding.ID], req.logEntry)
  550. req.executor.logmutex.Unlock()
  551. log.WithFields(log.Fields{
  552. "actionTitle": req.logEntry.ActionTitle,
  553. "tags": req.Tags,
  554. }).Infof("Action requested")
  555. notifyListenersStarted(req)
  556. return true
  557. }
  558. func stepLogStart(req *ExecutionRequest) bool {
  559. log.WithFields(log.Fields{
  560. "actionTitle": req.logEntry.ActionTitle,
  561. "timeout": req.Binding.Action.Timeout,
  562. }).Infof("Action started")
  563. return true
  564. }
  565. func stepLogFinish(req *ExecutionRequest) bool {
  566. req.logEntry.ExecutionFinished = true
  567. log.WithFields(log.Fields{
  568. "actionTitle": req.logEntry.ActionTitle,
  569. "outputLength": len(req.logEntry.Output),
  570. "timedOut": req.logEntry.TimedOut,
  571. "exit": req.logEntry.ExitCode,
  572. }).Infof("Action finished")
  573. return true
  574. }
  575. func notifyListenersFinished(req *ExecutionRequest) {
  576. for _, listener := range req.executor.listeners {
  577. listener.OnExecutionFinished(req.logEntry)
  578. }
  579. }
  580. func notifyListenersStarted(req *ExecutionRequest) {
  581. for _, listener := range req.executor.listeners {
  582. listener.OnExecutionStarted(req.logEntry)
  583. }
  584. }
  585. func appendErrorToStderr(err error, logEntry *InternalLogEntry) {
  586. if err != nil {
  587. logEntry.Output = err.Error() + "\n\n" + logEntry.Output
  588. }
  589. }
  590. type OutputStreamer struct {
  591. Req *ExecutionRequest
  592. output bytes.Buffer
  593. }
  594. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  595. for _, listener := range ost.Req.executor.listeners {
  596. listener.OnOutputChunk(o, ost.Req.TrackingID)
  597. }
  598. return ost.output.Write(o)
  599. }
  600. func (ost *OutputStreamer) String() string {
  601. return ost.output.String()
  602. }
  603. func buildEnv(args map[string]string) []string {
  604. ret := append(os.Environ(), "OLIVETIN=1")
  605. for k, v := range args {
  606. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  607. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  608. if varName == "" {
  609. continue
  610. }
  611. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  612. }
  613. return ret
  614. }
  615. func stepExec(req *ExecutionRequest) bool {
  616. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  617. defer cancel()
  618. streamer := &OutputStreamer{Req: req}
  619. cmd := buildCommand(ctx, req)
  620. if cmd == nil {
  621. req.logEntry.Output = "Cannot execute: no command arguments provided"
  622. log.Warn("Cannot execute: no command arguments provided")
  623. return false
  624. }
  625. prepareCommand(cmd, streamer, req)
  626. runerr := cmd.Start()
  627. req.logEntry.Process = cmd.Process
  628. waiterr := cmd.Wait()
  629. req.logEntry.ExitCode = int32(cmd.ProcessState.ExitCode())
  630. req.logEntry.Output = streamer.String()
  631. appendErrorToStderr(runerr, req.logEntry)
  632. appendErrorToStderr(waiterr, req.logEntry)
  633. if ctx.Err() == context.DeadlineExceeded {
  634. log.WithFields(log.Fields{
  635. "actionTitle": req.logEntry.ActionTitle,
  636. }).Warnf("Action timed out")
  637. // The context timeout should kill the process, but let's make sure.
  638. err := req.executor.Kill(req.logEntry)
  639. if err != nil {
  640. log.WithFields(log.Fields{
  641. "actionTitle": req.logEntry.ActionTitle,
  642. }).Warnf("could not kill process: %v", err)
  643. }
  644. req.logEntry.TimedOut = true
  645. 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."
  646. }
  647. req.logEntry.DatetimeFinished = time.Now()
  648. return true
  649. }
  650. func buildCommand(ctx context.Context, req *ExecutionRequest) *exec.Cmd {
  651. if req.useDirectExec {
  652. return wrapCommandDirect(ctx, req.execArgs)
  653. }
  654. return wrapCommandInShell(ctx, req.finalParsedCommand)
  655. }
  656. func prepareCommand(cmd *exec.Cmd, streamer *OutputStreamer, req *ExecutionRequest) {
  657. cmd.Stdout = streamer
  658. cmd.Stderr = streamer
  659. cmd.Env = buildEnv(req.Arguments)
  660. req.logEntry.ExecutionStarted = true
  661. }
  662. func stepExecAfter(req *ExecutionRequest) bool {
  663. if req.Binding.Action.ShellAfterCompleted == "" {
  664. return true
  665. }
  666. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second)
  667. defer cancel()
  668. var stdout bytes.Buffer
  669. var stderr bytes.Buffer
  670. args := map[string]string{
  671. "output": req.logEntry.Output,
  672. "exitCode": fmt.Sprintf("%v", req.logEntry.ExitCode),
  673. "ot_executionTrackingId": req.TrackingID,
  674. "ot_username": req.AuthenticatedUser.Username,
  675. }
  676. finalParsedCommand, err := parseCommandForReplacements(req.Binding.Action.ShellAfterCompleted, args, req.Binding.Entity)
  677. if err != nil {
  678. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  679. req.logEntry.Output += msg
  680. log.Warn(msg)
  681. return true
  682. }
  683. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  684. cmd.Stdout = &stdout
  685. cmd.Stderr = &stderr
  686. cmd.Env = buildEnv(args)
  687. runerr := cmd.Start()
  688. waiterr := cmd.Wait()
  689. req.logEntry.Output += "\n"
  690. req.logEntry.Output += "OliveTin::shellAfterCompleted stdout\n"
  691. req.logEntry.Output += stdout.String()
  692. req.logEntry.Output += "OliveTin::shellAfterCompleted stderr\n"
  693. req.logEntry.Output += stderr.String()
  694. req.logEntry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  695. appendErrorToStderr(runerr, req.logEntry)
  696. appendErrorToStderr(waiterr, req.logEntry)
  697. if ctx.Err() == context.DeadlineExceeded {
  698. req.logEntry.Output += "Your shellAfterCompleted command timed out."
  699. }
  700. req.logEntry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", cmd.ProcessState.ExitCode())
  701. req.logEntry.Output += "OliveTin::shellAfterCompleted output complete\n"
  702. return true
  703. }
  704. //gocyclo:ignore
  705. func stepTrigger(req *ExecutionRequest) bool {
  706. if req.Binding.Action.Triggers == nil {
  707. return true
  708. }
  709. if req.TriggerDepth >= MaxTriggerDepth {
  710. log.WithFields(log.Fields{
  711. "actionTitle": req.logEntry.ActionTitle,
  712. "depth": req.TriggerDepth,
  713. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  714. req.logEntry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  715. return true
  716. }
  717. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  718. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  719. }
  720. triggerLoop(req)
  721. return true
  722. }
  723. func triggerLoop(req *ExecutionRequest) {
  724. for _, triggerReq := range req.Binding.Action.Triggers {
  725. binding := req.executor.FindBindingByID(triggerReq)
  726. trigger := &ExecutionRequest{
  727. Binding: binding,
  728. TrackingID: uuid.NewString(),
  729. Tags: []string{"trigger"},
  730. AuthenticatedUser: req.AuthenticatedUser,
  731. Arguments: req.Arguments,
  732. Cfg: req.Cfg,
  733. TriggerDepth: req.TriggerDepth + 1,
  734. }
  735. req.executor.ExecRequest(trigger)
  736. }
  737. }
  738. func stepSaveLog(req *ExecutionRequest) bool {
  739. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  740. saveLogResults(req, filename)
  741. saveLogOutput(req, filename)
  742. return true
  743. }
  744. func firstNonEmpty(one, two string) string {
  745. if one != "" {
  746. return one
  747. }
  748. return two
  749. }
  750. func saveLogResults(req *ExecutionRequest, filename string) {
  751. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  752. if dir != "" {
  753. data, err := yaml.Marshal(req.logEntry)
  754. if err != nil {
  755. log.Warnf("%v", err)
  756. }
  757. filepath := path.Join(dir, filename+".yaml")
  758. err = os.WriteFile(filepath, data, 0644)
  759. if err != nil {
  760. log.Warnf("%v", err)
  761. }
  762. }
  763. }
  764. func saveLogOutput(req *ExecutionRequest, filename string) {
  765. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  766. if dir != "" {
  767. data := req.logEntry.Output
  768. filepath := path.Join(dir, filename+".log")
  769. err := os.WriteFile(filepath, []byte(data), 0644)
  770. if err != nil {
  771. log.Warnf("%v", err)
  772. }
  773. }
  774. }