executor.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. package executor
  2. import (
  3. acl "github.com/OliveTin/OliveTin/internal/acl"
  4. config "github.com/OliveTin/OliveTin/internal/config"
  5. sv "github.com/OliveTin/OliveTin/internal/stringvariables"
  6. "github.com/google/uuid"
  7. log "github.com/sirupsen/logrus"
  8. "github.com/prometheus/client_golang/prometheus"
  9. "github.com/prometheus/client_golang/prometheus/promauto"
  10. "gopkg.in/yaml.v3"
  11. "bytes"
  12. "context"
  13. "fmt"
  14. "os"
  15. "path"
  16. "strings"
  17. "sync"
  18. "time"
  19. )
  20. var (
  21. metricActionsRequested = promauto.NewCounter(prometheus.CounterOpts{
  22. Name: "olivetin_actions_requested_count",
  23. Help: "The actions requested count",
  24. })
  25. )
  26. type ActionBinding struct {
  27. Action *config.Action
  28. EntityPrefix string
  29. ConfigOrder int
  30. }
  31. // Executor represents a helper class for executing commands. It's main method
  32. // is ExecRequest
  33. type Executor struct {
  34. logs map[string]*InternalLogEntry
  35. logsTrackingIdsByDate []string
  36. LogsByActionId map[string][]*InternalLogEntry
  37. logmutex sync.RWMutex
  38. MapActionIdToBinding map[string]*ActionBinding
  39. MapActionIdToBindingLock sync.RWMutex
  40. Cfg *config.Config
  41. listeners []listener
  42. chainOfCommand []executorStepFunc
  43. }
  44. // ExecutionRequest is a request to execute an action. It's passed to an
  45. // Executor. They're created from the grpcapi.
  46. type ExecutionRequest struct {
  47. ActionTitle string
  48. Action *config.Action
  49. Arguments map[string]string
  50. TrackingID string
  51. Tags []string
  52. Cfg *config.Config
  53. AuthenticatedUser *acl.AuthenticatedUser
  54. EntityPrefix string
  55. logEntry *InternalLogEntry
  56. finalParsedCommand string
  57. executor *Executor
  58. }
  59. // InternalLogEntry objects are created by an Executor, and represent the final
  60. // state of execution (even if the command is not executed). It's designed to be
  61. // easily serializable.
  62. type InternalLogEntry struct {
  63. DatetimeStarted time.Time
  64. DatetimeFinished time.Time
  65. Output string
  66. TimedOut bool
  67. Blocked bool
  68. ExitCode int32
  69. Tags []string
  70. ExecutionStarted bool
  71. ExecutionFinished bool
  72. ExecutionTrackingID string
  73. Process *os.Process
  74. Username string
  75. Index int64
  76. EntityPrefix string
  77. /*
  78. The following 3 properties are obviously on Action normally, but it's useful
  79. that logs are lightweight (so we don't need to have an action associated to
  80. logs, etc. Therefore, we duplicate those values here.
  81. */
  82. ActionTitle string
  83. ActionIcon string
  84. ActionId string
  85. }
  86. type executorStepFunc func(*ExecutionRequest) bool
  87. // DefaultExecutor returns an Executor, with a sensible "chain of command" for
  88. // executing actions.
  89. func DefaultExecutor(cfg *config.Config) *Executor {
  90. e := Executor{}
  91. e.Cfg = cfg
  92. e.logs = make(map[string]*InternalLogEntry)
  93. e.logsTrackingIdsByDate = make([]string, 0)
  94. e.LogsByActionId = make(map[string][]*InternalLogEntry)
  95. e.MapActionIdToBinding = make(map[string]*ActionBinding)
  96. e.chainOfCommand = []executorStepFunc{
  97. stepRequestAction,
  98. stepConcurrencyCheck,
  99. stepRateCheck,
  100. stepACLCheck,
  101. stepParseArgs,
  102. stepLogStart,
  103. stepExec,
  104. stepExecAfter,
  105. stepLogFinish,
  106. stepSaveLog,
  107. stepTrigger,
  108. }
  109. return &e
  110. }
  111. type listener interface {
  112. OnExecutionStarted(logEntry *InternalLogEntry)
  113. OnExecutionFinished(logEntry *InternalLogEntry)
  114. OnOutputChunk(o []byte, executionTrackingId string)
  115. OnActionMapRebuilt()
  116. }
  117. func (e *Executor) AddListener(m listener) {
  118. e.listeners = append(e.listeners, m)
  119. }
  120. // getPagingStartIndex calculates the starting index for log pagination.
  121. // Parameters:
  122. //
  123. // startOffset: The offset from the most recent log (0 means start from the most recent)
  124. // totalLogCount: Total number of logs available
  125. // count: Number of logs to retrieve
  126. //
  127. // Returns: The calculated starting index for pagination
  128. func getPagingStartIndex(startOffset int64, totalLogCount int64, count int64) int64 {
  129. var startIndex int64
  130. if startOffset <= 0 {
  131. startIndex = totalLogCount
  132. } else {
  133. startIndex = (totalLogCount - startOffset)
  134. if startIndex < 0 {
  135. startIndex = 1
  136. }
  137. }
  138. return startIndex - 1
  139. }
  140. func (e *Executor) GetLogTrackingIds(startOffset int64, pageCount int64) ([]*InternalLogEntry, int64) {
  141. e.logmutex.RLock()
  142. totalLogCount := int64(len(e.logsTrackingIdsByDate))
  143. startIndex := getPagingStartIndex(startOffset, totalLogCount, pageCount)
  144. pageCount = min(totalLogCount, pageCount)
  145. endIndex := max(0, (startIndex-pageCount)+1)
  146. log.WithFields(log.Fields{
  147. "startOffset": startOffset,
  148. "pageCount": pageCount,
  149. "total": totalLogCount,
  150. "startIndex": startIndex,
  151. "endIndex": endIndex,
  152. }).Tracef("GetLogTrackingIds")
  153. trackingIds := make([]*InternalLogEntry, 0, pageCount)
  154. if totalLogCount > 0 {
  155. for i := endIndex; i <= startIndex; i++ {
  156. trackingIds = append(trackingIds, e.logs[e.logsTrackingIdsByDate[i]])
  157. }
  158. }
  159. e.logmutex.RUnlock()
  160. remainingLogs := endIndex
  161. return trackingIds, remainingLogs
  162. }
  163. func (e *Executor) GetLog(trackingID string) (*InternalLogEntry, bool) {
  164. e.logmutex.RLock()
  165. entry, found := e.logs[trackingID]
  166. e.logmutex.RUnlock()
  167. return entry, found
  168. }
  169. func (e *Executor) GetLogsByActionId(actionId string) []*InternalLogEntry {
  170. e.logmutex.RLock()
  171. logs, found := e.LogsByActionId[actionId]
  172. e.logmutex.RUnlock()
  173. if !found {
  174. return make([]*InternalLogEntry, 0)
  175. }
  176. return logs
  177. }
  178. func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) {
  179. e.logmutex.Lock()
  180. entry.Index = int64(len(e.logsTrackingIdsByDate))
  181. e.logs[trackingID] = entry
  182. e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
  183. e.logmutex.Unlock()
  184. }
  185. // ExecRequest processes an ExecutionRequest
  186. func (e *Executor) ExecRequest(req *ExecutionRequest) (*sync.WaitGroup, string) {
  187. if req.AuthenticatedUser == nil {
  188. req.AuthenticatedUser = acl.UserGuest(req.Cfg)
  189. }
  190. req.executor = e
  191. req.logEntry = &InternalLogEntry{
  192. DatetimeStarted: time.Now(),
  193. ExecutionTrackingID: req.TrackingID,
  194. Output: "",
  195. ExitCode: -1337, // If an Action is not actually executed, this is the default exit code.
  196. ExecutionStarted: false,
  197. ExecutionFinished: false,
  198. ActionId: "",
  199. ActionTitle: "notfound",
  200. ActionIcon: "&#x1f4a9;",
  201. Username: req.AuthenticatedUser.Username,
  202. EntityPrefix: req.EntityPrefix,
  203. }
  204. _, isDuplicate := e.GetLog(req.TrackingID)
  205. if isDuplicate || req.TrackingID == "" {
  206. req.TrackingID = uuid.NewString()
  207. }
  208. log.Tracef("executor.ExecRequest(): %v", req)
  209. e.SetLog(req.TrackingID, req.logEntry)
  210. wg := new(sync.WaitGroup)
  211. wg.Add(1)
  212. go func() {
  213. e.execChain(req)
  214. defer wg.Done()
  215. }()
  216. return wg, req.TrackingID
  217. }
  218. func (e *Executor) execChain(req *ExecutionRequest) {
  219. for _, step := range e.chainOfCommand {
  220. if !step(req) {
  221. break
  222. }
  223. }
  224. req.logEntry.ExecutionFinished = true
  225. // This isn't a step, because we want to notify all listeners, irrespective
  226. // of how many steps were actually executed.
  227. notifyListenersFinished(req)
  228. }
  229. func getConcurrentCount(req *ExecutionRequest) int {
  230. concurrentCount := 0
  231. req.executor.logmutex.RLock()
  232. for _, log := range req.executor.GetLogsByActionId(req.Action.ID) {
  233. if !log.ExecutionFinished {
  234. concurrentCount += 1
  235. }
  236. }
  237. req.executor.logmutex.RUnlock()
  238. return concurrentCount
  239. }
  240. func stepConcurrencyCheck(req *ExecutionRequest) bool {
  241. concurrentCount := getConcurrentCount(req)
  242. // Note that the current execution is counted int the logs, so when checking we +1
  243. if concurrentCount >= (req.Action.MaxConcurrent + 1) {
  244. msg := fmt.Sprintf("Blocked from executing. This would mean this action is running %d times concurrently, but this action has maxExecutions set to %d.", concurrentCount, req.Action.MaxConcurrent)
  245. log.WithFields(log.Fields{
  246. "actionTitle": req.logEntry.ActionTitle,
  247. }).Warnf(msg)
  248. req.logEntry.Output = msg
  249. req.logEntry.Blocked = true
  250. return false
  251. }
  252. return true
  253. }
  254. func parseDuration(rate config.RateSpec) time.Duration {
  255. duration, err := time.ParseDuration(rate.Duration)
  256. if err != nil {
  257. log.Warnf("Could not parse duration: %v", rate.Duration)
  258. return -1 * time.Minute
  259. }
  260. return duration
  261. }
  262. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  263. executions := -1 // Because we will find ourself when checking execution logs
  264. duration := parseDuration(rate)
  265. then := time.Now().Add(-duration)
  266. for _, logEntry := range req.executor.GetLogsByActionId(req.Action.ID) {
  267. if logEntry.EntityPrefix != req.EntityPrefix {
  268. continue
  269. }
  270. if logEntry.DatetimeStarted.After(then) && !logEntry.Blocked {
  271. executions += 1
  272. }
  273. }
  274. return executions
  275. }
  276. func stepRateCheck(req *ExecutionRequest) bool {
  277. for _, rate := range req.Action.MaxRate {
  278. executions := getExecutionsCount(rate, req)
  279. if executions >= rate.Limit {
  280. msg := fmt.Sprintf("Blocked from executing. This action has run %d out of %d allowed times in the last %s.", executions, rate.Limit, rate.Duration)
  281. log.WithFields(log.Fields{
  282. "actionTitle": req.logEntry.ActionTitle,
  283. }).Infof(msg)
  284. req.logEntry.Output = msg
  285. req.logEntry.Blocked = true
  286. return false
  287. }
  288. }
  289. return true
  290. }
  291. func stepACLCheck(req *ExecutionRequest) bool {
  292. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Action)
  293. if !canExec {
  294. req.logEntry.Output = "ACL check failed. Blocked from executing."
  295. req.logEntry.Blocked = true
  296. log.WithFields(log.Fields{
  297. "actionTitle": req.logEntry.ActionTitle,
  298. }).Warnf("ACL check failed. Blocked from executing.")
  299. }
  300. return canExec
  301. }
  302. func stepParseArgs(req *ExecutionRequest) bool {
  303. var err error
  304. if req.Arguments == nil {
  305. req.Arguments = make(map[string]string)
  306. }
  307. req.Arguments["ot_executionTrackingId"] = req.TrackingID
  308. req.Arguments["ot_username"] = req.AuthenticatedUser.Username
  309. req.finalParsedCommand, err = parseActionArguments(req.Arguments, req.Action, req.logEntry.ActionTitle, req.EntityPrefix)
  310. if err != nil {
  311. req.logEntry.Output = err.Error()
  312. log.Warnf(err.Error())
  313. return false
  314. }
  315. return true
  316. }
  317. func stepRequestAction(req *ExecutionRequest) bool {
  318. // The grpc API always tries to find the action by ID, but it may
  319. if req.Action == nil {
  320. log.WithFields(log.Fields{
  321. "actionTitle": req.ActionTitle,
  322. }).Infof("Action finding by title")
  323. req.Action = req.Cfg.FindAction(req.ActionTitle)
  324. if req.Action == nil {
  325. log.WithFields(log.Fields{
  326. "actionTitle": req.ActionTitle,
  327. }).Warnf("Action requested, but not found")
  328. req.logEntry.Output = "Action not found: " + req.ActionTitle
  329. return false
  330. }
  331. }
  332. metricActionsRequested.Inc()
  333. req.logEntry.ActionTitle = sv.ReplaceEntityVars(req.EntityPrefix, req.Action.Title)
  334. req.logEntry.ActionIcon = req.Action.Icon
  335. req.logEntry.ActionId = req.Action.ID
  336. req.logEntry.Tags = req.Tags
  337. req.executor.logmutex.Lock()
  338. if _, containsKey := req.executor.LogsByActionId[req.Action.ID]; !containsKey {
  339. req.executor.LogsByActionId[req.Action.ID] = make([]*InternalLogEntry, 0)
  340. }
  341. req.executor.LogsByActionId[req.Action.ID] = append(req.executor.LogsByActionId[req.Action.ID], req.logEntry)
  342. req.executor.logmutex.Unlock()
  343. log.WithFields(log.Fields{
  344. "actionTitle": req.logEntry.ActionTitle,
  345. "tags": req.Tags,
  346. }).Infof("Action requested")
  347. notifyListenersStarted(req)
  348. return true
  349. }
  350. func stepLogStart(req *ExecutionRequest) bool {
  351. log.WithFields(log.Fields{
  352. "actionTitle": req.logEntry.ActionTitle,
  353. "timeout": req.Action.Timeout,
  354. }).Infof("Action started")
  355. return true
  356. }
  357. func stepLogFinish(req *ExecutionRequest) bool {
  358. req.logEntry.ExecutionFinished = true
  359. log.WithFields(log.Fields{
  360. "actionTitle": req.logEntry.ActionTitle,
  361. "outputLength": len(req.logEntry.Output),
  362. "timedOut": req.logEntry.TimedOut,
  363. "exit": req.logEntry.ExitCode,
  364. }).Infof("Action finished")
  365. return true
  366. }
  367. func notifyListenersFinished(req *ExecutionRequest) {
  368. for _, listener := range req.executor.listeners {
  369. listener.OnExecutionFinished(req.logEntry)
  370. }
  371. }
  372. func notifyListenersStarted(req *ExecutionRequest) {
  373. for _, listener := range req.executor.listeners {
  374. listener.OnExecutionStarted(req.logEntry)
  375. }
  376. }
  377. func appendErrorToStderr(err error, logEntry *InternalLogEntry) {
  378. if err != nil {
  379. logEntry.Output = err.Error() + "\n\n" + logEntry.Output
  380. }
  381. }
  382. type OutputStreamer struct {
  383. Req *ExecutionRequest
  384. output bytes.Buffer
  385. }
  386. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  387. for _, listener := range ost.Req.executor.listeners {
  388. listener.OnOutputChunk(o, ost.Req.TrackingID)
  389. }
  390. return ost.output.Write(o)
  391. }
  392. func (ost *OutputStreamer) String() string {
  393. return ost.output.String()
  394. }
  395. func buildEnv(args map[string]string) []string {
  396. ret := append(os.Environ(), "OLIVETIN=1")
  397. for k, v := range args {
  398. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  399. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  400. if varName == "" {
  401. continue
  402. }
  403. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  404. }
  405. return ret
  406. }
  407. func stepExec(req *ExecutionRequest) bool {
  408. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Action.Timeout)*time.Second)
  409. defer cancel()
  410. streamer := &OutputStreamer{Req: req}
  411. cmd := wrapCommandInShell(ctx, req.finalParsedCommand)
  412. cmd.Stdout = streamer
  413. cmd.Stderr = streamer
  414. cmd.Env = buildEnv(req.Arguments)
  415. req.logEntry.ExecutionStarted = true
  416. runerr := cmd.Start()
  417. req.logEntry.Process = cmd.Process
  418. waiterr := cmd.Wait()
  419. req.logEntry.ExitCode = int32(cmd.ProcessState.ExitCode())
  420. req.logEntry.Output = streamer.String()
  421. appendErrorToStderr(runerr, req.logEntry)
  422. appendErrorToStderr(waiterr, req.logEntry)
  423. if ctx.Err() == context.DeadlineExceeded {
  424. log.WithFields(log.Fields{
  425. "actionTitle": req.logEntry.ActionTitle,
  426. }).Warnf("Action timed out")
  427. // The context timeout should kill the process, but let's make sure.
  428. req.executor.Kill(req.logEntry)
  429. req.logEntry.TimedOut = true
  430. req.logEntry.Output += "OliveTin::timeout - this action timed out after " + fmt.Sprintf("%v", req.Action.Timeout) + " seconds. If you need more time for this action, set a longer timeout. See https://docs.olivetin.app/timeout.html for more help."
  431. }
  432. req.logEntry.DatetimeFinished = time.Now()
  433. return true
  434. }
  435. func stepExecAfter(req *ExecutionRequest) bool {
  436. if req.Action.ShellAfterCompleted == "" {
  437. return true
  438. }
  439. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Action.Timeout)*time.Second)
  440. defer cancel()
  441. var stdout bytes.Buffer
  442. var stderr bytes.Buffer
  443. args := map[string]string{
  444. "output": req.logEntry.Output,
  445. "exitCode": fmt.Sprintf("%v", req.logEntry.ExitCode),
  446. "ot_executionTrackingId": req.TrackingID,
  447. "ot_username": req.AuthenticatedUser.Username,
  448. }
  449. finalParsedCommand, _, err := parseCommandForReplacements(req.Action.ShellAfterCompleted, args)
  450. if err != nil {
  451. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  452. req.logEntry.Output += msg
  453. log.Warnf(msg)
  454. return true
  455. }
  456. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  457. cmd.Stdout = &stdout
  458. cmd.Stderr = &stderr
  459. cmd.Env = buildEnv(args)
  460. runerr := cmd.Start()
  461. waiterr := cmd.Wait()
  462. req.logEntry.Output += "\n"
  463. req.logEntry.Output += "OliveTin::shellAfterCompleted stdout\n"
  464. req.logEntry.Output += stdout.String()
  465. req.logEntry.Output += "OliveTin::shellAfterCompleted stderr\n"
  466. req.logEntry.Output += stderr.String()
  467. req.logEntry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  468. appendErrorToStderr(runerr, req.logEntry)
  469. appendErrorToStderr(waiterr, req.logEntry)
  470. if ctx.Err() == context.DeadlineExceeded {
  471. req.logEntry.Output += "Your shellAfterCompleted command timed out."
  472. }
  473. req.logEntry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", cmd.ProcessState.ExitCode())
  474. req.logEntry.Output += "OliveTin::shellAfterCompleted output complete\n"
  475. return true
  476. }
  477. func stepTrigger(req *ExecutionRequest) bool {
  478. if req.Action.Triggers == nil {
  479. return true
  480. }
  481. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  482. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  483. }
  484. triggerLoop(req)
  485. return true
  486. }
  487. func triggerLoop(req *ExecutionRequest) {
  488. for _, triggerReq := range req.Action.Triggers {
  489. trigger := &ExecutionRequest{
  490. ActionTitle: triggerReq,
  491. TrackingID: uuid.NewString(),
  492. Tags: []string{"trigger"},
  493. AuthenticatedUser: req.AuthenticatedUser,
  494. Cfg: req.Cfg,
  495. }
  496. req.executor.ExecRequest(trigger)
  497. }
  498. }
  499. func stepSaveLog(req *ExecutionRequest) bool {
  500. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  501. saveLogResults(req, filename)
  502. saveLogOutput(req, filename)
  503. return true
  504. }
  505. func firstNonEmpty(one, two string) string {
  506. if one != "" {
  507. return one
  508. }
  509. return two
  510. }
  511. func saveLogResults(req *ExecutionRequest, filename string) {
  512. dir := firstNonEmpty(req.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  513. if dir != "" {
  514. data, err := yaml.Marshal(req.logEntry)
  515. if err != nil {
  516. log.Warnf("%v", err)
  517. }
  518. filepath := path.Join(dir, filename+".yaml")
  519. err = os.WriteFile(filepath, data, 0644)
  520. if err != nil {
  521. log.Warnf("%v", err)
  522. }
  523. }
  524. }
  525. func saveLogOutput(req *ExecutionRequest, filename string) {
  526. dir := firstNonEmpty(req.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  527. if dir != "" {
  528. data := req.logEntry.Output
  529. filepath := path.Join(dir, filename+".log")
  530. err := os.WriteFile(filepath, []byte(data), 0644)
  531. if err != nil {
  532. log.Warnf("%v", err)
  533. }
  534. }
  535. }