executor.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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. //gocyclo:ignore
  263. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  264. executions := -1 // Because we will find ourself when checking execution logs
  265. duration := parseDuration(rate)
  266. then := time.Now().Add(-duration)
  267. for _, logEntry := range req.executor.GetLogsByActionId(req.Action.ID) {
  268. if logEntry.EntityPrefix != req.EntityPrefix {
  269. continue
  270. }
  271. if logEntry.DatetimeStarted.After(then) && !logEntry.Blocked {
  272. executions += 1
  273. }
  274. }
  275. return executions
  276. }
  277. func stepRateCheck(req *ExecutionRequest) bool {
  278. for _, rate := range req.Action.MaxRate {
  279. executions := getExecutionsCount(rate, req)
  280. if executions >= rate.Limit {
  281. 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)
  282. log.WithFields(log.Fields{
  283. "actionTitle": req.logEntry.ActionTitle,
  284. }).Infof(msg)
  285. req.logEntry.Output = msg
  286. req.logEntry.Blocked = true
  287. return false
  288. }
  289. }
  290. return true
  291. }
  292. func stepACLCheck(req *ExecutionRequest) bool {
  293. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Action)
  294. if !canExec {
  295. req.logEntry.Output = "ACL check failed. Blocked from executing."
  296. req.logEntry.Blocked = true
  297. log.WithFields(log.Fields{
  298. "actionTitle": req.logEntry.ActionTitle,
  299. }).Warnf("ACL check failed. Blocked from executing.")
  300. }
  301. return canExec
  302. }
  303. func stepParseArgs(req *ExecutionRequest) bool {
  304. var err error
  305. if req.Arguments == nil {
  306. req.Arguments = make(map[string]string)
  307. }
  308. req.Arguments["ot_executionTrackingId"] = req.TrackingID
  309. req.Arguments["ot_username"] = req.AuthenticatedUser.Username
  310. req.finalParsedCommand, err = parseActionArguments(req.Arguments, req.Action, req.logEntry.ActionTitle, req.EntityPrefix)
  311. if err != nil {
  312. req.logEntry.Output = err.Error()
  313. log.Warnf(err.Error())
  314. return false
  315. }
  316. return true
  317. }
  318. func stepRequestAction(req *ExecutionRequest) bool {
  319. // The grpc API always tries to find the action by ID, but it may
  320. if req.Action == nil {
  321. log.WithFields(log.Fields{
  322. "actionTitle": req.ActionTitle,
  323. }).Infof("Action finding by title")
  324. req.Action = req.Cfg.FindAction(req.ActionTitle)
  325. if req.Action == nil {
  326. log.WithFields(log.Fields{
  327. "actionTitle": req.ActionTitle,
  328. }).Warnf("Action requested, but not found")
  329. req.logEntry.Output = "Action not found: " + req.ActionTitle
  330. return false
  331. }
  332. }
  333. metricActionsRequested.Inc()
  334. req.logEntry.ActionTitle = sv.ReplaceEntityVars(req.EntityPrefix, req.Action.Title)
  335. req.logEntry.ActionIcon = req.Action.Icon
  336. req.logEntry.ActionId = req.Action.ID
  337. req.logEntry.Tags = req.Tags
  338. req.executor.logmutex.Lock()
  339. if _, containsKey := req.executor.LogsByActionId[req.Action.ID]; !containsKey {
  340. req.executor.LogsByActionId[req.Action.ID] = make([]*InternalLogEntry, 0)
  341. }
  342. req.executor.LogsByActionId[req.Action.ID] = append(req.executor.LogsByActionId[req.Action.ID], req.logEntry)
  343. req.executor.logmutex.Unlock()
  344. log.WithFields(log.Fields{
  345. "actionTitle": req.logEntry.ActionTitle,
  346. "tags": req.Tags,
  347. }).Infof("Action requested")
  348. notifyListenersStarted(req)
  349. return true
  350. }
  351. func stepLogStart(req *ExecutionRequest) bool {
  352. log.WithFields(log.Fields{
  353. "actionTitle": req.logEntry.ActionTitle,
  354. "timeout": req.Action.Timeout,
  355. }).Infof("Action started")
  356. return true
  357. }
  358. func stepLogFinish(req *ExecutionRequest) bool {
  359. req.logEntry.ExecutionFinished = true
  360. log.WithFields(log.Fields{
  361. "actionTitle": req.logEntry.ActionTitle,
  362. "outputLength": len(req.logEntry.Output),
  363. "timedOut": req.logEntry.TimedOut,
  364. "exit": req.logEntry.ExitCode,
  365. }).Infof("Action finished")
  366. return true
  367. }
  368. func notifyListenersFinished(req *ExecutionRequest) {
  369. for _, listener := range req.executor.listeners {
  370. listener.OnExecutionFinished(req.logEntry)
  371. }
  372. }
  373. func notifyListenersStarted(req *ExecutionRequest) {
  374. for _, listener := range req.executor.listeners {
  375. listener.OnExecutionStarted(req.logEntry)
  376. }
  377. }
  378. func appendErrorToStderr(err error, logEntry *InternalLogEntry) {
  379. if err != nil {
  380. logEntry.Output = err.Error() + "\n\n" + logEntry.Output
  381. }
  382. }
  383. type OutputStreamer struct {
  384. Req *ExecutionRequest
  385. output bytes.Buffer
  386. }
  387. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  388. for _, listener := range ost.Req.executor.listeners {
  389. listener.OnOutputChunk(o, ost.Req.TrackingID)
  390. }
  391. return ost.output.Write(o)
  392. }
  393. func (ost *OutputStreamer) String() string {
  394. return ost.output.String()
  395. }
  396. func buildEnv(args map[string]string) []string {
  397. ret := append(os.Environ(), "OLIVETIN=1")
  398. for k, v := range args {
  399. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  400. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  401. if varName == "" {
  402. continue
  403. }
  404. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  405. }
  406. return ret
  407. }
  408. func stepExec(req *ExecutionRequest) bool {
  409. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Action.Timeout)*time.Second)
  410. defer cancel()
  411. streamer := &OutputStreamer{Req: req}
  412. cmd := wrapCommandInShell(ctx, req.finalParsedCommand)
  413. cmd.Stdout = streamer
  414. cmd.Stderr = streamer
  415. cmd.Env = buildEnv(req.Arguments)
  416. req.logEntry.ExecutionStarted = true
  417. runerr := cmd.Start()
  418. req.logEntry.Process = cmd.Process
  419. waiterr := cmd.Wait()
  420. req.logEntry.ExitCode = int32(cmd.ProcessState.ExitCode())
  421. req.logEntry.Output = streamer.String()
  422. appendErrorToStderr(runerr, req.logEntry)
  423. appendErrorToStderr(waiterr, req.logEntry)
  424. if ctx.Err() == context.DeadlineExceeded {
  425. log.WithFields(log.Fields{
  426. "actionTitle": req.logEntry.ActionTitle,
  427. }).Warnf("Action timed out")
  428. // The context timeout should kill the process, but let's make sure.
  429. req.executor.Kill(req.logEntry)
  430. req.logEntry.TimedOut = true
  431. 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."
  432. }
  433. req.logEntry.DatetimeFinished = time.Now()
  434. return true
  435. }
  436. func stepExecAfter(req *ExecutionRequest) bool {
  437. if req.Action.ShellAfterCompleted == "" {
  438. return true
  439. }
  440. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Action.Timeout)*time.Second)
  441. defer cancel()
  442. var stdout bytes.Buffer
  443. var stderr bytes.Buffer
  444. args := map[string]string{
  445. "output": req.logEntry.Output,
  446. "exitCode": fmt.Sprintf("%v", req.logEntry.ExitCode),
  447. "ot_executionTrackingId": req.TrackingID,
  448. "ot_username": req.AuthenticatedUser.Username,
  449. }
  450. finalParsedCommand, _, err := parseCommandForReplacements(req.Action.ShellAfterCompleted, args)
  451. if err != nil {
  452. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  453. req.logEntry.Output += msg
  454. log.Warnf(msg)
  455. return true
  456. }
  457. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  458. cmd.Stdout = &stdout
  459. cmd.Stderr = &stderr
  460. cmd.Env = buildEnv(args)
  461. runerr := cmd.Start()
  462. waiterr := cmd.Wait()
  463. req.logEntry.Output += "\n"
  464. req.logEntry.Output += "OliveTin::shellAfterCompleted stdout\n"
  465. req.logEntry.Output += stdout.String()
  466. req.logEntry.Output += "OliveTin::shellAfterCompleted stderr\n"
  467. req.logEntry.Output += stderr.String()
  468. req.logEntry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  469. appendErrorToStderr(runerr, req.logEntry)
  470. appendErrorToStderr(waiterr, req.logEntry)
  471. if ctx.Err() == context.DeadlineExceeded {
  472. req.logEntry.Output += "Your shellAfterCompleted command timed out."
  473. }
  474. req.logEntry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", cmd.ProcessState.ExitCode())
  475. req.logEntry.Output += "OliveTin::shellAfterCompleted output complete\n"
  476. return true
  477. }
  478. func stepTrigger(req *ExecutionRequest) bool {
  479. if req.Action.Triggers == nil {
  480. return true
  481. }
  482. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  483. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  484. }
  485. triggerLoop(req)
  486. return true
  487. }
  488. func triggerLoop(req *ExecutionRequest) {
  489. for _, triggerReq := range req.Action.Triggers {
  490. trigger := &ExecutionRequest{
  491. ActionTitle: triggerReq,
  492. TrackingID: uuid.NewString(),
  493. Tags: []string{"trigger"},
  494. AuthenticatedUser: req.AuthenticatedUser,
  495. Cfg: req.Cfg,
  496. }
  497. req.executor.ExecRequest(trigger)
  498. }
  499. }
  500. func stepSaveLog(req *ExecutionRequest) bool {
  501. filename := fmt.Sprintf("%v.%v.%v", req.logEntry.ActionTitle, req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  502. saveLogResults(req, filename)
  503. saveLogOutput(req, filename)
  504. return true
  505. }
  506. func firstNonEmpty(one, two string) string {
  507. if one != "" {
  508. return one
  509. }
  510. return two
  511. }
  512. func saveLogResults(req *ExecutionRequest, filename string) {
  513. dir := firstNonEmpty(req.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  514. if dir != "" {
  515. data, err := yaml.Marshal(req.logEntry)
  516. if err != nil {
  517. log.Warnf("%v", err)
  518. }
  519. filepath := path.Join(dir, filename+".yaml")
  520. err = os.WriteFile(filepath, data, 0644)
  521. if err != nil {
  522. log.Warnf("%v", err)
  523. }
  524. }
  525. }
  526. func saveLogOutput(req *ExecutionRequest, filename string) {
  527. dir := firstNonEmpty(req.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  528. if dir != "" {
  529. data := req.logEntry.Output
  530. filepath := path.Join(dir, filename+".log")
  531. err := os.WriteFile(filepath, []byte(data), 0644)
  532. if err != nil {
  533. log.Warnf("%v", err)
  534. }
  535. }
  536. }