forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 1
/
github.go
255 lines (210 loc) · 6.71 KB
/
github.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package github
import (
"context"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/google/go-github/v32/github"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/selfstat"
"golang.org/x/oauth2"
)
// GitHub - plugin main structure
type GitHub struct {
Repositories []string `toml:"repositories"`
AccessToken string `toml:"access_token"`
AdditionalFields []string `toml:"additional_fields"`
EnterpriseBaseURL string `toml:"enterprise_base_url"`
HTTPTimeout internal.Duration `toml:"http_timeout"`
githubClient *github.Client
obfuscatedToken string
RateLimit selfstat.Stat
RateLimitErrors selfstat.Stat
RateRemaining selfstat.Stat
}
const sampleConfig = `
## List of repositories to monitor.
repositories = [
"influxdata/telegraf",
"influxdata/influxdb"
]
## Github API access token. Unauthenticated requests are limited to 60 per hour.
# access_token = ""
## Github API enterprise url. Github Enterprise accounts must specify their base url.
# enterprise_base_url = ""
## Timeout for HTTP requests.
# http_timeout = "5s"
## List of additional fields to query.
## NOTE: Getting those fields might involve issuing additional API-calls, so please
## make sure you do not exceed the rate-limit of GitHub.
##
## Available fields are:
## - pull-requests -- number of open and closed pull requests (2 API-calls per repository)
# additional_fields = []
`
// SampleConfig returns sample configuration for this plugin.
func (g *GitHub) SampleConfig() string {
return sampleConfig
}
// Description returns the plugin description.
func (g *GitHub) Description() string {
return "Gather repository information from GitHub hosted repositories."
}
// Create GitHub Client
func (g *GitHub) createGitHubClient(ctx context.Context) (*github.Client, error) {
httpClient := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
},
Timeout: g.HTTPTimeout.Duration,
}
g.obfuscatedToken = "Unauthenticated"
if g.AccessToken != "" {
tokenSource := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: g.AccessToken},
)
oauthClient := oauth2.NewClient(ctx, tokenSource)
_ = context.WithValue(ctx, oauth2.HTTPClient, oauthClient)
g.obfuscatedToken = g.AccessToken[0:4] + "..." + g.AccessToken[len(g.AccessToken)-3:]
return g.newGithubClient(oauthClient)
}
return g.newGithubClient(httpClient)
}
func (g *GitHub) newGithubClient(httpClient *http.Client) (*github.Client, error) {
if g.EnterpriseBaseURL != "" {
return github.NewEnterpriseClient(g.EnterpriseBaseURL, "", httpClient)
}
return github.NewClient(httpClient), nil
}
// Gather GitHub Metrics
func (g *GitHub) Gather(acc telegraf.Accumulator) error {
ctx := context.Background()
if g.githubClient == nil {
githubClient, err := g.createGitHubClient(ctx)
if err != nil {
return err
}
g.githubClient = githubClient
tokenTags := map[string]string{
"access_token": g.obfuscatedToken,
}
g.RateLimitErrors = selfstat.Register("github", "rate_limit_blocks", tokenTags)
g.RateLimit = selfstat.Register("github", "rate_limit_limit", tokenTags)
g.RateRemaining = selfstat.Register("github", "rate_limit_remaining", tokenTags)
}
var wg sync.WaitGroup
wg.Add(len(g.Repositories))
for _, repository := range g.Repositories {
go func(repositoryName string, acc telegraf.Accumulator) {
defer wg.Done()
owner, repository, err := splitRepositoryName(repositoryName)
if err != nil {
acc.AddError(err)
return
}
repositoryInfo, response, err := g.githubClient.Repositories.Get(ctx, owner, repository)
g.handleRateLimit(response, err)
if err != nil {
acc.AddError(err)
return
}
now := time.Now()
tags := getTags(repositoryInfo)
fields := getFields(repositoryInfo)
for _, field := range g.AdditionalFields {
addFields := make(map[string]interface{})
switch field {
case "pull-requests":
// Pull request properties
addFields, err = g.getPullRequestFields(ctx, owner, repository)
if err != nil {
acc.AddError(err)
continue
}
default:
acc.AddError(fmt.Errorf("unknown additional field %q", field))
continue
}
for k, v := range addFields {
fields[k] = v
}
}
acc.AddFields("github_repository", fields, tags, now)
}(repository, acc)
}
wg.Wait()
return nil
}
func (g *GitHub) handleRateLimit(response *github.Response, err error) {
if err == nil {
g.RateLimit.Set(int64(response.Rate.Limit))
g.RateRemaining.Set(int64(response.Rate.Remaining))
} else if _, ok := err.(*github.RateLimitError); ok {
g.RateLimitErrors.Incr(1)
}
}
func splitRepositoryName(repositoryName string) (string, string, error) {
splits := strings.SplitN(repositoryName, "/", 2)
if len(splits) != 2 {
return "", "", fmt.Errorf("%v is not of format 'owner/repository'", repositoryName)
}
return splits[0], splits[1], nil
}
func getLicense(rI *github.Repository) string {
if licenseName := rI.GetLicense().GetName(); licenseName != "" {
return licenseName
}
return "None"
}
func getTags(repositoryInfo *github.Repository) map[string]string {
return map[string]string{
"owner": repositoryInfo.GetOwner().GetLogin(),
"name": repositoryInfo.GetName(),
"language": repositoryInfo.GetLanguage(),
"license": getLicense(repositoryInfo),
}
}
func getFields(repositoryInfo *github.Repository) map[string]interface{} {
return map[string]interface{}{
"stars": repositoryInfo.GetStargazersCount(),
"subscribers": repositoryInfo.GetSubscribersCount(),
"watchers": repositoryInfo.GetWatchersCount(),
"networks": repositoryInfo.GetNetworkCount(),
"forks": repositoryInfo.GetForksCount(),
"open_issues": repositoryInfo.GetOpenIssuesCount(),
"size": repositoryInfo.GetSize(),
}
}
func (g *GitHub) getPullRequestFields(ctx context.Context, owner, repo string) (map[string]interface{}, error) {
options := github.SearchOptions{
TextMatch: false,
ListOptions: github.ListOptions{
PerPage: 100,
Page: 1,
},
}
classes := []string{"open", "closed"}
fields := make(map[string]interface{})
for _, class := range classes {
q := fmt.Sprintf("repo:%s/%s is:pr is:%s", owner, repo, class)
searchResult, response, err := g.githubClient.Search.Issues(ctx, q, &options)
g.handleRateLimit(response, err)
if err != nil {
return fields, err
}
f := fmt.Sprintf("%s_pull_requests", class)
fields[f] = searchResult.GetTotal()
}
return fields, nil
}
func init() {
inputs.Add("github", func() telegraf.Input {
return &GitHub{
HTTPTimeout: internal.Duration{Duration: time.Second * 5},
}
})
}