/
caching.go
80 lines (63 loc) · 2.18 KB
/
caching.go
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
package repo
import (
"context"
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/kopia/kopia/repo/content"
)
// GetCachingOptions reads caching configuration for a given repository.
func GetCachingOptions(ctx context.Context, configFile string) (*content.CachingOptions, error) {
lc, err := LoadConfigFromFile(configFile)
if err != nil {
return nil, err
}
return lc.Caching.CloneOrDefault(), nil
}
// SetCachingOptions changes caching configuration for a given repository.
func SetCachingOptions(ctx context.Context, configFile string, opt *content.CachingOptions) error {
lc, err := LoadConfigFromFile(configFile)
if err != nil {
return err
}
if err = setupCachingOptionsWithDefaults(ctx, configFile, lc, opt, nil); err != nil {
return errors.Wrap(err, "unable to set up caching")
}
return lc.writeToFile(configFile)
}
func setupCachingOptionsWithDefaults(ctx context.Context, configPath string, lc *LocalConfig, opt *content.CachingOptions, uniqueID []byte) error {
opt = opt.CloneOrDefault()
if opt.MaxCacheSizeBytes == 0 {
lc.Caching = &content.CachingOptions{}
return nil
}
if lc.Caching == nil {
lc.Caching = &content.CachingOptions{}
}
if opt.CacheDirectory == "" {
cacheDir, err := os.UserCacheDir()
if err != nil {
return errors.Wrap(err, "unable to determine cache directory")
}
h := sha256.New()
h.Write(uniqueID)
h.Write([]byte(configPath))
lc.Caching.CacheDirectory = filepath.Join(cacheDir, "kopia", hex.EncodeToString(h.Sum(nil))[0:16])
} else {
d, err := filepath.Abs(opt.CacheDirectory)
if err != nil {
return errors.Wrap(err, "unable to determine absolute cache path")
}
lc.Caching.CacheDirectory = d
}
lc.Caching.MaxCacheSizeBytes = opt.MaxCacheSizeBytes
lc.Caching.MaxMetadataCacheSizeBytes = opt.MaxMetadataCacheSizeBytes
lc.Caching.MaxListCacheDuration = opt.MaxListCacheDuration
lc.Caching.MinContentSweepAge = opt.MinContentSweepAge
lc.Caching.MinMetadataSweepAge = opt.MinMetadataSweepAge
lc.Caching.MinIndexSweepAge = opt.MinIndexSweepAge
log(ctx).Debugf("Creating cache directory '%v' with max size %v", lc.Caching.CacheDirectory, lc.Caching.MaxCacheSizeBytes)
return nil
}