gitea源码

init.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package actions
  4. import (
  5. "context"
  6. "errors"
  7. "fmt"
  8. "os"
  9. "strings"
  10. actions_model "code.gitea.io/gitea/models/actions"
  11. "code.gitea.io/gitea/modules/graceful"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/queue"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/util"
  16. notify_service "code.gitea.io/gitea/services/notify"
  17. )
  18. func initGlobalRunnerToken(ctx context.Context) error {
  19. // use the same env name as the runner, for consistency
  20. token := os.Getenv("GITEA_RUNNER_REGISTRATION_TOKEN")
  21. tokenFile := os.Getenv("GITEA_RUNNER_REGISTRATION_TOKEN_FILE")
  22. if token != "" && tokenFile != "" {
  23. return errors.New("both GITEA_RUNNER_REGISTRATION_TOKEN and GITEA_RUNNER_REGISTRATION_TOKEN_FILE are set, only one can be used")
  24. }
  25. if tokenFile != "" {
  26. file, err := os.ReadFile(tokenFile)
  27. if err != nil {
  28. return fmt.Errorf("unable to read GITEA_RUNNER_REGISTRATION_TOKEN_FILE: %w", err)
  29. }
  30. token = strings.TrimSpace(string(file))
  31. }
  32. if token == "" {
  33. return nil
  34. }
  35. if len(token) < 32 {
  36. return errors.New("GITEA_RUNNER_REGISTRATION_TOKEN must be at least 32 random characters")
  37. }
  38. existing, err := actions_model.GetRunnerToken(ctx, token)
  39. if err != nil && !errors.Is(err, util.ErrNotExist) {
  40. return fmt.Errorf("unable to check existing token: %w", err)
  41. }
  42. if existing != nil {
  43. if !existing.IsActive {
  44. log.Warn("The token defined by GITEA_RUNNER_REGISTRATION_TOKEN is already invalidated, please use the latest one from web UI")
  45. }
  46. return nil
  47. }
  48. _, err = actions_model.NewRunnerTokenWithValue(ctx, 0, 0, token)
  49. return err
  50. }
  51. func Init(ctx context.Context) error {
  52. if !setting.Actions.Enabled {
  53. return nil
  54. }
  55. jobEmitterQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "actions_ready_job", jobEmitterQueueHandler)
  56. if jobEmitterQueue == nil {
  57. return errors.New("unable to create actions_ready_job queue")
  58. }
  59. go graceful.GetManager().RunWithCancel(jobEmitterQueue)
  60. notify_service.RegisterNotifier(NewNotifier())
  61. return initGlobalRunnerToken(ctx)
  62. }