builds_helper.go 1.64 KB
Newer Older
1 2 3 4 5 6 7 8
package commands

import (
	"gitlab.com/gitlab-org/gitlab-ci-multi-runner/common"
	"sync"
)

type buildsHelper struct {
Kamil Trzciński's avatar
Kamil Trzciński committed
9 10 11
	counts map[string]int
	builds []*common.Build
	lock   sync.Mutex
12 13
}

Kamil Trzciński's avatar
Kamil Trzciński committed
14 15 16
func (b *buildsHelper) acquire(runner *runnerAcquire) bool {
	b.lock.Lock()
	defer b.lock.Unlock()
17 18

	// Check number of builds
Kamil Trzciński's avatar
Kamil Trzciński committed
19
	count, _ := b.counts[runner.Token]
20 21
	if runner.Limit > 0 && count >= runner.Limit {
		// Too many builds
Kamil Trzciński's avatar
Kamil Trzciński committed
22
		return false
23 24 25
	}

	// Create a new build
Kamil Trzciński's avatar
Kamil Trzciński committed
26 27
	if b.counts == nil {
		b.counts = make(map[string]int)
28
	}
Kamil Trzciński's avatar
Kamil Trzciński committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
	b.counts[runner.Token]++
	return
}

func (b *buildsHelper) release(runner *runnerAcquire) bool {
	b.lock.Lock()
	defer b.lock.Unlock()

	_, ok := b.counts[runner.Token]
	if ok {
		b.counts[runner.Token]--
		return true
	}
	return false
}

func (b *buildsHelper) addBuild(build *common.Build) {
	b.lock.Lock()
	defer b.lock.Unlock()

	runners := make(map[int]bool)
	projectRunners := make(map[int]bool)

	for _, otherBuild := range b.builds {
		if otherBuild.Runner.Token != build.Runner.Token {
			continue
		}
		runners[otherBuild.RunnerID] = true

		if otherBuild.ProjectID != build.ProjectID {
			continue
		}
		projectRunners[otherBuild.ProjectRunnerID] = true
	}

	for {
		if !runners[build.RunnerID] {
			break
		}
		build.RunnerID++
	}

	for {
		if !projectRunners[build.ProjectRunnerID] {
			break
		}
		build.ProjectRunnerID++
	}

78 79 80 81
	b.builds = append(b.builds, build)
	return
}

Kamil Trzciński's avatar
Kamil Trzciński committed
82 83 84
func (b *buildsHelper) removeBuild(deleteBuild *common.Build) bool {
	b.lock.Lock()
	defer b.lock.Unlock()
85 86 87 88 89 90 91 92 93

	for idx, build := range b.builds {
		if build == deleteBuild {
			b.builds = append(b.builds[0:idx], b.builds[idx+1:]...)
			return true
		}
	}
	return false
}