4
0

executor.go 17 KB

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