Welcome to mirror list, hosted at ThFree Co, Russian Federation.

walker.go « cache « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 00d990c175e0248dc62f01ca9441197cde564a98 (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
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
// Package cache supplies background workers for periodically cleaning the
// cache folder on all storages listed in the config file. Upon configuration
// validation, one worker will be started for each storage. The worker will
// walk the cache directory tree and remove any files older than one hour. The
// worker will walk the cache directory every ten minutes.
package cache

//nolint:depguard
import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"github.com/sirupsen/logrus"
	"gitlab.com/gitlab-org/gitaly/v14/internal/dontpanic"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/config"
	"gitlab.com/gitlab-org/gitaly/v14/internal/log"
)

func (c *DiskCache) logWalkErr(err error, path, msg string) {
	c.walkerErrorTotal.Inc()
	log.Default().
		WithField("path", path).
		WithError(err).
		Warn(msg)
}

func (c *DiskCache) cleanWalk(path string) error {
	defer time.Sleep(100 * time.Microsecond) // relieve pressure

	c.walkerCheckTotal.Inc()
	entries, err := ioutil.ReadDir(path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		c.logWalkErr(err, path, "unable to stat directory")
		return err
	}

	for _, e := range entries {
		ePath := filepath.Join(path, e.Name())

		if e.IsDir() {
			if err := c.cleanWalk(ePath); err != nil {
				return err
			}
			continue
		}

		c.walkerCheckTotal.Inc()
		if time.Since(e.ModTime()) < staleAge {
			continue // still fresh
		}

		// file is stale
		if err := os.Remove(ePath); err != nil {
			if os.IsNotExist(err) {
				continue
			}
			c.logWalkErr(err, ePath, "unable to remove file")
			return err
		}
		c.walkerRemovalTotal.Inc()
	}

	files, err := os.ReadDir(path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		c.logWalkErr(err, path, "unable to stat directory after walk")
		return err
	}

	if len(files) == 0 {
		c.walkerEmptyDirTotal.Inc()
		if err := os.Remove(path); err != nil {
			if os.IsNotExist(err) {
				return nil
			}
			c.logWalkErr(err, path, "unable to remove empty directory")
			return err
		}
		c.walkerEmptyDirRemovalTotal.Inc()
		c.walkerRemovalTotal.Inc()
	}

	return nil
}

const cleanWalkFrequency = 10 * time.Minute

func (c *DiskCache) walkLoop(walkPath string) {
	logger := logrus.WithField("path", walkPath)
	logger.Infof("Starting file walker for %s", walkPath)

	walkTick := time.NewTicker(cleanWalkFrequency)

	forever := dontpanic.NewForever(time.Minute)
	forever.Go(func() {
		select {
		case <-c.walkersDone:
			return
		default:
		}

		if err := c.cleanWalk(walkPath); err != nil {
			logger.Error(err)
		}

		select {
		case <-c.walkersDone:
			return
		case <-walkTick.C:
		}
	})

	c.walkerLoops = append(c.walkerLoops, forever)
}

func (c *DiskCache) startCleanWalker(cacheDir, stateDir string) {
	if c.cacheConfig.disableWalker {
		return
	}

	c.walkLoop(cacheDir)
	c.walkLoop(stateDir)
}

// moveAndClear will move the cache to the storage location's
// temporary folder, and then remove its contents asynchronously
func (c *DiskCache) moveAndClear(storage config.Storage) error {
	if c.cacheConfig.disableMoveAndClear {
		return nil
	}

	logger := logrus.WithField("storage", storage.Name)
	logger.Info("clearing disk cache object folder")

	tempPath, err := c.locator.TempDir(storage.Name)
	if err != nil {
		return fmt.Errorf("temp dir: %w", err)
	}

	if err := os.MkdirAll(tempPath, 0o755); err != nil {
		return err
	}

	tmpDir, err := os.MkdirTemp(tempPath, "diskcache")
	if err != nil {
		return err
	}

	defer func() {
		dontpanic.Go(func() {
			start := time.Now()
			if err := os.RemoveAll(tmpDir); err != nil {
				logger.Errorf("unable to remove disk cache objects: %q", err)
				return
			}

			logger.Infof("cleared all cache object files in %s after %s", tmpDir, time.Since(start))
		})
	}()

	logger.Infof("moving disk cache object folder to %s", tmpDir)

	cachePath, err := c.locator.CacheDir(storage.Name)
	if err != nil {
		return fmt.Errorf("cache dir: %w", err)
	}

	if err := os.Rename(cachePath, filepath.Join(tmpDir, "moved")); err != nil {
		if os.IsNotExist(err) {
			logger.Info("disk cache object folder doesn't exist, no need to remove")
			return nil
		}

		return err
	}

	return nil
}

// StartWalkers starts the cache walker Goroutines. Initially, this function will try to clean up
// any preexisting cache directories.
func (c *DiskCache) StartWalkers() error {
	// Deduplicate storages by path.
	storageByPath := map[string]config.Storage{}
	for _, storage := range c.storages {
		storageByPath[storage.Path] = storage
	}

	for _, storage := range storageByPath {
		cacheDir, err := c.locator.CacheDir(storage.Name)
		if err != nil {
			return fmt.Errorf("cache dir: %w", err)
		}

		stateDir, err := c.locator.StateDir(storage.Name)
		if err != nil {
			return fmt.Errorf("state dir: %w", err)
		}

		if err := c.moveAndClear(storage); err != nil {
			return err
		}

		c.startCleanWalker(cacheDir, stateDir)
	}

	return nil
}

// StopWalkers stops all walkers started by StartWalkers.
func (c *DiskCache) StopWalkers() {
	close(c.walkersDone)
	for _, walkerLoop := range c.walkerLoops {
		walkerLoop.Cancel()
	}
	c.walkerLoops = nil
}