summaryrefslogtreecommitdiff
path: root/execute.go
blob: 9f9e3e631b8664aab836cbe8193dca1cd0bb030b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
package main

import (
	"context"
	"log"
	"sync"
	"time"
)

type executionUnit struct {
	name  string
	check check
}

func execute(config config, state state) state {
	limiterCh := make(chan struct{}, config.CheckConcurrency)
	executionCh := make(chan executionUnit)
	resultCh := make(chan checkResult)

	go func() {
		for name, check := range config.Checks {
			executionCh <- executionUnit{name, check}
		}
		close(executionCh)
	}()

	var resultWg sync.WaitGroup
	resultWg.Add(1)

	go func() {
		for checkResult := range resultCh {
			state.update(checkResult)
		}
		resultWg.Done()
	}()

	var executionWg sync.WaitGroup
	executionWg.Add(len(config.Checks))

	for executionUnit := range executionCh {
		go func(name string, check check) {
			limiterCh <- struct{}{}
			defer func() {
				<-limiterCh
				executionWg.Done()
			}()

			ctx, cancel := context.WithTimeout(context.Background(),
				time.Duration(config.CheckTimeoutS)*time.Second)
			defer cancel()

			resultCh <- check.execute(ctx, name)
		}(executionUnit.name, executionUnit.check)
	}

	executionWg.Wait()
	log.Println("All checks completed!")
	close(resultCh)

	resultWg.Wait()
	log.Println("All results collected!")

	return state
}