-
Notifications
You must be signed in to change notification settings - Fork 113
/
main.go
271 lines (241 loc) · 7.86 KB
/
main.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// Copyright 2022 Criticality Score Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"errors"
"flag"
"fmt"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/ossf/criticality_score/v2/cmd/criticality_score/inputiter"
"github.com/ossf/criticality_score/v2/internal/collector"
log "github.com/ossf/criticality_score/v2/internal/log"
"github.com/ossf/criticality_score/v2/internal/outfile"
"github.com/ossf/criticality_score/v2/internal/scorer"
"github.com/ossf/criticality_score/v2/internal/signalio"
"github.com/ossf/criticality_score/v2/internal/workerpool"
)
const defaultLogLevel = zapcore.InfoLevel
var (
gcpProjectFlag = flag.String("gcp-project-id", "", "the Google Cloud Project ID to use. Auto-detects by default.")
depsdevDisableFlag = flag.Bool("depsdev-disable", false, "disables the collection of signals from deps.dev.")
depsdevDatasetFlag = flag.String("depsdev-dataset", collector.DefaultGCPDatasetName, "the BigQuery dataset name to use.")
depsdevTTLFlag = flag.Int("depsdev-expiration", 0, "the default expiration (`hours`) to use for deps.dev tables. No expiration by default.")
scoringDisableFlag = flag.Bool("scoring-disable", false, "disables the generation of scores.")
scoringConfigFlag = flag.String("scoring-config", "", "path to a YAML file for configuring the scoring algorithm.")
scoringColumnNameFlag = flag.String("scoring-column", "", "manually specify the name for the column used to hold the score.")
workersFlag = flag.Int("workers", 1, "the total number of concurrent workers to use.")
versionFlag = flag.Bool("version", false, "display the version of this command.")
logLevel = defaultLogLevel
logEnv log.Env
formatType signalio.WriterType
)
// initFlags prepares any runtime flags, usage information and parses the flags.
func initFlags() {
flag.Var(&logLevel, "log", "set the `level` of logging.")
flag.TextVar(&logEnv, "log-env", log.DefaultEnv, "set logging `env`.")
flag.TextVar(&formatType, "format", signalio.WriterTypeText, "set the output format. Choices are text, json or csv.")
outfile.DefineFlags(flag.CommandLine, "out", "force", "append", "OUTFILE")
flag.Usage = func() {
cmdName := path.Base(os.Args[0])
w := flag.CommandLine.Output()
fmt.Fprintf(w, "Usage:\n %s [FLAGS]... {FILE|REPO...}\n\n", cmdName)
fmt.Fprintf(w, "Collects signals for a list of project repository urls.\n\n")
fmt.Fprintf(w, "FILE must be either a file or - to read from stdin. If FILE does not\n")
fmt.Fprintf(w, "exist it will be treated as a REPO.\n")
fmt.Fprintf(w, "Each REPO must be a project repository url.\n")
fmt.Fprintf(w, "\nFlags:\n")
flag.PrintDefaults()
}
flag.Parse()
// Handle the version flag immediately. It's similar to -help.
if *versionFlag {
printVersion()
os.Exit(0)
}
}
// getScorer prepares a Scorer based on the flags passed to the command.
//
// nil will be returned if scoring is disabled.
func getScorer(logger *zap.Logger) *scorer.Scorer {
if *scoringDisableFlag {
logger.Info("Scoring disabled")
return nil
}
if *scoringConfigFlag == "" {
logger.Info("Preparing default scorer")
return scorer.FromDefaultConfig()
}
// Prepare the scorer from the config file
logger = logger.With(
zap.String("filename", *scoringConfigFlag),
)
logger.Info("Preparing scorer from config")
cf, err := os.Open(*scoringConfigFlag)
if err != nil {
logger.With(
zap.Error(err),
).Error("Failed to open scoring config file")
os.Exit(2)
}
defer cf.Close()
s, err := scorer.FromConfig(scorer.NameFromFilepath(*scoringConfigFlag), cf)
if err != nil {
logger.With(
zap.Error(err),
).Error("Failed to initialize scorer")
os.Exit(2)
}
return s
}
func generateScoreColumnName(s *scorer.Scorer) string {
if s == nil {
return ""
}
if *scoringColumnNameFlag != "" {
return *scoringColumnNameFlag
}
return s.Name()
}
func main() {
initFlags()
logger, err := log.NewLogger(logEnv, logLevel)
if err != nil {
panic(err)
}
defer logger.Sync()
// Prepare the scorer, if it is enabled.
s := getScorer(logger)
scoreColumnName := generateScoreColumnName(s)
// Complete the validation of args
if flag.NArg() == 0 {
logger.Error("An input file or at least one repo must be specified.")
os.Exit(2)
}
ctx := context.Background()
// Bump the # idle conns per host
http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = *workersFlag * 5
opts := []collector.Option{
collector.EnableAllSources(),
collector.GCPProject(*gcpProjectFlag),
collector.GCPDatasetName(*depsdevDatasetFlag),
collector.GCPDatasetTTL(time.Hour * time.Duration(*depsdevTTLFlag)),
}
if *depsdevDisableFlag {
opts = append(opts, collector.DisableSource(collector.SourceTypeDepsDev))
}
c, err := collector.New(ctx, logger, opts...)
if err != nil {
logger.With(
zap.Error(err),
).Error("Failed to create collector")
os.Exit(2)
}
// Prepare the input for reading
iter, err := inputiter.New(flag.Args())
if err != nil {
logger.With(
zap.Error(err),
).Error("Failed to prepare input")
os.Exit(2)
}
defer iter.Close()
// Open the out-file for writing
w, err := outfile.Open(context.Background())
if err != nil {
logger.With(
zap.Error(err),
).Error("Failed to open file for output")
os.Exit(2)
}
defer w.Close()
// Prepare the output writer
extras := []string{}
if s != nil {
extras = append(extras, scoreColumnName)
}
out := formatType.New(w, c.EmptySets(), extras...)
// Start the workers that process a channel of repo urls.
repos := make(chan *url.URL)
wait := workerpool.WorkerPool(*workersFlag, func(worker int) {
innerLogger := logger.With(zap.Int("worker", worker))
for u := range repos {
l := innerLogger.With(zap.String("url", u.String()))
ss, err := c.Collect(ctx, u, "")
if err != nil {
if errors.Is(err, collector.ErrUncollectableRepo) {
l.With(
zap.Error(err),
).Warn("Repo cannot be collected")
return
}
l.With(
zap.Error(err),
).Error("Failed to collect signals for repo")
os.Exit(1) // TODO: pass up the error
}
// If scoring is enabled, prepare the extra data to be output.
extras := []signalio.Field{}
if s != nil {
f := signalio.Field{
Key: scoreColumnName,
Value: fmt.Sprintf("%.5f", s.Score(ss)),
}
extras = append(extras, f)
}
// Write the signals to storage.
if err := out.WriteSignals(ss, extras...); err != nil {
l.With(
zap.Error(err),
).Error("Failed to write signal set")
os.Exit(1) // TODO: pass up the error
}
}
})
// Read in each repo from the input
for iter.Next() {
line := iter.Item()
u, err := url.Parse(strings.TrimSpace(line))
if err != nil {
logger.With(
zap.String("url", line),
zap.Error(err),
).Error("Failed to parse project url")
os.Exit(1) // TODO: add a flag to continue or abort on failure
}
logger.With(
zap.String("url", u.String()),
).Debug("Parsed project url")
// Send the url to the workers
repos <- u
}
if err := iter.Err(); err != nil {
logger.With(
zap.Error(err),
).Error("Failed while reading input")
os.Exit(2)
}
// Close the repos channel to indicate that there is no more input.
close(repos)
// Wait until all the workers have finished.
wait()
// TODO: track metrics as we are running to measure coverage of data
}