summaryrefslogtreecommitdiffstats
path: root/modules/doctor/storage.go
blob: aa987de4477b46ff991866d0323f8953ad30e8ef (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
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
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package doctor

import (
	"context"
	"errors"
	"io/fs"
	"strings"

	"code.gitea.io/gitea/models/git"
	"code.gitea.io/gitea/models/packages"
	"code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/base"
	"code.gitea.io/gitea/modules/log"
	packages_module "code.gitea.io/gitea/modules/packages"
	"code.gitea.io/gitea/modules/storage"
	"code.gitea.io/gitea/modules/util"
)

type commonStorageCheckOptions struct {
	storer     storage.ObjectStorage
	isOrphaned func(path string, obj storage.Object, stat fs.FileInfo) (bool, error)
	name       string
}

func commonCheckStorage(ctx context.Context, logger log.Logger, autofix bool, opts *commonStorageCheckOptions) error {
	totalCount, orphanedCount := 0, 0
	totalSize, orphanedSize := int64(0), int64(0)

	var pathsToDelete []string
	if err := opts.storer.IterateObjects(func(p string, obj storage.Object) error {
		defer obj.Close()

		totalCount++
		stat, err := obj.Stat()
		if err != nil {
			return err
		}
		totalSize += stat.Size()

		orphaned, err := opts.isOrphaned(p, obj, stat)
		if err != nil {
			return err
		}
		if orphaned {
			orphanedCount++
			orphanedSize += stat.Size()
			if autofix {
				pathsToDelete = append(pathsToDelete, p)
			}
		}
		return nil
	}); err != nil {
		logger.Error("Error whilst iterating %s storage: %v", opts.name, err)
		return err
	}

	if orphanedCount > 0 {
		if autofix {
			var deletedNum int
			for _, p := range pathsToDelete {
				if err := opts.storer.Delete(p); err != nil {
					log.Error("Error whilst deleting %s from %s storage: %v", p, opts.name, err)
				} else {
					deletedNum++
				}
			}
			logger.Info("Deleted %d/%d orphaned %s(s)", deletedNum, orphanedCount, opts.name)
		} else {
			logger.Warn("Found %d/%d (%s/%s) orphaned %s(s)", orphanedCount, totalCount, base.FileSize(orphanedSize), base.FileSize(totalSize), opts.name)
		}
	} else {
		logger.Info("Found %d (%s) %s(s)", totalCount, base.FileSize(totalSize), opts.name)
	}
	return nil
}

type checkStorageOptions struct {
	All          bool
	Attachments  bool
	LFS          bool
	Avatars      bool
	RepoAvatars  bool
	RepoArchives bool
	Packages     bool
}

// checkStorage will return a doctor check function to check the requested storage types for "orphaned" stored object/files and optionally delete them
func checkStorage(opts *checkStorageOptions) func(ctx context.Context, logger log.Logger, autofix bool) error {
	return func(ctx context.Context, logger log.Logger, autofix bool) error {
		if err := storage.Init(); err != nil {
			logger.Error("storage.Init failed: %v", err)
			return err
		}

		if opts.Attachments || opts.All {
			if err := commonCheckStorage(ctx, logger, autofix,
				&commonStorageCheckOptions{
					storer: storage.Attachments,
					isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) {
						exists, err := repo.ExistAttachmentsByUUID(ctx, stat.Name())
						return !exists, err
					},
					name: "attachment",
				}); err != nil {
				return err
			}
		}

		if opts.LFS || opts.All {
			if err := commonCheckStorage(ctx, logger, autofix,
				&commonStorageCheckOptions{
					storer: storage.LFS,
					isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) {
						// The oid of an LFS stored object is the name but with all the path.Separators removed
						oid := strings.ReplaceAll(path, "/", "")
						exists, err := git.ExistsLFSObject(ctx, oid)
						return !exists, err
					},
					name: "LFS file",
				}); err != nil {
				return err
			}
		}

		if opts.Avatars || opts.All {
			if err := commonCheckStorage(ctx, logger, autofix,
				&commonStorageCheckOptions{
					storer: storage.Avatars,
					isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) {
						exists, err := user.ExistsWithAvatarAtStoragePath(ctx, path)
						return !exists, err
					},
					name: "avatar",
				}); err != nil {
				return err
			}
		}

		if opts.RepoAvatars || opts.All {
			if err := commonCheckStorage(ctx, logger, autofix,
				&commonStorageCheckOptions{
					storer: storage.RepoAvatars,
					isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) {
						exists, err := repo.ExistsWithAvatarAtStoragePath(ctx, path)
						return !exists, err
					},
					name: "repo avatar",
				}); err != nil {
				return err
			}
		}

		if opts.RepoArchives || opts.All {
			if err := commonCheckStorage(ctx, logger, autofix,
				&commonStorageCheckOptions{
					storer: storage.RepoAvatars,
					isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) {
						exists, err := repo.ExistsRepoArchiverWithStoragePath(ctx, path)
						if err == nil || errors.Is(err, util.ErrInvalidArgument) {
							// invalid arguments mean that the object is not a valid repo archiver and it should be removed
							return !exists, nil
						}
						return !exists, err
					},
					name: "repo archive",
				}); err != nil {
				return err
			}
		}

		if opts.Packages || opts.All {
			if err := commonCheckStorage(ctx, logger, autofix,
				&commonStorageCheckOptions{
					storer: storage.Packages,
					isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) {
						key, err := packages_module.RelativePathToKey(path)
						if err != nil {
							// If there is an error here then the relative path does not match a valid package
							// Therefore it is orphaned by default
							return true, nil
						}

						exists, err := packages.ExistPackageBlobWithSHA(ctx, string(key))

						return !exists, err
					},
					name: "package blob",
				}); err != nil {
				return err
			}
		}

		return nil
	}
}

func init() {
	Register(&Check{
		Title:                      "Check if there are orphaned storage files",
		Name:                       "storages",
		IsDefault:                  false,
		Run:                        checkStorage(&checkStorageOptions{All: true}),
		AbortIfFailed:              false,
		SkipDatabaseInitialization: false,
		Priority:                   1,
	})

	Register(&Check{
		Title:                      "Check if there are orphaned attachments in storage",
		Name:                       "storage-attachments",
		IsDefault:                  false,
		Run:                        checkStorage(&checkStorageOptions{Attachments: true}),
		AbortIfFailed:              false,
		SkipDatabaseInitialization: false,
		Priority:                   1,
	})

	Register(&Check{
		Title:                      "Check if there are orphaned lfs files in storage",
		Name:                       "storage-lfs",
		IsDefault:                  false,
		Run:                        checkStorage(&checkStorageOptions{LFS: true}),
		AbortIfFailed:              false,
		SkipDatabaseInitialization: false,
		Priority:                   1,
	})

	Register(&Check{
		Title:                      "Check if there are orphaned avatars in storage",
		Name:                       "storage-avatars",
		IsDefault:                  false,
		Run:                        checkStorage(&checkStorageOptions{Avatars: true, RepoAvatars: true}),
		AbortIfFailed:              false,
		SkipDatabaseInitialization: false,
		Priority:                   1,
	})

	Register(&Check{
		Title:                      "Check if there are orphaned archives in storage",
		Name:                       "storage-archives",
		IsDefault:                  false,
		Run:                        checkStorage(&checkStorageOptions{RepoArchives: true}),
		AbortIfFailed:              false,
		SkipDatabaseInitialization: false,
		Priority:                   1,
	})

	Register(&Check{
		Title:                      "Check if there are orphaned package blobs in storage",
		Name:                       "storage-packages",
		IsDefault:                  false,
		Run:                        checkStorage(&checkStorageOptions{Packages: true}),
		AbortIfFailed:              false,
		SkipDatabaseInitialization: false,
		Priority:                   1,
	})
}