blob: 8f9496d388ca5ac29e05c27f89af10b87241c74d [file] [log] [blame]
Jeff Gastonf1fd45e2017-08-09 18:25:28 -07001// Copyright 2017 Google Inc. All rights reserved.
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 finder
16
17import (
18 "bufio"
19 "bytes"
20 "encoding/json"
21 "fmt"
22 "io"
23 "os"
24 "path/filepath"
25 "runtime"
26 "sort"
27 "strings"
28 "sync"
29 "sync/atomic"
30 "time"
31
32 "android/soong/fs"
33 "errors"
34)
35
36// This file provides a Finder struct that can quickly search for files satisfying
37// certain criteria.
38// This Finder gets its speed partially from parallelism and partially from caching.
39// If a Stat call returns the same result as last time, then it means Finder
40// can skip the ReadDir call for that dir.
41
42// The primary data structure used by the finder is the field Finder.nodes ,
43// which is a tree of nodes of type *pathMap .
44// Each node represents a directory on disk, along with its stats, subdirectories,
45// and contained files.
46
47// The common use case for the Finder is that the caller creates a Finder and gives
48// it the same query that was given to it in the previous execution.
49// In this situation, the major events that take place are:
50// 1. The Finder begins to load its db
51// 2. The Finder begins to stat the directories mentioned in its db (using multiple threads)
52// Calling Stat on each of these directories is generally a large fraction of the total time
53// 3. The Finder begins to construct a separate tree of nodes in each of its threads
54// 4. The Finder merges the individual node trees into the main node tree
55// 5. The Finder may call ReadDir a few times if there are a few directories that are out-of-date
56// These ReadDir calls might prompt additional Stat calls, etc
57// 6. The Finder waits for all loading to complete
58// 7. The Finder searches the cache for files matching the user's query (using multiple threads)
59
60// These are the invariants regarding concurrency:
61// 1. The public methods of Finder are threadsafe.
62// The public methods are only performance-optimized for one caller at a time, however.
63// For the moment, multiple concurrent callers shouldn't expect any better performance than
64// multiple serial callers.
65// 2. While building the node tree, only one thread may ever access the <children> collection of a
66// *pathMap at once.
67// a) The thread that accesses the <children> collection is the thread that discovers the
68// children (by reading them from the cache or by having received a response to ReadDir).
69// 1) Consequently, the thread that discovers the children also spawns requests to stat
70// subdirs.
71// b) Consequently, while building the node tree, no thread may do a lookup of its
72// *pathMap via filepath because another thread may be adding children to the
73// <children> collection of an ancestor node. Additionally, in rare cases, another thread
74// may be removing children from an ancestor node if the children were only discovered to
75// be irrelevant after calling ReadDir (which happens if a prune-file was just added).
76// 3. No query will begin to be serviced until all loading (both reading the db
77// and scanning the filesystem) is complete.
78// Tests indicate that it only takes about 10% as long to search the in-memory cache as to
79// generate it, making this not a huge loss in performance.
80// 4. The parsing of the db and the initial setup of the pathMap tree must complete before
81// beginning to call listDirSync (because listDirSync can create new entries in the pathMap)
82
83// see cmd/finder.go or finder_test.go for usage examples
84
85// Update versionString whenever making a backwards-incompatible change to the cache file format
86const versionString = "Android finder version 1"
87
88// a CacheParams specifies which files and directories the user wishes be scanned and
89// potentially added to the cache
90type CacheParams struct {
91 // WorkingDirectory is used as a base for any relative file paths given to the Finder
92 WorkingDirectory string
93
94 // RootDirs are the root directories used to initiate the search
95 RootDirs []string
96
97 // ExcludeDirs are directory names that if encountered are removed from the search
98 ExcludeDirs []string
99
100 // PruneFiles are file names that if encountered prune their entire directory
101 // (including siblings)
102 PruneFiles []string
103
104 // IncludeFiles are file names to include as matches
105 IncludeFiles []string
106}
107
108// a cacheConfig stores the inputs that determine what should be included in the cache
109type cacheConfig struct {
110 CacheParams
111
112 // FilesystemView is a unique identifier telling which parts of which file systems
113 // are readable by the Finder. In practice its value is essentially username@hostname.
114 // FilesystemView is set to ensure that a cache file copied to another host or
115 // found by another user doesn't inadvertently get reused.
116 FilesystemView string
117}
118
119func (p *cacheConfig) Dump() ([]byte, error) {
120 bytes, err := json.Marshal(p)
121 return bytes, err
122}
123
124// a cacheMetadata stores version information about the cache
125type cacheMetadata struct {
126 // The Version enables the Finder to determine whether it can even parse the file
127 // If the version changes, the entire cache file must be regenerated
128 Version string
129
130 // The CacheParams enables the Finder to determine whether the parameters match
131 // If the CacheParams change, the Finder can choose how much of the cache file to reuse
132 // (although in practice, the Finder will probably choose to ignore the entire file anyway)
133 Config cacheConfig
134}
135
136type Logger interface {
137 Output(calldepth int, s string) error
138}
139
140// the Finder is the main struct that callers will want to use
141type Finder struct {
142 // configuration
143 DbPath string
144 numDbLoadingThreads int
145 numSearchingThreads int
146 cacheMetadata cacheMetadata
147 logger Logger
148 filesystem fs.FileSystem
149
150 // temporary state
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700151 threadPool *threadPool
152 mutex sync.Mutex
153 fsErrs []fsErr
154 errlock sync.Mutex
155 shutdownWaitgroup sync.WaitGroup
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700156
157 // non-temporary state
158 modifiedFlag int32
159 nodes pathMap
160}
161
162// New creates a new Finder for use
163func New(cacheParams CacheParams, filesystem fs.FileSystem,
Jeff Gastonb629e182017-08-14 16:49:18 -0700164 logger Logger, dbPath string) (f *Finder, err error) {
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700165
166 numThreads := runtime.NumCPU() * 2
167 numDbLoadingThreads := numThreads
168 numSearchingThreads := numThreads
169
170 metadata := cacheMetadata{
171 Version: versionString,
172 Config: cacheConfig{
173 CacheParams: cacheParams,
174 FilesystemView: filesystem.ViewId(),
175 },
176 }
177
Jeff Gastonb629e182017-08-14 16:49:18 -0700178 f = &Finder{
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700179 numDbLoadingThreads: numDbLoadingThreads,
180 numSearchingThreads: numSearchingThreads,
181 cacheMetadata: metadata,
182 logger: logger,
183 filesystem: filesystem,
184
185 nodes: *newPathMap("/"),
186 DbPath: dbPath,
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700187
188 shutdownWaitgroup: sync.WaitGroup{},
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700189 }
190
Jeff Gastonb629e182017-08-14 16:49:18 -0700191 f.loadFromFilesystem()
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700192
Jeff Gastonb629e182017-08-14 16:49:18 -0700193 // check for any filesystem errors
194 err = f.getErr()
195 if err != nil {
196 return nil, err
197 }
198
199 // confirm that every path mentioned in the CacheConfig exists
200 for _, path := range cacheParams.RootDirs {
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700201 if !filepath.IsAbs(path) {
202 path = filepath.Join(f.cacheMetadata.Config.WorkingDirectory, path)
203 }
Jeff Gastonb629e182017-08-14 16:49:18 -0700204 node := f.nodes.GetNode(filepath.Clean(path), false)
205 if node == nil || node.ModTime == 0 {
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700206 return nil, fmt.Errorf("path %v was specified to be included in the cache but does not exist\n", path)
Jeff Gastonb629e182017-08-14 16:49:18 -0700207 }
208 }
209
210 return f, nil
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700211}
212
213// FindNamed searches for every cached file
214func (f *Finder) FindAll() []string {
215 return f.FindAt("/")
216}
217
218// FindNamed searches for every cached file under <rootDir>
219func (f *Finder) FindAt(rootDir string) []string {
220 filter := func(entries DirEntries) (dirNames []string, fileNames []string) {
221 return entries.DirNames, entries.FileNames
222 }
223 return f.FindMatching(rootDir, filter)
224}
225
226// FindNamed searches for every cached file named <fileName>
227func (f *Finder) FindNamed(fileName string) []string {
228 return f.FindNamedAt("/", fileName)
229}
230
231// FindNamedAt searches under <rootPath> for every file named <fileName>
232// The reason a caller might use FindNamedAt instead of FindNamed is if they want
233// to limit their search to a subset of the cache
234func (f *Finder) FindNamedAt(rootPath string, fileName string) []string {
235 filter := func(entries DirEntries) (dirNames []string, fileNames []string) {
236 matches := []string{}
237 for _, foundName := range entries.FileNames {
238 if foundName == fileName {
239 matches = append(matches, foundName)
240 }
241 }
242 return entries.DirNames, matches
243
244 }
245 return f.FindMatching(rootPath, filter)
246}
247
248// FindFirstNamed searches for every file named <fileName>
249// Whenever it finds a match, it stops search subdirectories
250func (f *Finder) FindFirstNamed(fileName string) []string {
251 return f.FindFirstNamedAt("/", fileName)
252}
253
254// FindFirstNamedAt searches for every file named <fileName>
255// Whenever it finds a match, it stops search subdirectories
256func (f *Finder) FindFirstNamedAt(rootPath string, fileName string) []string {
257 filter := func(entries DirEntries) (dirNames []string, fileNames []string) {
258 matches := []string{}
259 for _, foundName := range entries.FileNames {
260 if foundName == fileName {
261 matches = append(matches, foundName)
262 }
263 }
264
265 if len(matches) > 0 {
266 return []string{}, matches
267 }
268 return entries.DirNames, matches
269 }
270 return f.FindMatching(rootPath, filter)
271}
272
273// FindMatching is the most general exported function for searching for files in the cache
274// The WalkFunc will be invoked repeatedly and is expected to modify the provided DirEntries
275// in place, removing file paths and directories as desired.
276// WalkFunc will be invoked potentially many times in parallel, and must be threadsafe.
277func (f *Finder) FindMatching(rootPath string, filter WalkFunc) []string {
278 // set up some parameters
279 scanStart := time.Now()
280 var isRel bool
281 workingDir := f.cacheMetadata.Config.WorkingDirectory
282
283 isRel = !filepath.IsAbs(rootPath)
284 if isRel {
285 rootPath = filepath.Join(workingDir, rootPath)
286 }
287
288 rootPath = filepath.Clean(rootPath)
289
290 // ensure nothing else is using the Finder
291 f.verbosef("FindMatching waiting for finder to be idle\n")
292 f.lock()
293 defer f.unlock()
294
295 node := f.nodes.GetNode(rootPath, false)
296 if node == nil {
297 f.verbosef("No data for path %v ; apparently not included in cache params: %v\n",
298 rootPath, f.cacheMetadata.Config.CacheParams)
299 // path is not found; don't do a search
300 return []string{}
301 }
302
303 // search for matching files
304 f.verbosef("Finder finding %v using cache\n", rootPath)
305 results := f.findInCacheMultithreaded(node, filter, f.numSearchingThreads)
306
307 // format and return results
308 if isRel {
309 for i := 0; i < len(results); i++ {
310 results[i] = strings.Replace(results[i], workingDir+"/", "", 1)
311 }
312 }
313 sort.Strings(results)
314 f.verbosef("Found %v files under %v in %v using cache\n",
315 len(results), rootPath, time.Since(scanStart))
316 return results
317}
318
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700319// Shutdown declares that the finder is no longer needed and waits for its cleanup to complete
320// Currently, that only entails waiting for the database dump to complete.
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700321func (f *Finder) Shutdown() {
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700322 f.waitForDbDump()
323}
324
325// End of public api
326
327func (f *Finder) goDumpDb() {
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700328 if f.wasModified() {
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700329 f.shutdownWaitgroup.Add(1)
330 go func() {
331 err := f.dumpDb()
332 if err != nil {
333 f.verbosef("%v\n", err)
334 }
335 f.shutdownWaitgroup.Done()
336 }()
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700337 } else {
338 f.verbosef("Skipping dumping unmodified db\n")
339 }
340}
341
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700342func (f *Finder) waitForDbDump() {
343 f.shutdownWaitgroup.Wait()
344}
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700345
346// joinCleanPaths is like filepath.Join but is faster because
347// joinCleanPaths doesn't have to support paths ending in "/" or containing ".."
348func joinCleanPaths(base string, leaf string) string {
349 if base == "" {
350 return leaf
351 }
352 if base == "/" {
353 return base + leaf
354 }
355 if leaf == "" {
356 return base
357 }
358 return base + "/" + leaf
359}
360
361func (f *Finder) verbosef(format string, args ...interface{}) {
362 f.logger.Output(2, fmt.Sprintf(format, args...))
363}
364
365// loadFromFilesystem populates the in-memory cache based on the contents of the filesystem
366func (f *Finder) loadFromFilesystem() {
367 f.threadPool = newThreadPool(f.numDbLoadingThreads)
368
369 err := f.startFromExternalCache()
370 if err != nil {
371 f.startWithoutExternalCache()
372 }
373
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700374 f.goDumpDb()
375
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700376 f.threadPool = nil
377}
378
379func (f *Finder) startFind(path string) {
380 if !filepath.IsAbs(path) {
381 path = filepath.Join(f.cacheMetadata.Config.WorkingDirectory, path)
382 }
383 node := f.nodes.GetNode(path, true)
384 f.statDirAsync(node)
385}
386
387func (f *Finder) lock() {
388 f.mutex.Lock()
389}
390
391func (f *Finder) unlock() {
392 f.mutex.Unlock()
393}
394
395// a statResponse is the relevant portion of the response from the filesystem to a Stat call
396type statResponse struct {
397 ModTime int64
398 Inode uint64
399 Device uint64
400}
401
402// a pathAndStats stores a path and its stats
403type pathAndStats struct {
404 statResponse
405
406 Path string
407}
408
409// a dirFullInfo stores all of the relevant information we know about a directory
410type dirFullInfo struct {
411 pathAndStats
412
413 FileNames []string
414}
415
416// a PersistedDirInfo is the information about a dir that we save to our cache on disk
417type PersistedDirInfo struct {
418 // These field names are short because they are repeated many times in the output json file
419 P string // path
420 T int64 // modification time
421 I uint64 // inode number
422 F []string // relevant filenames contained
423}
424
425// a PersistedDirs is the information that we persist for a group of dirs
426type PersistedDirs struct {
427 // the device on which each directory is stored
428 Device uint64
429 // the common root path to which all contained dirs are relative
430 Root string
431 // the directories themselves
432 Dirs []PersistedDirInfo
433}
434
435// a CacheEntry is the smallest unit that can be read and parsed from the cache (on disk) at a time
436type CacheEntry []PersistedDirs
437
438// a DirEntries lists the files and directories contained directly within a specific directory
439type DirEntries struct {
440 Path string
441
442 // elements of DirNames are just the dir names; they don't include any '/' character
443 DirNames []string
444 // elements of FileNames are just the file names; they don't include '/' character
445 FileNames []string
446}
447
448// a WalkFunc is the type that is passed into various Find functions for determining which
449// directories the caller wishes be walked. The WalkFunc is expected to decide which
450// directories to walk and which files to consider as matches to the original query.
451type WalkFunc func(DirEntries) (dirs []string, files []string)
452
453// a mapNode stores the relevant stats about a directory to be stored in a pathMap
454type mapNode struct {
455 statResponse
456 FileNames []string
457}
458
459// a pathMap implements the directory tree structure of nodes
460type pathMap struct {
461 mapNode
462
463 path string
464
465 children map[string]*pathMap
466
467 // number of descendent nodes, including self
468 approximateNumDescendents int
469}
470
471func newPathMap(path string) *pathMap {
472 result := &pathMap{path: path, children: make(map[string]*pathMap, 4),
473 approximateNumDescendents: 1}
474 return result
475}
476
477// GetNode returns the node at <path>
478func (m *pathMap) GetNode(path string, createIfNotFound bool) *pathMap {
479 if len(path) > 0 && path[0] == '/' {
480 path = path[1:]
481 }
482
483 node := m
484 for {
485 if path == "" {
486 return node
487 }
488
489 index := strings.Index(path, "/")
490 var firstComponent string
491 if index >= 0 {
492 firstComponent = path[:index]
493 path = path[index+1:]
494 } else {
495 firstComponent = path
496 path = ""
497 }
498
499 child, found := node.children[firstComponent]
500
501 if !found {
502 if createIfNotFound {
503 child = node.newChild(firstComponent)
504 } else {
505 return nil
506 }
507 }
508
509 node = child
510 }
511}
512
513func (m *pathMap) newChild(name string) (child *pathMap) {
514 path := joinCleanPaths(m.path, name)
515 newChild := newPathMap(path)
516 m.children[name] = newChild
517
518 return m.children[name]
519}
520
521func (m *pathMap) UpdateNumDescendents() int {
522 count := 1
523 for _, child := range m.children {
524 count += child.approximateNumDescendents
525 }
526 m.approximateNumDescendents = count
527 return count
528}
529
530func (m *pathMap) UpdateNumDescendentsRecursive() {
531 for _, child := range m.children {
532 child.UpdateNumDescendentsRecursive()
533 }
534 m.UpdateNumDescendents()
535}
536
537func (m *pathMap) MergeIn(other *pathMap) {
538 for key, theirs := range other.children {
539 ours, found := m.children[key]
540 if found {
541 ours.MergeIn(theirs)
542 } else {
543 m.children[key] = theirs
544 }
545 }
546 if other.ModTime != 0 {
547 m.mapNode = other.mapNode
548 }
549 m.UpdateNumDescendents()
550}
551
552func (m *pathMap) DumpAll() []dirFullInfo {
553 results := []dirFullInfo{}
554 m.dumpInto("", &results)
555 return results
556}
557
558func (m *pathMap) dumpInto(path string, results *[]dirFullInfo) {
559 *results = append(*results,
560 dirFullInfo{
561 pathAndStats{statResponse: m.statResponse, Path: path},
562 m.FileNames},
563 )
564 for key, child := range m.children {
565 childPath := joinCleanPaths(path, key)
566 if len(childPath) == 0 || childPath[0] != '/' {
567 childPath = "/" + childPath
568 }
569 child.dumpInto(childPath, results)
570 }
571}
572
573// a semaphore can be locked by up to <capacity> callers at once
574type semaphore struct {
575 pool chan bool
576}
577
578func newSemaphore(capacity int) *semaphore {
579 return &semaphore{pool: make(chan bool, capacity)}
580}
581
582func (l *semaphore) Lock() {
583 l.pool <- true
584}
585
586func (l *semaphore) Unlock() {
587 <-l.pool
588}
589
590// A threadPool runs goroutines and supports throttling and waiting.
591// Without throttling, Go may exhaust the maximum number of various resources, such as
592// threads or file descriptors, and crash the program.
593type threadPool struct {
594 receivedRequests sync.WaitGroup
595 activeRequests semaphore
596}
597
598func newThreadPool(maxNumConcurrentThreads int) *threadPool {
599 return &threadPool{
600 receivedRequests: sync.WaitGroup{},
601 activeRequests: *newSemaphore(maxNumConcurrentThreads),
602 }
603}
604
605// Run requests to run the given function in its own goroutine
606func (p *threadPool) Run(function func()) {
607 p.receivedRequests.Add(1)
608 // If Run() was called from within a goroutine spawned by this threadPool,
609 // then we may need to return from Run() before having capacity to actually
610 // run <function>.
611 //
612 // It's possible that the body of <function> contains a statement (such as a syscall)
613 // that will cause Go to pin it to a thread, or will contain a statement that uses
614 // another resource that is in short supply (such as a file descriptor), so we can't
615 // actually run <function> until we have capacity.
616 //
617 // However, the semaphore used for synchronization is implemented via a channel and
618 // shouldn't require a new thread for each access.
619 go func() {
620 p.activeRequests.Lock()
621 function()
622 p.activeRequests.Unlock()
623 p.receivedRequests.Done()
624 }()
625}
626
627// Wait waits until all goroutines are done, just like sync.WaitGroup's Wait
628func (p *threadPool) Wait() {
629 p.receivedRequests.Wait()
630}
631
Jeff Gastonb629e182017-08-14 16:49:18 -0700632type fsErr struct {
633 path string
634 err error
635}
636
637func (e fsErr) String() string {
638 return e.path + ": " + e.err.Error()
639}
640
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700641func (f *Finder) serializeCacheEntry(dirInfos []dirFullInfo) ([]byte, error) {
642 // group each dirFullInfo by its Device, to avoid having to repeat it in the output
643 dirsByDevice := map[uint64][]PersistedDirInfo{}
644 for _, entry := range dirInfos {
645 _, found := dirsByDevice[entry.Device]
646 if !found {
647 dirsByDevice[entry.Device] = []PersistedDirInfo{}
648 }
649 dirsByDevice[entry.Device] = append(dirsByDevice[entry.Device],
650 PersistedDirInfo{P: entry.Path, T: entry.ModTime, I: entry.Inode, F: entry.FileNames})
651 }
652
653 cacheEntry := CacheEntry{}
654
655 for device, infos := range dirsByDevice {
656 // find common prefix
657 prefix := ""
658 if len(infos) > 0 {
659 prefix = infos[0].P
660 }
661 for _, info := range infos {
662 for !strings.HasPrefix(info.P+"/", prefix+"/") {
663 prefix = filepath.Dir(prefix)
664 }
665 }
666 // remove common prefix
667 for i := range infos {
668 suffix := strings.Replace(infos[i].P, prefix, "", 1)
669 if len(suffix) > 0 && suffix[0] == '/' {
670 suffix = suffix[1:]
671 }
672 infos[i].P = suffix
673 }
674
675 // turn the map (keyed by device) into a list of structs with labeled fields
676 // this is to improve readability of the output
677 cacheEntry = append(cacheEntry, PersistedDirs{Device: device, Root: prefix, Dirs: infos})
678 }
679
680 // convert to json.
681 // it would save some space to use a different format than json for the db file,
682 // but the space and time savings are small, and json is easy for humans to read
683 bytes, err := json.Marshal(cacheEntry)
684 return bytes, err
685}
686
687func (f *Finder) parseCacheEntry(bytes []byte) ([]dirFullInfo, error) {
688 var cacheEntry CacheEntry
689 err := json.Unmarshal(bytes, &cacheEntry)
690 if err != nil {
691 return nil, err
692 }
693
694 // convert from a CacheEntry to a []dirFullInfo (by copying a few fields)
695 capacity := 0
696 for _, element := range cacheEntry {
697 capacity += len(element.Dirs)
698 }
699 nodes := make([]dirFullInfo, capacity)
700 count := 0
701 for _, element := range cacheEntry {
702 for _, dir := range element.Dirs {
703 path := joinCleanPaths(element.Root, dir.P)
704
705 nodes[count] = dirFullInfo{
706 pathAndStats: pathAndStats{
707 statResponse: statResponse{
708 ModTime: dir.T, Inode: dir.I, Device: element.Device,
709 },
710 Path: path},
711 FileNames: dir.F}
712 count++
713 }
714 }
715 return nodes, nil
716}
717
718// We use the following separator byte to distinguish individually parseable blocks of json
719// because we know this separator won't appear in the json that we're parsing.
720//
721// The newline byte can only appear in a UTF-8 stream if the newline character appears, because:
722// - The newline character is encoded as "0000 1010" in binary ("0a" in hex)
723// - UTF-8 dictates that bytes beginning with a "0" bit are never emitted as part of a multibyte
724// character.
725//
726// We know that the newline character will never appear in our json string, because:
727// - If a newline character appears as part of a data string, then json encoding will
728// emit two characters instead: '\' and 'n'.
729// - The json encoder that we use doesn't emit the optional newlines between any of its
730// other outputs.
731const lineSeparator = byte('\n')
732
733func (f *Finder) readLine(reader *bufio.Reader) ([]byte, error) {
734 return reader.ReadBytes(lineSeparator)
735}
736
737// validateCacheHeader reads the cache header from cacheReader and tells whether the cache is compatible with this Finder
738func (f *Finder) validateCacheHeader(cacheReader *bufio.Reader) bool {
739 cacheVersionBytes, err := f.readLine(cacheReader)
740 if err != nil {
741 f.verbosef("Failed to read database header; database is invalid\n")
742 return false
743 }
744 if len(cacheVersionBytes) > 0 && cacheVersionBytes[len(cacheVersionBytes)-1] == lineSeparator {
745 cacheVersionBytes = cacheVersionBytes[:len(cacheVersionBytes)-1]
746 }
747 cacheVersionString := string(cacheVersionBytes)
748 currentVersion := f.cacheMetadata.Version
749 if cacheVersionString != currentVersion {
750 f.verbosef("Version changed from %q to %q, database is not applicable\n", cacheVersionString, currentVersion)
751 return false
752 }
753
754 cacheParamBytes, err := f.readLine(cacheReader)
755 if err != nil {
756 f.verbosef("Failed to read database search params; database is invalid\n")
757 return false
758 }
759
760 if len(cacheParamBytes) > 0 && cacheParamBytes[len(cacheParamBytes)-1] == lineSeparator {
761 cacheParamBytes = cacheParamBytes[:len(cacheParamBytes)-1]
762 }
763
764 currentParamBytes, err := f.cacheMetadata.Config.Dump()
765 if err != nil {
766 panic("Finder failed to serialize its parameters")
767 }
768 cacheParamString := string(cacheParamBytes)
769 currentParamString := string(currentParamBytes)
770 if cacheParamString != currentParamString {
771 f.verbosef("Params changed from %q to %q, database is not applicable\n", cacheParamString, currentParamString)
772 return false
773 }
774 return true
775}
776
777// loadBytes compares the cache info in <data> to the state of the filesystem
778// loadBytes returns a map representing <data> and also a slice of dirs that need to be re-walked
779func (f *Finder) loadBytes(id int, data []byte) (m *pathMap, dirsToWalk []string, err error) {
780
781 helperStartTime := time.Now()
782
783 cachedNodes, err := f.parseCacheEntry(data)
784 if err != nil {
785 return nil, nil, fmt.Errorf("Failed to parse block %v: %v\n", id, err.Error())
786 }
787
788 unmarshalDate := time.Now()
789 f.verbosef("Unmarshaled %v objects for %v in %v\n",
790 len(cachedNodes), id, unmarshalDate.Sub(helperStartTime))
791
792 tempMap := newPathMap("/")
793 stats := make([]statResponse, len(cachedNodes))
794
795 for i, node := range cachedNodes {
796 // check the file system for an updated timestamp
797 stats[i] = f.statDirSync(node.Path)
798 }
799
800 dirsToWalk = []string{}
801 for i, cachedNode := range cachedNodes {
802 updated := stats[i]
803 // save the cached value
804 container := tempMap.GetNode(cachedNode.Path, true)
805 container.mapNode = mapNode{statResponse: updated}
806
807 // if the metadata changed and the directory still exists, then
808 // make a note to walk it later
809 if !f.isInfoUpToDate(cachedNode.statResponse, updated) && updated.ModTime != 0 {
810 f.setModified()
811 // make a note that the directory needs to be walked
812 dirsToWalk = append(dirsToWalk, cachedNode.Path)
813 } else {
814 container.mapNode.FileNames = cachedNode.FileNames
815 }
816 }
817 // count the number of nodes to improve our understanding of the shape of the tree,
818 // thereby improving parallelism of subsequent searches
819 tempMap.UpdateNumDescendentsRecursive()
820
821 f.verbosef("Statted inodes of block %v in %v\n", id, time.Now().Sub(unmarshalDate))
822 return tempMap, dirsToWalk, nil
823}
824
825// startFromExternalCache loads the cache database from disk
826// startFromExternalCache waits to return until the load of the cache db is complete, but
827// startFromExternalCache does not wait for all every listDir() or statDir() request to complete
828func (f *Finder) startFromExternalCache() (err error) {
829 startTime := time.Now()
830 dbPath := f.DbPath
831
832 // open cache file and validate its header
833 reader, err := f.filesystem.Open(dbPath)
834 if err != nil {
835 return errors.New("No data to load from database\n")
836 }
837 bufferedReader := bufio.NewReader(reader)
838 if !f.validateCacheHeader(bufferedReader) {
839 return errors.New("Cache header does not match")
840 }
841 f.verbosef("Database header matches, will attempt to use database %v\n", f.DbPath)
842
843 // read the file and spawn threads to process it
844 nodesToWalk := [][]*pathMap{}
845 mainTree := newPathMap("/")
846
847 // read the blocks and stream them into <blockChannel>
848 type dataBlock struct {
849 id int
850 err error
851 data []byte
852 }
853 blockChannel := make(chan dataBlock, f.numDbLoadingThreads)
854 readBlocks := func() {
855 index := 0
856 for {
857 // It takes some time to unmarshal the input from json, so we want
858 // to unmarshal it in parallel. In order to find valid places to
859 // break the input, we scan for the line separators that we inserted
860 // (for this purpose) when we dumped the database.
861 data, err := f.readLine(bufferedReader)
862 var response dataBlock
863 done := false
864 if err != nil && err != io.EOF {
865 response = dataBlock{id: index, err: err, data: nil}
866 done = true
867 } else {
868 done = (err == io.EOF)
869 response = dataBlock{id: index, err: nil, data: data}
870 }
871 blockChannel <- response
872 index++
873 duration := time.Since(startTime)
874 f.verbosef("Read block %v after %v\n", index, duration)
875 if done {
876 f.verbosef("Read %v blocks in %v\n", index, duration)
877 close(blockChannel)
878 return
879 }
880 }
881 }
882 go readBlocks()
883
884 // Read from <blockChannel> and stream the responses into <resultChannel>.
885 type workResponse struct {
886 id int
887 err error
888 tree *pathMap
889 updatedDirs []string
890 }
891 resultChannel := make(chan workResponse)
892 processBlocks := func() {
893 numProcessed := 0
894 threadPool := newThreadPool(f.numDbLoadingThreads)
895 for {
896 // get a block to process
897 block, received := <-blockChannel
898 if !received {
899 break
900 }
901
902 if block.err != nil {
903 resultChannel <- workResponse{err: block.err}
904 break
905 }
906 numProcessed++
907 // wait until there is CPU available to process it
908 threadPool.Run(
909 func() {
910 processStartTime := time.Now()
911 f.verbosef("Starting to process block %v after %v\n",
912 block.id, processStartTime.Sub(startTime))
913 tempMap, updatedDirs, err := f.loadBytes(block.id, block.data)
914 var response workResponse
915 if err != nil {
916 f.verbosef(
917 "Block %v failed to parse with error %v\n",
918 block.id, err)
919 response = workResponse{err: err}
920 } else {
921 response = workResponse{
922 id: block.id,
923 err: nil,
924 tree: tempMap,
925 updatedDirs: updatedDirs,
926 }
927 }
928 f.verbosef("Processed block %v in %v\n",
929 block.id, time.Since(processStartTime),
930 )
931 resultChannel <- response
932 },
933 )
934 }
935 threadPool.Wait()
936 f.verbosef("Finished processing %v blocks in %v\n",
937 numProcessed, time.Since(startTime))
938 close(resultChannel)
939 }
940 go processBlocks()
941
942 // Read from <resultChannel> and use the results
943 combineResults := func() (err error) {
944 for {
945 result, received := <-resultChannel
946 if !received {
947 break
948 }
949 if err != nil {
950 // In case of an error, wait for work to complete before
951 // returning the error. This ensures that any subsequent
952 // work doesn't need to compete for resources (and possibly
953 // fail due to, for example, a filesystem limit on the number of
954 // concurrently open files) with past work.
955 continue
956 }
957 if result.err != nil {
958 err = result.err
959 continue
960 }
961 // update main tree
962 mainTree.MergeIn(result.tree)
963 // record any new directories that we will need to Stat()
964 updatedNodes := make([]*pathMap, len(result.updatedDirs))
965 for j, dir := range result.updatedDirs {
966 node := mainTree.GetNode(dir, false)
967 updatedNodes[j] = node
968 }
969 nodesToWalk = append(nodesToWalk, updatedNodes)
970 }
971 return err
972 }
973 err = combineResults()
974 if err != nil {
975 return err
976 }
977
978 f.nodes = *mainTree
979
980 // after having loaded the entire db and therefore created entries for
981 // the directories we know of, now it's safe to start calling ReadDir on
982 // any updated directories
983 for i := range nodesToWalk {
984 f.listDirsAsync(nodesToWalk[i])
985 }
Jeff Gastonb629e182017-08-14 16:49:18 -0700986 f.verbosef("Loaded db and statted known dirs in %v\n", time.Since(startTime))
987 f.threadPool.Wait()
988 f.verbosef("Loaded db and statted all dirs in %v\n", time.Now().Sub(startTime))
989
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700990 return err
991}
992
993// startWithoutExternalCache starts scanning the filesystem according to the cache config
994// startWithoutExternalCache should be called if startFromExternalCache is not applicable
995func (f *Finder) startWithoutExternalCache() {
Jeff Gastonb629e182017-08-14 16:49:18 -0700996 startTime := time.Now()
Jeff Gastonf1fd45e2017-08-09 18:25:28 -0700997 configDirs := f.cacheMetadata.Config.RootDirs
998
999 // clean paths
1000 candidates := make([]string, len(configDirs))
1001 for i, dir := range configDirs {
1002 candidates[i] = filepath.Clean(dir)
1003 }
1004 // remove duplicates
1005 dirsToScan := make([]string, 0, len(configDirs))
1006 for _, candidate := range candidates {
1007 include := true
1008 for _, included := range dirsToScan {
1009 if included == "/" || strings.HasPrefix(candidate+"/", included+"/") {
1010 include = false
1011 break
1012 }
1013 }
1014 if include {
1015 dirsToScan = append(dirsToScan, candidate)
1016 }
1017 }
1018
1019 // start searching finally
1020 for _, path := range dirsToScan {
1021 f.verbosef("Starting find of %v\n", path)
1022 f.startFind(path)
1023 }
Jeff Gastonb629e182017-08-14 16:49:18 -07001024
1025 f.threadPool.Wait()
1026
1027 f.verbosef("Scanned filesystem (not using cache) in %v\n", time.Now().Sub(startTime))
Jeff Gastonf1fd45e2017-08-09 18:25:28 -07001028}
1029
1030// isInfoUpToDate tells whether <new> can confirm that results computed at <old> are still valid
1031func (f *Finder) isInfoUpToDate(old statResponse, new statResponse) (equal bool) {
1032 if old.Inode != new.Inode {
1033 return false
1034 }
1035 if old.ModTime != new.ModTime {
1036 return false
1037 }
1038 if old.Device != new.Device {
1039 return false
1040 }
1041 return true
1042}
1043
1044func (f *Finder) wasModified() bool {
1045 return atomic.LoadInt32(&f.modifiedFlag) > 0
1046}
1047
1048func (f *Finder) setModified() {
1049 var newVal int32
1050 newVal = 1
1051 atomic.StoreInt32(&f.modifiedFlag, newVal)
1052}
1053
1054// sortedDirEntries exports directory entries to facilitate dumping them to the external cache
1055func (f *Finder) sortedDirEntries() []dirFullInfo {
1056 startTime := time.Now()
1057 nodes := make([]dirFullInfo, 0)
1058 for _, node := range f.nodes.DumpAll() {
1059 if node.ModTime != 0 {
1060 nodes = append(nodes, node)
1061 }
1062 }
1063 discoveryDate := time.Now()
1064 f.verbosef("Generated %v cache entries in %v\n", len(nodes), discoveryDate.Sub(startTime))
1065 less := func(i int, j int) bool {
1066 return nodes[i].Path < nodes[j].Path
1067 }
1068 sort.Slice(nodes, less)
1069 sortDate := time.Now()
1070 f.verbosef("Sorted %v cache entries in %v\n", len(nodes), sortDate.Sub(discoveryDate))
1071
1072 return nodes
1073}
1074
1075// serializeDb converts the cache database into a form to save to disk
1076func (f *Finder) serializeDb() ([]byte, error) {
1077 // sort dir entries
1078 var entryList = f.sortedDirEntries()
1079
1080 // Generate an output file that can be conveniently loaded using the same number of threads
1081 // as were used in this execution (because presumably that will be the number of threads
1082 // used in the next execution too)
1083
1084 // generate header
1085 header := []byte{}
1086 header = append(header, []byte(f.cacheMetadata.Version)...)
1087 header = append(header, lineSeparator)
1088 configDump, err := f.cacheMetadata.Config.Dump()
1089 if err != nil {
1090 return nil, err
1091 }
1092 header = append(header, configDump...)
1093
1094 // serialize individual blocks in parallel
1095 numBlocks := f.numDbLoadingThreads
1096 if numBlocks > len(entryList) {
1097 numBlocks = len(entryList)
1098 }
1099 blocks := make([][]byte, 1+numBlocks)
1100 blocks[0] = header
1101 blockMin := 0
1102 wg := sync.WaitGroup{}
1103 var errLock sync.Mutex
1104
1105 for i := 1; i <= numBlocks; i++ {
1106 // identify next block
1107 blockMax := len(entryList) * i / numBlocks
1108 block := entryList[blockMin:blockMax]
1109
1110 // process block
1111 wg.Add(1)
1112 go func(index int, block []dirFullInfo) {
1113 byteBlock, subErr := f.serializeCacheEntry(block)
1114 f.verbosef("Serialized block %v into %v bytes\n", index, len(byteBlock))
1115 if subErr != nil {
1116 f.verbosef("%v\n", subErr.Error())
1117 errLock.Lock()
1118 err = subErr
1119 errLock.Unlock()
1120 } else {
1121 blocks[index] = byteBlock
1122 }
1123 wg.Done()
1124 }(i, block)
1125
1126 blockMin = blockMax
1127 }
1128
1129 wg.Wait()
1130
1131 if err != nil {
1132 return nil, err
1133 }
1134
1135 content := bytes.Join(blocks, []byte{lineSeparator})
1136
1137 return content, nil
1138}
1139
1140// dumpDb saves the cache database to disk
1141func (f *Finder) dumpDb() error {
1142 startTime := time.Now()
1143 f.verbosef("Dumping db\n")
1144
1145 tempPath := f.DbPath + ".tmp"
1146
1147 bytes, err := f.serializeDb()
1148 if err != nil {
1149 return err
1150 }
1151 serializeDate := time.Now()
1152 f.verbosef("Serialized db in %v\n", serializeDate.Sub(startTime))
1153 // dump file and atomically move
1154 err = f.filesystem.WriteFile(tempPath, bytes, 0777)
1155 if err != nil {
1156 return err
1157 }
1158 err = f.filesystem.Rename(tempPath, f.DbPath)
1159 if err != nil {
1160 return err
1161 }
1162
1163 f.verbosef("Wrote db in %v\n", time.Now().Sub(serializeDate))
1164 return nil
Jeff Gastonb629e182017-08-14 16:49:18 -07001165
1166}
1167
1168// canIgnoreFsErr checks for certain classes of filesystem errors that are safe to ignore
1169func (f *Finder) canIgnoreFsErr(err error) bool {
1170 pathErr, isPathErr := err.(*os.PathError)
1171 if !isPathErr {
1172 // Don't recognize this error
1173 return false
1174 }
1175 if pathErr.Err == os.ErrPermission {
1176 // Permission errors are ignored:
1177 // https://issuetracker.google.com/37553659
1178 // https://github.com/google/kati/pull/116
1179 return true
1180 }
1181 if pathErr.Err == os.ErrNotExist {
1182 // If a directory doesn't exist, that generally means the cache is out-of-date
1183 return true
1184 }
1185 // Don't recognize this error
1186 return false
1187}
1188
1189// onFsError should be called whenever a potentially fatal error is returned from a filesystem call
1190func (f *Finder) onFsError(path string, err error) {
1191 if !f.canIgnoreFsErr(err) {
1192 // We could send the errors through a channel instead, although that would cause this call
1193 // to block unless we preallocated a sufficient buffer or spawned a reader thread.
1194 // Although it wouldn't be too complicated to spawn a reader thread, it's still slightly
1195 // more convenient to use a lock. Only in an unusual situation should this code be
1196 // invoked anyway.
1197 f.errlock.Lock()
1198 f.fsErrs = append(f.fsErrs, fsErr{path: path, err: err})
1199 f.errlock.Unlock()
1200 }
1201}
1202
1203// discardErrsForPrunedPaths removes any errors for paths that are no longer included in the cache
1204func (f *Finder) discardErrsForPrunedPaths() {
1205 // This function could be somewhat inefficient due to being single-threaded,
1206 // but the length of f.fsErrs should be approximately 0, so it shouldn't take long anyway.
1207 relevantErrs := make([]fsErr, 0, len(f.fsErrs))
1208 for _, fsErr := range f.fsErrs {
1209 path := fsErr.path
1210 node := f.nodes.GetNode(path, false)
1211 if node != nil {
1212 // The path in question wasn't pruned due to a failure to process a parent directory.
1213 // So, the failure to process this path is important
1214 relevantErrs = append(relevantErrs, fsErr)
1215 }
1216 }
1217 f.fsErrs = relevantErrs
1218}
1219
1220// getErr returns an error based on previous calls to onFsErr, if any
1221func (f *Finder) getErr() error {
1222 f.discardErrsForPrunedPaths()
1223
1224 numErrs := len(f.fsErrs)
1225 if numErrs < 1 {
1226 return nil
1227 }
1228
1229 maxNumErrsToInclude := 10
1230 message := ""
1231 if numErrs > maxNumErrsToInclude {
1232 message = fmt.Sprintf("finder encountered %v errors: %v...", numErrs, f.fsErrs[:maxNumErrsToInclude])
1233 } else {
1234 message = fmt.Sprintf("finder encountered %v errors: %v", numErrs, f.fsErrs)
1235 }
1236
1237 return errors.New(message)
Jeff Gastonf1fd45e2017-08-09 18:25:28 -07001238}
1239
1240func (f *Finder) statDirAsync(dir *pathMap) {
1241 node := dir
1242 path := dir.path
1243 f.threadPool.Run(
1244 func() {
1245 updatedStats := f.statDirSync(path)
1246
1247 if !f.isInfoUpToDate(node.statResponse, updatedStats) {
1248 node.mapNode = mapNode{
1249 statResponse: updatedStats,
1250 FileNames: []string{},
1251 }
1252 f.setModified()
1253 if node.statResponse.ModTime != 0 {
1254 // modification time was updated, so re-scan for
1255 // child directories
1256 f.listDirAsync(dir)
1257 }
1258 }
1259 },
1260 )
1261}
1262
1263func (f *Finder) statDirSync(path string) statResponse {
1264
1265 fileInfo, err := f.filesystem.Lstat(path)
1266
1267 var stats statResponse
1268 if err != nil {
Jeff Gastonb629e182017-08-14 16:49:18 -07001269 // possibly record this error
1270 f.onFsError(path, err)
Jeff Gastonf1fd45e2017-08-09 18:25:28 -07001271 // in case of a failure to stat the directory, treat the directory as missing (modTime = 0)
1272 return stats
1273 }
1274 modTime := fileInfo.ModTime()
1275 stats = statResponse{}
1276 inode, err := f.filesystem.InodeNumber(fileInfo)
1277 if err != nil {
1278 panic(fmt.Sprintf("Could not get inode number of %v: %v\n", path, err.Error()))
1279 }
1280 stats.Inode = inode
1281 device, err := f.filesystem.DeviceNumber(fileInfo)
1282 if err != nil {
1283 panic(fmt.Sprintf("Could not get device number of %v: %v\n", path, err.Error()))
1284 }
1285 stats.Device = device
1286 permissionsChangeTime, err := f.filesystem.PermTime(fileInfo)
1287
1288 if err != nil {
1289 panic(fmt.Sprintf("Could not get permissions modification time (CTime) of %v: %v\n", path, err.Error()))
1290 }
1291 // We're only interested in knowing whether anything about the directory
1292 // has changed since last check, so we use the latest of the two
1293 // modification times (content modification (mtime) and
1294 // permission modification (ctime))
1295 if permissionsChangeTime.After(modTime) {
1296 modTime = permissionsChangeTime
1297 }
1298 stats.ModTime = modTime.UnixNano()
1299
1300 return stats
1301}
1302
1303// pruneCacheCandidates removes the items that we don't want to include in our persistent cache
1304func (f *Finder) pruneCacheCandidates(items *DirEntries) {
1305
1306 for _, fileName := range items.FileNames {
1307 for _, abortedName := range f.cacheMetadata.Config.PruneFiles {
1308 if fileName == abortedName {
1309 items.FileNames = []string{}
1310 items.DirNames = []string{}
1311 return
1312 }
1313 }
1314 }
1315
1316 // remove any files that aren't the ones we want to include
1317 writeIndex := 0
1318 for _, fileName := range items.FileNames {
1319 // include only these files
1320 for _, includedName := range f.cacheMetadata.Config.IncludeFiles {
1321 if fileName == includedName {
1322 items.FileNames[writeIndex] = fileName
1323 writeIndex++
1324 break
1325 }
1326 }
1327 }
1328 // resize
1329 items.FileNames = items.FileNames[:writeIndex]
1330
1331 writeIndex = 0
1332 for _, dirName := range items.DirNames {
1333 items.DirNames[writeIndex] = dirName
1334 // ignore other dirs that are known to not be inputs to the build process
1335 include := true
1336 for _, excludedName := range f.cacheMetadata.Config.ExcludeDirs {
1337 if dirName == excludedName {
1338 // don't include
1339 include = false
1340 break
1341 }
1342 }
1343 if include {
1344 writeIndex++
1345 }
1346 }
1347 // resize
1348 items.DirNames = items.DirNames[:writeIndex]
1349}
1350
1351func (f *Finder) listDirsAsync(nodes []*pathMap) {
1352 f.threadPool.Run(
1353 func() {
1354 for i := range nodes {
1355 f.listDirSync(nodes[i])
1356 }
1357 },
1358 )
1359}
1360
1361func (f *Finder) listDirAsync(node *pathMap) {
1362 f.threadPool.Run(
1363 func() {
1364 f.listDirSync(node)
1365 },
1366 )
1367}
1368
1369func (f *Finder) listDirSync(dir *pathMap) {
1370 path := dir.path
1371 children, err := f.filesystem.ReadDir(path)
1372
1373 if err != nil {
Jeff Gastonb629e182017-08-14 16:49:18 -07001374 // possibly record this error
1375 f.onFsError(path, err)
Jeff Gastonf1fd45e2017-08-09 18:25:28 -07001376 // if listing the contents of the directory fails (presumably due to
1377 // permission denied), then treat the directory as empty
1378 children = []os.FileInfo{}
1379 }
1380
1381 var subdirs []string
1382 var subfiles []string
1383
1384 for _, child := range children {
1385 linkBits := child.Mode() & os.ModeSymlink
1386 isLink := linkBits != 0
1387 if child.IsDir() {
1388 if !isLink {
1389 // Skip symlink dirs.
1390 // We don't have to support symlink dirs because
1391 // that would cause duplicates.
1392 subdirs = append(subdirs, child.Name())
1393 }
1394 } else {
1395 // We do have to support symlink files because the link name might be
1396 // different than the target name
1397 // (for example, Android.bp -> build/soong/root.bp)
1398 subfiles = append(subfiles, child.Name())
1399 }
1400
1401 }
1402 parentNode := dir
1403
1404 entry := &DirEntries{Path: path, DirNames: subdirs, FileNames: subfiles}
1405 f.pruneCacheCandidates(entry)
1406
1407 // create a pathMap node for each relevant subdirectory
1408 relevantChildren := map[string]*pathMap{}
1409 for _, subdirName := range entry.DirNames {
1410 childNode, found := parentNode.children[subdirName]
1411 // if we already knew of this directory, then we already have a request pending to Stat it
1412 // if we didn't already know of this directory, then we must Stat it now
1413 if !found {
1414 childNode = parentNode.newChild(subdirName)
1415 f.statDirAsync(childNode)
1416 }
1417 relevantChildren[subdirName] = childNode
1418 }
1419 // Note that in rare cases, it's possible that we're reducing the set of
1420 // children via this statement, if these are all true:
1421 // 1. we previously had a cache that knew about subdirectories of parentNode
1422 // 2. the user created a prune-file (described in pruneCacheCandidates)
1423 // inside <parentNode>, which specifies that the contents of parentNode
1424 // are to be ignored.
1425 // The fact that it's possible to remove children here means that *pathMap structs
1426 // must not be looked up from f.nodes by filepath (and instead must be accessed by
1427 // direct pointer) until after every listDirSync completes
1428 parentNode.FileNames = entry.FileNames
1429 parentNode.children = relevantChildren
1430
1431}
1432
1433// listMatches takes a node and a function that specifies which subdirectories and
1434// files to include, and listMatches returns the matches
1435func (f *Finder) listMatches(node *pathMap,
1436 filter WalkFunc) (subDirs []*pathMap, filePaths []string) {
1437 entries := DirEntries{
1438 FileNames: node.FileNames,
1439 }
1440 entries.DirNames = make([]string, 0, len(node.children))
1441 for childName := range node.children {
1442 entries.DirNames = append(entries.DirNames, childName)
1443 }
1444
1445 dirNames, fileNames := filter(entries)
1446
1447 subDirs = []*pathMap{}
1448 filePaths = make([]string, 0, len(fileNames))
1449 for _, fileName := range fileNames {
1450 filePaths = append(filePaths, joinCleanPaths(node.path, fileName))
1451 }
1452 subDirs = make([]*pathMap, 0, len(dirNames))
1453 for _, childName := range dirNames {
1454 child, ok := node.children[childName]
1455 if ok {
1456 subDirs = append(subDirs, child)
1457 }
1458 }
1459
1460 return subDirs, filePaths
1461}
1462
1463// findInCacheMultithreaded spawns potentially multiple goroutines with which to search the cache.
1464func (f *Finder) findInCacheMultithreaded(node *pathMap, filter WalkFunc,
1465 approxNumThreads int) []string {
1466
1467 if approxNumThreads < 2 {
1468 // Done spawning threads; process remaining directories
1469 return f.findInCacheSinglethreaded(node, filter)
1470 }
1471
1472 totalWork := 0
1473 for _, child := range node.children {
1474 totalWork += child.approximateNumDescendents
1475 }
1476 childrenResults := make(chan []string, len(node.children))
1477
1478 subDirs, filePaths := f.listMatches(node, filter)
1479
1480 // process child directories
1481 for _, child := range subDirs {
1482 numChildThreads := approxNumThreads * child.approximateNumDescendents / totalWork
1483 childProcessor := func(child *pathMap) {
1484 childResults := f.findInCacheMultithreaded(child, filter, numChildThreads)
1485 childrenResults <- childResults
1486 }
1487 // If we're allowed to use more than 1 thread to process this directory,
1488 // then instead we use 1 thread for each subdirectory.
1489 // It would be strange to spawn threads for only some subdirectories.
1490 go childProcessor(child)
1491 }
1492
1493 // collect results
1494 for i := 0; i < len(subDirs); i++ {
1495 childResults := <-childrenResults
1496 filePaths = append(filePaths, childResults...)
1497 }
1498 close(childrenResults)
1499
1500 return filePaths
1501}
1502
1503// findInCacheSinglethreaded synchronously searches the cache for all matching file paths
1504// note findInCacheSinglethreaded runs 2X to 4X as fast by being iterative rather than recursive
1505func (f *Finder) findInCacheSinglethreaded(node *pathMap, filter WalkFunc) []string {
1506 if node == nil {
1507 return []string{}
1508 }
1509
1510 nodes := []*pathMap{node}
1511 matches := []string{}
1512
1513 for len(nodes) > 0 {
1514 currentNode := nodes[0]
1515 nodes = nodes[1:]
1516
1517 subDirs, filePaths := f.listMatches(currentNode, filter)
1518
1519 nodes = append(nodes, subDirs...)
1520
1521 matches = append(matches, filePaths...)
1522 }
1523 return matches
1524}