summaryrefslogtreecommitdiffstats
path: root/modules/doctor/storage.go
blob: d2b7f5ee13895b9f7b10313cc9bf0bbed1a1a501 (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
// Copyright 2021 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package doctor

import (
	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/storage"
)

func checkAttachmentStorageFiles(logger log.Logger, autofix bool) error {
	var total, garbageNum int
	var deletePaths []string
	if err := storage.Attachments.IterateObjects(func(p string, obj storage.Object) error {
		defer obj.Close()

		total++
		stat, err := obj.Stat()
		if err != nil {
			return err
		}
		exist, err := repo_model.ExistAttachmentsByUUID(stat.Name())
		if err != nil {
			return err
		}
		if !exist {
			garbageNum++
			if autofix {
				deletePaths = append(deletePaths, p)
			}
		}
		return nil
	}); err != nil {
		logger.Error("storage.Attachments.IterateObjects failed: %v", err)
		return err
	}

	if garbageNum > 0 {
		if autofix {
			var deletedNum int
			for _, p := range deletePaths {
				if err := storage.Attachments.Delete(p); err != nil {
					log.Error("Delete attachment %s failed: %v", p, err)
				} else {
					deletedNum++
				}
			}
			logger.Info("%d missed information attachment detected, %d deleted.", garbageNum, deletedNum)
		} else {
			logger.Warn("Checked %d attachment, %d missed information.", total, garbageNum)
		}
	}
	return nil
}

func checkStorageFiles(logger log.Logger, autofix bool) error {
	if err := storage.Init(); err != nil {
		logger.Error("storage.Init failed: %v", err)
		return err
	}
	return checkAttachmentStorageFiles(logger, autofix)
}

func init() {
	Register(&Check{
		Title:                      "Check if there is garbage storage files",
		Name:                       "storages",
		IsDefault:                  false,
		Run:                        checkStorageFiles,
		AbortIfFailed:              false,
		SkipDatabaseInitialization: false,
		Priority:                   1,
	})
}