summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/dockerhub/collect.go
blob: 211c1ea7cac07bc8d1dae48039186c485e9c79e7 (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
65
// SPDX-License-Identifier: GPL-3.0-or-later

package dockerhub

import (
	"fmt"
	"time"
)

func (dh *DockerHub) collect() (map[string]int64, error) {
	var (
		reposNum = len(dh.Repositories)
		ch       = make(chan *repository, reposNum)
		mx       = make(map[string]int64)
	)

	for _, name := range dh.Repositories {
		go dh.collectRepo(name, ch)
	}

	var (
		parsed  int
		pullSum int
	)

	for i := 0; i < reposNum; i++ {
		repo := <-ch
		if repo == nil {
			continue
		}
		if err := parseRepoTo(repo, mx); err != nil {
			dh.Errorf("error on parsing %s/%s : %v", repo.User, repo.Name, err)
			continue
		}
		pullSum += repo.PullCount
		parsed++
	}
	close(ch)

	if parsed == reposNum {
		mx["pull_sum"] = int64(pullSum)
	}

	return mx, nil
}

func (dh *DockerHub) collectRepo(repoName string, ch chan *repository) {
	repo, err := dh.client.getRepository(repoName)
	if err != nil {
		dh.Error(err)
	}
	ch <- repo
}

func parseRepoTo(repo *repository, mx map[string]int64) error {
	t, err := time.Parse(time.RFC3339Nano, repo.LastUpdated)
	if err != nil {
		return err
	}
	mx[fmt.Sprintf("last_updated_%s/%s", repo.User, repo.Name)] = int64(time.Since(t).Seconds())
	mx[fmt.Sprintf("star_count_%s/%s", repo.User, repo.Name)] = int64(repo.StarCount)
	mx[fmt.Sprintf("pull_count_%s/%s", repo.User, repo.Name)] = int64(repo.PullCount)
	mx[fmt.Sprintf("status_%s/%s", repo.User, repo.Name)] = int64(repo.Status)
	return nil
}