blob: 7faca86cdef94f5e459b27ebf0acf8a72eecb589 [file] [log] [blame]
Bob Badoura99ac622021-10-25 16:21:00 -07001// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package compliance
16
17import (
18 "fmt"
19 "io"
20 "io/fs"
Bob Badourc778e4c2022-03-22 13:05:19 -070021 "os"
Bob Badoura99ac622021-10-25 16:21:00 -070022 "strings"
23 "sync"
24
25 "android/soong/compliance/license_metadata_proto"
26
27 "google.golang.org/protobuf/encoding/prototext"
28)
29
30var (
31 // ConcurrentReaders is the size of the task pool for limiting resource usage e.g. open files.
32 ConcurrentReaders = 5
33)
34
Bob Badourc778e4c2022-03-22 13:05:19 -070035type globalFS struct{}
36
37func (s globalFS) Open(name string) (fs.File, error) {
38 return os.Open(name)
39}
40
41var FS globalFS
42
43// GetFS returns a filesystem for accessing files under the OUT_DIR environment variable.
44func GetFS(outDir string) fs.FS {
45 if len(outDir) > 0 {
46 return os.DirFS(outDir)
47 }
48 return os.DirFS(".")
49}
50
Bob Badoura99ac622021-10-25 16:21:00 -070051// result describes the outcome of reading and parsing a single license metadata file.
52type result struct {
53 // file identifies the path to the license metadata file
54 file string
55
56 // target contains the parsed metadata or nil if an error
57 target *TargetNode
58
Bob Badoura99ac622021-10-25 16:21:00 -070059 // err is nil unless an error occurs
60 err error
61}
62
63// receiver coordinates the tasks for reading and parsing license metadata files.
64type receiver struct {
Bob Badour103eb0f2022-01-10 13:50:57 -080065 // lg accumulates the read metadata and becomes the final resulting LicenseGraph.
Bob Badoura99ac622021-10-25 16:21:00 -070066 lg *LicenseGraph
67
68 // rootFS locates the root of the file system from which to read the files.
69 rootFS fs.FS
70
71 // stderr identifies the error output writer.
72 stderr io.Writer
73
74 // task provides a fixed-size task pool to limit concurrent open files etc.
75 task chan bool
76
77 // results returns one license metadata file result at a time.
78 results chan *result
79
80 // wg detects when done
81 wg sync.WaitGroup
82}
83
84// ReadLicenseGraph reads and parses `files` and their dependencies into a LicenseGraph.
85//
86// `files` become the root files of the graph for top-down walks of the graph.
87func ReadLicenseGraph(rootFS fs.FS, stderr io.Writer, files []string) (*LicenseGraph, error) {
88 if len(files) == 0 {
89 return nil, fmt.Errorf("no license metadata to analyze")
90 }
91 if ConcurrentReaders < 1 {
92 return nil, fmt.Errorf("need at least one task in pool")
93 }
94
95 lg := newLicenseGraph()
96 for _, f := range files {
Bob Badour63a281c2022-01-10 17:59:14 -080097 if strings.HasSuffix(f, "meta_lic") {
Bob Badoura99ac622021-10-25 16:21:00 -070098 lg.rootFiles = append(lg.rootFiles, f)
99 } else {
100 lg.rootFiles = append(lg.rootFiles, f+".meta_lic")
101 }
102 }
103
104 recv := &receiver{
105 lg: lg,
106 rootFS: rootFS,
107 stderr: stderr,
108 task: make(chan bool, ConcurrentReaders),
109 results: make(chan *result, ConcurrentReaders),
110 wg: sync.WaitGroup{},
111 }
112 for i := 0; i < ConcurrentReaders; i++ {
113 recv.task <- true
114 }
115
116 readFiles := func() {
117 lg.mu.Lock()
118 // identify the metadata files to schedule reading tasks for
119 for _, f := range lg.rootFiles {
120 lg.targets[f] = nil
121 }
122 lg.mu.Unlock()
123
124 // schedule tasks to read the files
125 for _, f := range lg.rootFiles {
126 readFile(recv, f)
127 }
128
129 // schedule a task to wait until finished and close the channel.
130 go func() {
131 recv.wg.Wait()
132 close(recv.task)
133 close(recv.results)
134 }()
135 }
136 go readFiles()
137
138 // tasks to read license metadata files are scheduled; read and process results from channel
139 var err error
140 for recv.results != nil {
141 select {
142 case r, ok := <-recv.results:
143 if ok {
144 // handle errors by nil'ing ls, setting err, and clobbering results channel
145 if r.err != nil {
146 err = r.err
147 fmt.Fprintf(recv.stderr, "%s\n", err.Error())
148 lg = nil
149 recv.results = nil
150 continue
151 }
152
153 // record the parsed metadata (guarded by mutex)
154 recv.lg.mu.Lock()
Bob Badour103eb0f2022-01-10 13:50:57 -0800155 lg.targets[r.target.name] = r.target
Bob Badoura99ac622021-10-25 16:21:00 -0700156 recv.lg.mu.Unlock()
157 } else {
158 // finished -- nil the results channel
159 recv.results = nil
160 }
161 }
162 }
163
Bob Badour103eb0f2022-01-10 13:50:57 -0800164 if lg != nil {
165 esize := 0
166 for _, tn := range lg.targets {
167 esize += len(tn.proto.Deps)
168 }
169 lg.edges = make(TargetEdgeList, 0, esize)
170 for _, tn := range lg.targets {
171 tn.licenseConditions = LicenseConditionSetFromNames(tn, tn.proto.LicenseConditions...)
172 err = addDependencies(lg, tn)
173 if err != nil {
174 return nil, fmt.Errorf("error indexing dependencies for %q: %w", tn.name, err)
175 }
176 tn.proto.Deps = []*license_metadata_proto.AnnotatedDependency{}
177 }
178 }
Bob Badoura99ac622021-10-25 16:21:00 -0700179 return lg, err
180
181}
182
183// targetNode contains the license metadata for a node in the license graph.
184type targetNode struct {
185 proto license_metadata_proto.LicenseMetadata
186
Bob Badour103eb0f2022-01-10 13:50:57 -0800187 // name is the path to the metadata file.
Bob Badoura99ac622021-10-25 16:21:00 -0700188 name string
Bob Badoura99ac622021-10-25 16:21:00 -0700189
Bob Badour103eb0f2022-01-10 13:50:57 -0800190 // lg is the license graph the node belongs to.
191 lg *LicenseGraph
Bob Badoura99ac622021-10-25 16:21:00 -0700192
Bob Badour103eb0f2022-01-10 13:50:57 -0800193 // edges identifies the dependencies of the target.
194 edges TargetEdgeList
Bob Badoura99ac622021-10-25 16:21:00 -0700195
Bob Badour103eb0f2022-01-10 13:50:57 -0800196 // licenseConditions identifies the set of license conditions originating at the target node.
197 licenseConditions LicenseConditionSet
198
199 // resolution identifies the set of conditions resolved by acting on the target node.
200 resolution LicenseConditionSet
Bob Badour085a2c22022-09-21 19:36:59 -0700201
202 // pure indicates whether to treat the node as a pure aggregate (no internal linkage)
203 pure bool
Bob Badoura99ac622021-10-25 16:21:00 -0700204}
205
206// addDependencies converts the proto AnnotatedDependencies into `edges`
Bob Badour103eb0f2022-01-10 13:50:57 -0800207func addDependencies(lg *LicenseGraph, tn *TargetNode) error {
Colin Cross35f79c32022-01-27 15:18:52 -0800208 tn.edges = make(TargetEdgeList, 0, len(tn.proto.Deps))
Bob Badour103eb0f2022-01-10 13:50:57 -0800209 for _, ad := range tn.proto.Deps {
Bob Badoura99ac622021-10-25 16:21:00 -0700210 dependency := ad.GetFile()
211 if len(dependency) == 0 {
212 return fmt.Errorf("missing dependency name")
213 }
Bob Badour103eb0f2022-01-10 13:50:57 -0800214 dtn, ok := lg.targets[dependency]
215 if !ok {
216 return fmt.Errorf("unknown dependency name %q", dependency)
217 }
218 if dtn == nil {
219 return fmt.Errorf("nil dependency for name %q", dependency)
220 }
Bob Badoura99ac622021-10-25 16:21:00 -0700221 annotations := newEdgeAnnotations()
222 for _, a := range ad.Annotations {
Bob Badour67d8ae32022-01-10 18:32:54 -0800223 // look up a common constant annotation string from a small map
224 // instead of creating 1000's of copies of the same 3 strings.
225 if ann, ok := RecognizedAnnotations[a]; ok {
Bob Badour5446a6f2022-01-10 18:44:59 -0800226 annotations.annotations[ann] = struct{}{}
Bob Badoura99ac622021-10-25 16:21:00 -0700227 }
Bob Badoura99ac622021-10-25 16:21:00 -0700228 }
Bob Badour103eb0f2022-01-10 13:50:57 -0800229 edge := &TargetEdge{tn, dtn, annotations}
230 lg.edges = append(lg.edges, edge)
231 tn.edges = append(tn.edges, edge)
Bob Badoura99ac622021-10-25 16:21:00 -0700232 }
233 return nil
234}
235
236// readFile is a task to read and parse a single license metadata file, and to schedule
237// additional tasks for reading and parsing dependencies as necessary.
238func readFile(recv *receiver, file string) {
239 recv.wg.Add(1)
240 <-recv.task
241 go func() {
242 f, err := recv.rootFS.Open(file)
243 if err != nil {
Bob Badour103eb0f2022-01-10 13:50:57 -0800244 recv.results <- &result{file, nil, fmt.Errorf("error opening license metadata %q: %w", file, err)}
Bob Badoura99ac622021-10-25 16:21:00 -0700245 return
246 }
247
248 // read the file
249 data, err := io.ReadAll(f)
250 if err != nil {
Bob Badour103eb0f2022-01-10 13:50:57 -0800251 recv.results <- &result{file, nil, fmt.Errorf("error reading license metadata %q: %w", file, err)}
Bob Badoura99ac622021-10-25 16:21:00 -0700252 return
253 }
Bob Badour103eb0f2022-01-10 13:50:57 -0800254 f.Close()
Bob Badoura99ac622021-10-25 16:21:00 -0700255
Bob Badour103eb0f2022-01-10 13:50:57 -0800256 tn := &TargetNode{lg: recv.lg, name: file}
Bob Badoura99ac622021-10-25 16:21:00 -0700257
258 err = prototext.Unmarshal(data, &tn.proto)
259 if err != nil {
Bob Badour103eb0f2022-01-10 13:50:57 -0800260 recv.results <- &result{file, nil, fmt.Errorf("error license metadata %q: %w", file, err)}
Bob Badoura99ac622021-10-25 16:21:00 -0700261 return
262 }
263
Bob Badoura99ac622021-10-25 16:21:00 -0700264 // send result for this file and release task before scheduling dependencies,
265 // but do not signal done to WaitGroup until dependencies are scheduled.
Bob Badour103eb0f2022-01-10 13:50:57 -0800266 recv.results <- &result{file, tn, nil}
Bob Badoura99ac622021-10-25 16:21:00 -0700267 recv.task <- true
268
269 // schedule tasks as necessary to read dependencies
Bob Badour103eb0f2022-01-10 13:50:57 -0800270 for _, ad := range tn.proto.Deps {
271 dependency := ad.GetFile()
Bob Badoura99ac622021-10-25 16:21:00 -0700272 // decide, signal and record whether to schedule task in critical section
273 recv.lg.mu.Lock()
Bob Badour103eb0f2022-01-10 13:50:57 -0800274 _, alreadyScheduled := recv.lg.targets[dependency]
Bob Badoura99ac622021-10-25 16:21:00 -0700275 if !alreadyScheduled {
Bob Badour103eb0f2022-01-10 13:50:57 -0800276 recv.lg.targets[dependency] = nil
Bob Badoura99ac622021-10-25 16:21:00 -0700277 }
278 recv.lg.mu.Unlock()
279 // schedule task to read dependency file outside critical section
280 if !alreadyScheduled {
Bob Badour103eb0f2022-01-10 13:50:57 -0800281 readFile(recv, dependency)
Bob Badoura99ac622021-10-25 16:21:00 -0700282 }
283 }
284
285 // signal task done after scheduling dependencies
286 recv.wg.Done()
287 }()
288}