autogits/prjgit-updater/main.go

440 lines
14 KiB
Go
Raw Normal View History

2024-07-07 21:08:41 +02:00
package main
2024-09-10 18:24:41 +02:00
/*
* This file is part of Autogits.
*
* Copyright © 2024 SUSE LLC
*
* Autogits is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* Autogits is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* Foobar. If not, see <https://www.gnu.org/licenses/>.
*/
2024-07-07 21:08:41 +02:00
import (
2024-08-26 17:07:52 +02:00
"flag"
2024-07-07 21:08:41 +02:00
"fmt"
2024-08-26 17:07:52 +02:00
"log"
2024-08-28 12:39:32 +02:00
"math/rand"
2024-07-07 21:08:41 +02:00
"os"
2024-09-05 15:02:26 +02:00
"path"
2024-07-07 21:08:41 +02:00
"path/filepath"
2024-08-28 00:45:47 +02:00
"slices"
2024-08-28 12:39:32 +02:00
"time"
2024-07-07 21:08:41 +02:00
"src.opensuse.org/autogits/common"
)
2024-09-04 14:04:13 +02:00
const AppName = "direct_workflow"
const GitAuthor = "AutoGits prjgit-updater"
const GitEmail = "adam+autogits-direct@zombino.com"
var configuredRepos map[string][]*common.AutogitConfig
2024-08-30 17:05:57 +02:00
var gitea *common.GiteaTransport
2024-08-28 00:45:47 +02:00
2024-08-30 16:37:51 +02:00
func isConfiguredOrg(org *common.Organization) bool {
_, found := configuredRepos[org.Username]
return found
}
2024-09-04 14:04:13 +02:00
func concatenateErrors(err1, err2 error) error {
if err1 == nil {
return err2
}
if err2 == nil {
return err1
}
return fmt.Errorf("%w\n%w", err1, err2)
}
2024-07-08 17:14:18 +02:00
func processRepositoryAction(h *common.RequestHandler) error {
2024-08-28 00:45:47 +02:00
action := h.Request.Data.(*common.RepositoryWebhookEvent)
2024-09-04 14:04:13 +02:00
configs, configFound := configuredRepos[action.Organization.Username]
2024-07-07 21:08:41 +02:00
2024-08-30 16:37:51 +02:00
if !configFound {
2024-09-04 14:04:13 +02:00
h.StdLogger.Printf("Repository event for %s. Not configured. Ignoring.\n", action.Organization.Username)
2024-07-08 17:14:18 +02:00
return nil
2024-07-07 21:08:41 +02:00
}
2024-09-05 15:41:02 +02:00
for _, config := range configs {
if config.GitProjectName == action.Repository.Name {
h.StdLogger.Println("+ ignoring repo event for PrjGit repository", config.GitProjectName)
2024-09-12 14:15:59 +02:00
return nil
2024-09-05 15:41:02 +02:00
}
}
2024-09-04 14:04:13 +02:00
var err error
for _, config := range configs {
err = concatenateErrors(err, processConfiguredRepositoryAction(h, action, config))
}
return err
}
2024-09-11 18:50:49 +02:00
2024-09-04 14:04:13 +02:00
func processConfiguredRepositoryAction(h *common.RequestHandler, action *common.RepositoryWebhookEvent, config *common.AutogitConfig) error {
2024-09-02 17:27:23 +02:00
prjgit := config.GitProjectName
2024-09-04 14:04:13 +02:00
git, err := common.CreateGitHandler(GitAuthor, GitEmail, AppName)
2024-09-11 18:50:49 +02:00
common.PanicOnError(err)
if !debugMode {
defer git.Close()
}
2024-09-04 14:04:13 +02:00
if len(config.Branch) == 0 {
config.Branch = action.Repository.Default_Branch
}
2024-09-04 14:04:13 +02:00
prjGitRepo, err := gitea.CreateRepositoryIfNotExist(git, *action.Organization, prjgit)
2024-08-30 16:37:51 +02:00
if err != nil {
return fmt.Errorf("Error accessing/creating prjgit: %s err: %w", prjgit, err)
}
2024-09-04 14:04:13 +02:00
common.PanicOnError(git.GitExec("", "clone", "--depth", "1", prjGitRepo.SSHURL, prjgit))
2024-07-07 21:08:41 +02:00
switch action.Action {
case "created":
common.PanicOnError(git.GitExec(prjgit, "submodule", "--quiet", "add", "--depth", "1", action.Repository.Clone_Url, action.Repository.Name))
if _, err := git.GitBranchHead(path.Join(prjgit, action.Repository.Name), config.Branch); err != nil {
if err := git.GitExec(path.Join(prjgit, action.Repository.Name), "fetch", "--depth", "1", "origin", config.Branch+":"+config.Branch); err != nil {
return fmt.Errorf("error fetching branch %s. ignoring as non-existent. err: %w", config.Branch, err) // no branch? so ignore repo here
}
}
common.PanicOnError(git.GitExec(path.Join(prjgit, action.Repository.Name), "checkout", config.Branch))
common.PanicOnError(git.GitExec(prjgit, "commit", "-m", "Automatic package inclusion via Direct Workflow"))
common.PanicOnError(git.GitExec(prjgit, "push"))
2024-08-30 16:37:51 +02:00
2024-07-07 21:08:41 +02:00
case "deleted":
if stat, err := os.Stat(filepath.Join(git.GitPath, prjgit, action.Repository.Name)); err != nil || !stat.IsDir() {
2024-09-04 14:04:13 +02:00
if git.DebugLogger {
2024-08-30 16:37:51 +02:00
h.StdLogger.Printf("delete event for %s -- not in project. Ignoring\n", action.Repository.Name)
}
2024-07-08 17:14:18 +02:00
return nil
2024-07-07 21:08:41 +02:00
}
common.PanicOnError(git.GitExec(prjgit, "rm", action.Repository.Name))
common.PanicOnError(git.GitExec(prjgit, "commit", "-m", "Automatic package removal via Direct Workflow"))
common.PanicOnError(git.GitExec(prjgit, "push"))
2024-08-30 16:37:51 +02:00
2024-07-07 21:08:41 +02:00
default:
2024-07-08 17:14:18 +02:00
return fmt.Errorf("%s: %s", "Unknown action type", action.Action)
2024-07-07 21:08:41 +02:00
}
2024-07-08 17:14:18 +02:00
return nil
}
2024-07-07 21:08:41 +02:00
2024-07-08 17:14:18 +02:00
func processPushAction(h *common.RequestHandler) error {
2024-08-28 00:45:47 +02:00
action := h.Request.Data.(*common.PushWebhookEvent)
2024-09-04 14:04:13 +02:00
configs, configFound := configuredRepos[action.Repository.Owner.Username]
2024-08-30 16:37:51 +02:00
if !configFound {
2024-09-04 14:04:13 +02:00
h.StdLogger.Printf("Repository event for %s. Not configured. Ignoring.\n", action.Repository.Owner.Username)
2024-08-30 16:37:51 +02:00
return nil
}
2024-07-07 21:08:41 +02:00
2024-09-05 15:39:42 +02:00
for _, config := range configs {
if config.GitProjectName == action.Repository.Name {
h.StdLogger.Println("+ ignoring push to PrjGit repository", config.GitProjectName)
2024-09-12 14:15:59 +02:00
return nil
2024-09-05 15:39:42 +02:00
}
}
2024-09-04 14:04:13 +02:00
var err error
for _, config := range configs {
err = concatenateErrors(err, processConfiguredPushAction(h, action, config))
}
return err
}
func processConfiguredPushAction(h *common.RequestHandler, action *common.PushWebhookEvent, config *common.AutogitConfig) error {
2024-09-02 17:27:23 +02:00
prjgit := config.GitProjectName
2024-09-04 14:04:13 +02:00
git, err := common.CreateGitHandler(GitAuthor, GitEmail, AppName)
2024-09-11 18:50:49 +02:00
common.PanicOnError(err)
if !debugMode {
defer git.Close()
}
2024-09-04 14:04:13 +02:00
if len(config.Branch) == 0 {
config.Branch = action.Repository.Default_Branch
}
2024-09-04 14:04:13 +02:00
prjGitRepo, err := gitea.CreateRepositoryIfNotExist(git, *action.Repository.Owner, prjgit)
2024-08-30 16:37:51 +02:00
if err != nil {
return fmt.Errorf("Error accessing/creating prjgit: %s err: %w", prjgit, err)
}
2024-09-04 14:04:13 +02:00
common.PanicOnError(git.GitExec("", "clone", "--depth", "1", prjGitRepo.SSHURL, prjgit))
if stat, err := os.Stat(filepath.Join(git.GitPath, prjgit, action.Repository.Name)); err != nil || !stat.IsDir() {
2024-09-04 14:04:13 +02:00
if git.DebugLogger {
h.StdLogger.Println("Pushed to package that is not part of the project. Ignoring:", err)
2024-08-30 16:37:51 +02:00
}
2024-08-28 00:45:47 +02:00
return nil
2024-07-07 21:08:41 +02:00
}
common.PanicOnError(git.GitExec(prjgit, "submodule", "update", "--init", "--depth", "1", "--checkout", action.Repository.Name))
if err := git.GitExec(filepath.Join(prjgit, action.Repository.Name), "fetch", "--depth", "1", "origin", config.Branch+":"+config.Branch); err != nil {
return fmt.Errorf("error fetching branch %s. ignoring as non-existent. err: %w", config.Branch, err) // no branch? so ignore repo here
}
id, err := git.GitBranchHead(filepath.Join(prjgit, action.Repository.Name), config.Branch)
2024-09-11 18:50:49 +02:00
common.PanicOnError(err)
2024-07-07 21:08:41 +02:00
for _, commitId := range action.Commits {
if commitId.Id == id {
common.PanicOnError(git.GitExec(filepath.Join(prjgit, action.Repository.Name), "fetch", "--depth", "1", "origin", id))
common.PanicOnError(git.GitExec(filepath.Join(prjgit, action.Repository.Name), "checkout", id))
common.PanicOnError(git.GitExec(prjgit, "commit", "-a", "-m", "Automatic update via push via Direct Workflow"))
common.PanicOnError(git.GitExec(prjgit, "push"))
2024-07-08 17:14:18 +02:00
return nil
2024-07-07 21:08:41 +02:00
}
}
2024-09-12 14:15:59 +02:00
h.StdLogger.Println("push of refs the configured branch", config.Branch, ". ignoring.")
2024-07-07 21:08:41 +02:00
return nil
}
2024-09-11 18:50:49 +02:00
func verifyProjectState(git *common.GitHandler, orgName string, config *common.AutogitConfig, configs []*common.AutogitConfig) (err error) {
defer func() {
e := recover()
if e != nil {
errCast, ok := e.(error)
if ok {
err = errCast
}
}
}()
2024-09-02 17:27:23 +02:00
org := common.Organization{
Username: orgName,
}
repo, err := gitea.CreateRepositoryIfNotExist(git, org, config.GitProjectName)
if err != nil {
return fmt.Errorf("Error fetching or creating '%s/%s' -- aborting verifyProjectState(). Err: %w", orgName, config.GitProjectName, err)
}
2024-09-11 18:50:49 +02:00
common.PanicOnError(git.GitExec("", "clone", "--depth", "1", repo.SSHURL, config.GitProjectName))
2024-09-04 14:04:13 +02:00
log.Println("getting submodule list")
2024-09-02 17:27:23 +02:00
sub, err := git.GitSubmoduleList(config.GitProjectName, "HEAD")
2024-09-11 18:50:49 +02:00
common.PanicOnError(err)
2024-09-02 17:27:23 +02:00
isGitUpdated := false
2024-09-10 16:21:01 +02:00
next_package:
2024-09-02 17:27:23 +02:00
for filename, commitId := range sub {
2024-09-10 16:21:01 +02:00
// ignore project gits
for _, c := range configs {
if c.GitProjectName == filename {
log.Println(" prjgit as package? ignoring project git:", filename)
continue next_package
}
}
2024-09-04 14:04:13 +02:00
log.Println(" verifying package:", filename, commitId, config.Branch)
2024-09-02 17:27:23 +02:00
commits, err := gitea.GetRecentCommits(orgName, filename, config.Branch, 10)
if err != nil {
2024-09-04 14:04:13 +02:00
// assumption that package does not exist, remove from project
2024-09-05 15:02:26 +02:00
// https://github.com/go-gitea/gitea/issues/31976
2024-09-04 14:04:13 +02:00
if err := git.GitExec(config.GitProjectName, "rm", filename); err != nil {
return fmt.Errorf("Failed to remove deleted submodule. Err: %w", err)
}
isGitUpdated = true
continue
2024-09-02 17:27:23 +02:00
}
2024-09-05 15:02:26 +02:00
// if err != nil {
// return fmt.Errorf("Failed to fetch recent commits for package: '%s'. Err: %w", filename, err)
// }
2024-09-02 17:27:23 +02:00
idx := 1000
for i, c := range commits {
if c.SHA == commitId {
idx = i
break
}
}
if idx == 0 {
// up-to-date
continue
} else if idx < len(commits) { // update
2024-09-11 18:50:49 +02:00
common.PanicOnError(git.GitExec(config.GitProjectName, "submodule", "update", "--init", "--depth", "1", "--checkout", filename))
common.PanicOnError(git.GitExec(filepath.Join(config.GitProjectName, filename), "fetch", "--depth", "1", "origin", commits[0].SHA))
common.PanicOnError(git.GitExec(filepath.Join(config.GitProjectName, filename), "checkout", commits[0].SHA))
2024-09-02 17:27:23 +02:00
isGitUpdated = true
} else {
// probably need `merge-base` or `rev-list` here instead, or the project updated already
return fmt.Errorf("Cannot find SHA of last matching update for package: '%s'. idx: %d", filename, idx)
}
}
2024-09-05 15:02:26 +02:00
// find all missing repositories, and add them
2024-09-05 15:28:08 +02:00
if debugMode {
log.Println("checking for missing repositories...")
}
2024-09-05 15:02:26 +02:00
repos, err := gitea.GetOrganizationRepositories(orgName)
if err != nil {
return err
}
2024-09-05 15:28:08 +02:00
if debugMode {
log.Println(" nRepos:", len(repos))
}
2024-09-10 16:21:01 +02:00
next_repo:
2024-09-05 15:02:26 +02:00
for _, r := range repos {
2024-09-05 15:28:08 +02:00
if debugMode {
log.Println(" -- checking", r.Name)
}
2024-09-05 15:02:26 +02:00
for _, c := range configs {
if c.Organization == orgName && c.GitProjectName == r.Name {
2024-09-05 15:28:08 +02:00
// ignore project gits
2024-09-12 14:15:59 +02:00
continue next_repo
2024-09-05 15:02:26 +02:00
}
}
2024-09-05 15:28:08 +02:00
for repo := range sub {
if repo == r.Name {
2024-09-12 14:15:59 +02:00
// not missing
2024-09-05 15:28:08 +02:00
continue next_repo
}
}
if debugMode {
log.Println(" -- checking repository:", r.Name)
}
2024-09-12 14:15:59 +02:00
if _, err := gitea.GetRecentCommits(orgName, r.Name, config.Branch, 1); err != nil {
2024-09-05 15:02:26 +02:00
// assumption that package does not exist, so not part of project
// https://github.com/go-gitea/gitea/issues/31976
2024-09-12 14:15:59 +02:00
continue
2024-09-05 15:02:26 +02:00
}
// add repository to git project
2024-09-12 14:15:59 +02:00
common.PanicOnError(git.GitExec(config.GitProjectName, "submodule", "--quiet", "add", "--depth", "1", r.SSHURL, r.Name))
2024-09-05 15:02:26 +02:00
if len(config.Branch) > 0 {
2024-09-12 14:15:59 +02:00
common.PanicOnError(git.GitExec(path.Join(config.GitProjectName, r.Name), "fetch", "--depth", "1", "origin", config.Branch+":"+config.Branch))
2024-09-11 18:50:49 +02:00
common.PanicOnError(git.GitExec(path.Join(config.GitProjectName, r.Name), "checkout", config.Branch))
2024-09-05 15:02:26 +02:00
}
isGitUpdated = true
}
2024-09-02 17:27:23 +02:00
if isGitUpdated {
2024-09-11 18:50:49 +02:00
common.PanicOnError(git.GitExec(config.GitProjectName, "commit", "-a", "-m", "Automatic update via push via Direct Workflow -- SYNC"))
common.PanicOnError(git.GitExec(config.GitProjectName, "push"))
2024-09-02 17:27:23 +02:00
}
2024-09-05 15:28:08 +02:00
if debugMode {
log.Println("Verification finished for ", orgName, ", config", config.GitProjectName)
}
2024-08-28 17:53:15 +02:00
return nil
2024-08-28 12:39:32 +02:00
}
var checkOnStart bool
2024-08-28 17:53:15 +02:00
var checkInterval time.Duration
2024-08-28 12:39:32 +02:00
2024-09-11 18:50:49 +02:00
func checkRepos() {
2024-09-04 14:04:13 +02:00
for org, configs := range configuredRepos {
for _, config := range configs {
2024-09-11 18:50:49 +02:00
if checkInterval > 0 {
sleepInterval := checkInterval - checkInterval/2 + time.Duration(rand.Int63n(int64(checkInterval)))
log.Println(" - sleep interval", sleepInterval, "until next check")
time.Sleep(sleepInterval)
}
2024-08-28 12:39:32 +02:00
2024-09-11 18:50:49 +02:00
log.Printf(" ++ starting verification, org: `%s` config: `%s`\n", org, config.GitProjectName)
2024-09-04 14:04:13 +02:00
git, err := common.CreateGitHandler(GitAuthor, GitEmail, AppName)
if err != nil {
log.Println("Faield to allocate GitHandler:", err)
return
}
2024-09-05 15:02:26 +02:00
if err := verifyProjectState(git, org, config, configs); err != nil {
2024-09-04 14:04:13 +02:00
log.Printf(" *** verification failed, org: `%s`, err: %#v\n", org, err)
}
2024-09-11 18:50:49 +02:00
log.Printf(" ++ verification complete, org: `%s` config: `%s`\n", org, config.GitProjectName)
2024-08-28 12:39:32 +02:00
}
}
}
2024-09-11 18:50:49 +02:00
func consistencyCheckProcess() {
if checkOnStart {
savedCheckInterval := checkInterval
checkInterval = 0
log.Println("== Startup consistency check begin...")
checkRepos()
log.Println("== Startup consistency check done...")
checkInterval = savedCheckInterval
}
for {
checkRepos()
}
}
2024-08-28 00:45:47 +02:00
var debugMode bool
2024-07-07 21:08:41 +02:00
func main() {
2024-09-04 14:04:13 +02:00
if err := common.RequireGiteaSecretToken(); err != nil {
log.Fatal(err)
}
if err := common.RequireRabbitSecrets(); err != nil {
log.Fatal(err)
}
2024-08-26 17:07:52 +02:00
workflowConfig := flag.String("config", "", "Repository and workflow definition file")
2024-08-30 17:05:57 +02:00
giteaHost := flag.String("gitea", "src.opensuse.org", "Gitea instance")
2024-08-28 00:45:47 +02:00
rabbitUrl := flag.String("url", "amqps://rabbit.opensuse.org", "URL for RabbitMQ instance")
flag.BoolVar(&debugMode, "debug", false, "Extra debugging information")
2024-08-28 12:39:32 +02:00
flag.BoolVar(&checkOnStart, "check-on-start", false, "Check all repositories for consistency on start, without delays")
checkIntervalHours := flag.Float64("check-interval", 5, "Check interval (+-random delay) for repositories for consitency, in hours")
2024-08-26 17:07:52 +02:00
flag.Parse()
2024-08-28 12:39:32 +02:00
checkInterval = time.Duration(*checkIntervalHours) * time.Hour
2024-08-28 00:45:47 +02:00
if len(*workflowConfig) == 0 {
log.Fatalln("No configuratio file specified. Aborting")
}
2024-08-26 17:07:52 +02:00
configs, err := common.ReadWorkflowConfigsFile(*workflowConfig)
if err != nil {
2024-09-02 17:56:00 +02:00
log.Fatal(err)
2024-08-26 17:07:52 +02:00
}
2024-09-04 14:04:13 +02:00
configuredRepos = make(map[string][]*common.AutogitConfig)
orgs := make([]string, 0, 1)
2024-08-28 00:45:47 +02:00
for _, c := range configs {
2024-09-04 14:04:13 +02:00
if slices.Contains(c.Workflows, "direct") {
2024-08-28 00:45:47 +02:00
if debugMode {
2024-08-28 17:53:15 +02:00
log.Printf(" + adding org: '%s', branch: '%s', prjgit: '%s'\n", c.Organization, c.Branch, c.GitProjectName)
2024-08-28 00:45:47 +02:00
}
2024-09-04 14:04:13 +02:00
configs := configuredRepos[c.Organization]
if configs == nil {
configs = make([]*common.AutogitConfig, 0, 1)
}
configs = append(configs, c)
configuredRepos[c.Organization] = configs
2024-08-28 00:45:47 +02:00
orgs = append(orgs, c.Organization)
}
}
2024-08-30 17:05:57 +02:00
gitea = common.AllocateGiteaTransport(*giteaHost)
2024-09-04 14:04:13 +02:00
go consistencyCheckProcess()
2024-08-30 17:05:57 +02:00
2024-07-08 17:14:18 +02:00
var defs common.ListenDefinitions
2024-09-04 14:04:13 +02:00
defs.GitAuthor = GitAuthor
2024-08-28 00:45:47 +02:00
defs.RabbitURL = *rabbitUrl
2024-07-09 15:05:49 +02:00
2024-08-28 00:45:47 +02:00
defs.Handlers = make(map[string]common.RequestProcessor)
2024-07-08 17:14:18 +02:00
defs.Handlers[common.RequestType_Push] = processPushAction
defs.Handlers[common.RequestType_Repository] = processRepositoryAction
2024-08-28 00:45:47 +02:00
log.Fatal(common.ProcessRabbitMQEvents(defs, orgs))
2024-07-07 21:08:41 +02:00
}