mirror of
https://github.com/syncthing/syncthing.git
synced 2026-01-30 16:51:45 -05:00
This updates our logging framework from legacy freetext strings using the `log` package to structured log entries using `log/slog`. I have updated all INFO or higher level entries, but not yet DEBUG (😓)... So, at a high level: There is a slight change in log levels, effectively adding a new warning level: - DEBUG is still debug (ideally not for users but developers, though this is something we need to work on) - INFO is still info, though I've added more data here, effectively making Syncthing more verbose by default (more on this below) - WARNING is a new log level that is different from the _old_ WARNING (more below) - ERROR is what was WARNING before -- problems that must be dealt with, and also bubbled as a popup in the GUI. A new feature is that the logging level can be set per package to something other than just debug or info, and hence I feel that we can add a bit more things into INFO while moving some (in fact, most) current INFO level warnings into WARNING. For example, I think it's justified to get a log of synced files in INFO and sync failures in WARNING. These are things that have historically been tricky to debug properly, and having more information by default will be useful to many, while still making it possible get close to told level of inscrutability by setting the log level to WARNING. I'd like to get to a stage where DEBUG is never necessary to just figure out what's going on, as opposed to trying to narrow down a likely bug. Code wise: - Our logging object, generally known as `l` in each package, is now a new adapter object that provides the old API on top of the newer one. (This should go away once all old log entries are migrated.) This is only for `l.Debugln` and `l.Debugf`. - There is a new level tracker that keeps the log level for each package. - There is a nested setup of handlers, since the structure mandated by `log/slog` is slightly convoluted (imho). We do this because we need to do formatting at a "medium" level internally so we can buffer log lines in text format but with separate timestamp and log level for the API/GUI to consume. - The `debug` API call becomes a `loglevels` API call, which can set the log level to `DEBUG`, `INFO`, `WARNING` or `ERROR` per package. The GUI is updated to handle this. - Our custom `sync` package provided some debugging of mutexes quite strongly integrated into the old logging framework, only turned on when `STTRACE` was set to certain values at startup, etc. It's been a long time since this has been useful; I removed it. - The `STTRACE` env var remains and can be used the same way as before, while additionally permitting specific log levels to be specified, `STTRACE=model:WARN,scanner:DEBUG`. - There is a new command line option `--log-level=INFO` to set the default log level. - The command line options `--log-flags` and `--verbose` go away, but are currently retained as hidden & ignored options since we set them by default in some of our startup examples and Syncthing would otherwise fail to start. Sample format messages: ``` 2009-02-13 23:31:30 INF A basic info line (attr1="val with spaces" attr2=2 attr3="val\"quote" a=a log.pkg=slogutil) 2009-02-13 23:31:30 INF An info line with grouped values (attr1=val1 foo.attr2=2 foo.bar.attr3=3 a=a log.pkg=slogutil) 2009-02-13 23:31:30 INF An info line with grouped values via logger (foo.attr1=val1 foo.attr2=2 a=a log.pkg=slogutil) 2009-02-13 23:31:30 INF An info line with nested grouped values via logger (bar.foo.attr1=val1 bar.foo.attr2=2 a=a log.pkg=slogutil) 2009-02-13 23:31:30 WRN A warning entry (a=a log.pkg=slogutil) 2009-02-13 23:31:30 ERR An error (a=a log.pkg=slogutil) ``` --------- Co-authored-by: Ross Smith II <ross@smithii.com>
418 lines
11 KiB
Go
418 lines
11 KiB
Go
// Copyright (C) 2014 The Syncthing Authors.
|
|
//
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
package versioner
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/syncthing/syncthing/internal/slogutil"
|
|
"github.com/syncthing/syncthing/lib/config"
|
|
"github.com/syncthing/syncthing/lib/fs"
|
|
"github.com/syncthing/syncthing/lib/osutil"
|
|
"github.com/syncthing/syncthing/lib/stringutil"
|
|
)
|
|
|
|
var (
|
|
ErrDirectory = errors.New("cannot restore on top of a directory")
|
|
errNotFound = errors.New("version not found")
|
|
errFileAlreadyExists = errors.New("file already exists")
|
|
)
|
|
|
|
const (
|
|
DefaultPath = ".stversions"
|
|
)
|
|
|
|
// TagFilename inserts ~tag just before the extension of the filename.
|
|
func TagFilename(name, tag string) string {
|
|
dir, file := filepath.Dir(name), filepath.Base(name)
|
|
ext := filepath.Ext(file)
|
|
withoutExt := file[:len(file)-len(ext)]
|
|
return filepath.Join(dir, withoutExt+"~"+tag+ext)
|
|
}
|
|
|
|
var tagExp = regexp.MustCompile(`.*~([^~.]+)(?:\.[^.]+)?$`)
|
|
|
|
// extractTag returns the tag from a filename, whether at the end or middle.
|
|
func extractTag(path string) string {
|
|
match := tagExp.FindStringSubmatch(path)
|
|
// match is []string{"whole match", "submatch"} when successful
|
|
|
|
if len(match) != 2 {
|
|
return ""
|
|
}
|
|
return match[1]
|
|
}
|
|
|
|
// UntagFilename returns the filename without tag, and the extracted tag
|
|
func UntagFilename(path string) (string, string) {
|
|
ext := filepath.Ext(path)
|
|
versionTag := extractTag(path)
|
|
|
|
// Files tagged with old style tags cannot be untagged.
|
|
if versionTag == "" {
|
|
return "", ""
|
|
}
|
|
|
|
// Old style tag
|
|
if strings.HasSuffix(ext, versionTag) {
|
|
return strings.TrimSuffix(path, "~"+versionTag), versionTag
|
|
}
|
|
|
|
withoutExt := path[:len(path)-len(ext)-len(versionTag)-1]
|
|
name := withoutExt + ext
|
|
return name, versionTag
|
|
}
|
|
|
|
func retrieveVersions(fileSystem fs.Filesystem) (map[string][]FileVersion, error) {
|
|
files := make(map[string][]FileVersion)
|
|
|
|
err := fileSystem.Walk(".", func(path string, f fs.FileInfo, err error) error {
|
|
// Skip root (which is ok to be a symlink)
|
|
if path == "." {
|
|
return nil
|
|
}
|
|
|
|
// Skip walking if we cannot walk...
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Ignore symlinks
|
|
if f.IsSymlink() {
|
|
return fs.SkipDir
|
|
}
|
|
|
|
// No records for directories
|
|
if f.IsDir() {
|
|
return nil
|
|
}
|
|
|
|
modTime := f.ModTime().Truncate(time.Second)
|
|
|
|
path = osutil.NormalizedFilename(path)
|
|
|
|
name, tag := UntagFilename(path)
|
|
// Something invalid, assume it's an untagged file (trashcan versioner stuff)
|
|
if name == "" || tag == "" {
|
|
files[path] = append(files[path], FileVersion{
|
|
VersionTime: modTime,
|
|
ModTime: modTime,
|
|
Size: f.Size(),
|
|
})
|
|
return nil
|
|
}
|
|
|
|
versionTime, err := time.ParseInLocation(TimeFormat, tag, time.Local)
|
|
if err != nil {
|
|
// Can't parse it, welp, continue
|
|
return nil
|
|
}
|
|
|
|
files[name] = append(files[name], FileVersion{
|
|
VersionTime: versionTime,
|
|
ModTime: modTime,
|
|
Size: f.Size(),
|
|
})
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return files, nil
|
|
}
|
|
|
|
type fileTagger func(string, string) string
|
|
|
|
func archiveFile(method fs.CopyRangeMethod, srcFs, dstFs fs.Filesystem, filePath string, tagger fileTagger) error {
|
|
filePath = osutil.NativeFilename(filePath)
|
|
info, err := srcFs.Lstat(filePath)
|
|
if fs.IsNotExist(err) {
|
|
l.Debugln("not archiving nonexistent file", filePath)
|
|
return nil
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
if info.IsSymlink() {
|
|
panic("bug: attempting to version a symlink")
|
|
}
|
|
|
|
_, err = dstFs.Stat(".")
|
|
if err != nil {
|
|
if fs.IsNotExist(err) {
|
|
slog.Debug("Creating versions dir")
|
|
err := dstFs.MkdirAll(".", 0o755)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_ = dstFs.Hide(".")
|
|
} else {
|
|
return err
|
|
}
|
|
}
|
|
|
|
file := filepath.Base(filePath)
|
|
inFolderPath := filepath.Dir(filePath)
|
|
err = dupDirTree(srcFs, dstFs, inFolderPath)
|
|
if err != nil {
|
|
l.Debugln("archiving", filePath, err)
|
|
return err
|
|
}
|
|
|
|
now := time.Now()
|
|
|
|
ver := tagger(file, now.Format(TimeFormat))
|
|
dst := filepath.Join(inFolderPath, ver)
|
|
l.Debugln("archiving", filePath, "moving to", dst)
|
|
err = osutil.RenameOrCopy(method, srcFs, dstFs, filePath, dst)
|
|
|
|
mtime := info.ModTime()
|
|
// If it's a trashcan versioner type thing, then it does not have version time in the name
|
|
// so use mtime for that.
|
|
if ver == file {
|
|
mtime = now
|
|
}
|
|
|
|
_ = dstFs.Chtimes(dst, mtime, mtime)
|
|
|
|
return err
|
|
}
|
|
|
|
func dupDirTree(srcFs, dstFs fs.Filesystem, folderPath string) error {
|
|
// Return early if the folder already exists.
|
|
_, err := dstFs.Stat(folderPath)
|
|
if err == nil || !fs.IsNotExist(err) {
|
|
return err
|
|
}
|
|
hadParent := true
|
|
for i := range folderPath {
|
|
if os.IsPathSeparator(folderPath[i]) {
|
|
// If the parent folder didn't exist, then this folder doesn't exist
|
|
// so we can skip the check
|
|
if hadParent {
|
|
_, err := dstFs.Stat(folderPath[:i])
|
|
if err == nil {
|
|
continue
|
|
}
|
|
if !fs.IsNotExist(err) {
|
|
return err
|
|
}
|
|
}
|
|
hadParent = false
|
|
err := dupDirWithPerms(srcFs, dstFs, folderPath[:i])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return dupDirWithPerms(srcFs, dstFs, folderPath)
|
|
}
|
|
|
|
func dupDirWithPerms(srcFs, dstFs fs.Filesystem, folderPath string) error {
|
|
srcStat, err := srcFs.Stat(folderPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// If we call Mkdir with srcStat.Mode(), we won't get the expected perms because of umask
|
|
// So, we create the folder with 0700, and then change the perms to the srcStat.Mode()
|
|
err = dstFs.Mkdir(folderPath, 0o700)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return dstFs.Chmod(folderPath, srcStat.Mode())
|
|
}
|
|
|
|
func restoreFile(method fs.CopyRangeMethod, src, dst fs.Filesystem, filePath string, versionTime time.Time, tagger fileTagger) error {
|
|
tag := versionTime.In(time.Local).Truncate(time.Second).Format(TimeFormat)
|
|
taggedFilePath := tagger(filePath, tag)
|
|
|
|
// If the something already exists where we are restoring to, archive existing file for versioning
|
|
// remove if it's a symlink, or fail if it's a directory
|
|
if info, err := dst.Lstat(filePath); err == nil {
|
|
switch {
|
|
case info.IsDir():
|
|
return ErrDirectory
|
|
case info.IsSymlink():
|
|
// Remove existing symlinks (as we don't want to archive them)
|
|
if err := dst.Remove(filePath); err != nil {
|
|
return fmt.Errorf("removing existing symlink: %w", err)
|
|
}
|
|
case info.IsRegular():
|
|
if err := archiveFile(method, dst, src, filePath, tagger); err != nil {
|
|
return fmt.Errorf("archiving existing file: %w", err)
|
|
}
|
|
default:
|
|
panic("bug: unknown item type")
|
|
}
|
|
} else if !fs.IsNotExist(err) {
|
|
return err
|
|
}
|
|
|
|
filePath = osutil.NativeFilename(filePath)
|
|
|
|
// Try and find a file that has the correct mtime
|
|
sourceFile := ""
|
|
sourceMtime := time.Time{}
|
|
if info, err := src.Lstat(taggedFilePath); err == nil && info.IsRegular() {
|
|
sourceFile = taggedFilePath
|
|
sourceMtime = info.ModTime()
|
|
} else if err == nil {
|
|
l.Debugln("restore:", taggedFilePath, "not regular")
|
|
} else {
|
|
l.Debugln("restore:", taggedFilePath, err.Error())
|
|
}
|
|
|
|
// Check for untagged file
|
|
if sourceFile == "" {
|
|
info, err := src.Lstat(filePath)
|
|
if err == nil && info.IsRegular() && info.ModTime().Truncate(time.Second).Equal(versionTime) {
|
|
sourceFile = filePath
|
|
sourceMtime = info.ModTime()
|
|
}
|
|
|
|
}
|
|
|
|
if sourceFile == "" {
|
|
return errNotFound
|
|
}
|
|
|
|
// Check that the target location of where we are supposed to restore does not exist.
|
|
// This should have been taken care of by the first few lines of this function.
|
|
if _, err := dst.Lstat(filePath); err == nil {
|
|
return errFileAlreadyExists
|
|
} else if !fs.IsNotExist(err) {
|
|
return err
|
|
}
|
|
|
|
_ = dst.MkdirAll(filepath.Dir(filePath), 0o755)
|
|
err := osutil.RenameOrCopy(method, src, dst, sourceFile, filePath)
|
|
_ = dst.Chtimes(filePath, sourceMtime, sourceMtime)
|
|
return err
|
|
}
|
|
|
|
func versionerFsFromFolderCfg(cfg config.FolderConfiguration) (versionsFs fs.Filesystem) {
|
|
folderFs := cfg.Filesystem()
|
|
if cfg.Versioning.FSPath == "" {
|
|
versionsFs = fs.NewFilesystem(folderFs.Type(), filepath.Join(folderFs.URI(), DefaultPath))
|
|
} else if cfg.Versioning.FSType == config.FilesystemTypeBasic {
|
|
// Expand any leading tildes for basic filesystems,
|
|
// before checking for absolute paths.
|
|
path, err := fs.ExpandTilde(cfg.Versioning.FSPath)
|
|
if err != nil {
|
|
path = cfg.Versioning.FSPath
|
|
}
|
|
// We only know how to deal with relative folders for
|
|
// basic filesystems, as that's the only one we know
|
|
// how to check if it's absolute or relative.
|
|
if !filepath.IsAbs(path) {
|
|
path = filepath.Join(folderFs.URI(), path)
|
|
}
|
|
versionsFs = fs.NewFilesystem(cfg.Versioning.FSType.ToFS(), path)
|
|
} else {
|
|
versionsFs = fs.NewFilesystem(cfg.Versioning.FSType.ToFS(), cfg.Versioning.FSPath)
|
|
}
|
|
l.Debugf("%s (%s) folder using %s (%s) versioner dir", folderFs.URI(), folderFs.Type(), versionsFs.URI(), versionsFs.Type())
|
|
return
|
|
}
|
|
|
|
func findAllVersions(fs fs.Filesystem, filePath string) []string {
|
|
inFolderPath := filepath.Dir(filePath)
|
|
file := filepath.Base(filePath)
|
|
|
|
// Glob according to the new file~timestamp.ext pattern.
|
|
pattern := filepath.Join(inFolderPath, TagFilename(file, timeGlob))
|
|
versions, err := fs.Glob(pattern)
|
|
if err != nil {
|
|
slog.Warn("Failed to glob for versions", slog.String("pattern", pattern), slogutil.Error(err))
|
|
return nil
|
|
}
|
|
versions = stringutil.UniqueTrimmedStrings(versions)
|
|
slices.Sort(versions)
|
|
|
|
return versions
|
|
}
|
|
|
|
func clean(ctx context.Context, versionsFs fs.Filesystem, toRemove func([]string, time.Time) []string) error {
|
|
l.Debugln("Versioner clean: Cleaning", versionsFs)
|
|
|
|
if _, err := versionsFs.Stat("."); fs.IsNotExist(err) {
|
|
// There is no need to clean a nonexistent dir.
|
|
return nil
|
|
}
|
|
|
|
versionsPerFile := make(map[string][]string)
|
|
dirTracker := make(emptyDirTracker)
|
|
|
|
walkFn := func(path string, f fs.FileInfo, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
default:
|
|
}
|
|
|
|
if f.IsDir() && !f.IsSymlink() {
|
|
dirTracker.addDir(path)
|
|
return nil
|
|
}
|
|
|
|
// Regular file, or possibly a symlink.
|
|
dirTracker.addFile(path)
|
|
|
|
name, _ := UntagFilename(path)
|
|
if name == "" {
|
|
return nil
|
|
}
|
|
|
|
versionsPerFile[name] = append(versionsPerFile[name], path)
|
|
|
|
return nil
|
|
}
|
|
|
|
if err := versionsFs.Walk(".", walkFn); err != nil {
|
|
if !errors.Is(err, context.Canceled) {
|
|
slog.WarnContext(ctx, "Failed to scan versions directory", slogutil.Error(err))
|
|
}
|
|
return err
|
|
}
|
|
|
|
for _, versionList := range versionsPerFile {
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
default:
|
|
}
|
|
cleanVersions(versionsFs, versionList, toRemove)
|
|
}
|
|
|
|
dirTracker.deleteEmptyDirs(versionsFs)
|
|
|
|
l.Debugln("Cleaner: Finished cleaning", versionsFs)
|
|
return nil
|
|
}
|
|
|
|
func cleanVersions(versionsFs fs.Filesystem, versions []string, toRemove func([]string, time.Time) []string) {
|
|
l.Debugln("Versioner: Expiring versions", versions)
|
|
for _, file := range toRemove(versions, time.Now()) {
|
|
if err := versionsFs.Remove(file); err != nil {
|
|
slog.Warn("Failed to remove versioned file during cleanup", slogutil.FilePath(file), slogutil.Error(err))
|
|
}
|
|
}
|
|
}
|