/
autogit_manager.go
373 lines (329 loc) · 10.5 KB
/
autogit_manager.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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Copyright 2017 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libgit
import (
"context"
"os"
"sync"
lru "github.com/hashicorp/golang-lru"
"github.com/adamwalz/keybase-client/go/kbfs/data"
"github.com/adamwalz/keybase-client/go/kbfs/libfs"
"github.com/adamwalz/keybase-client/go/kbfs/libkbfs"
"github.com/adamwalz/keybase-client/go/kbfs/tlf"
"github.com/adamwalz/keybase-client/go/kbfs/tlfhandle"
"github.com/adamwalz/keybase-client/go/logger"
"github.com/adamwalz/keybase-client/go/protocol/keybase1"
"github.com/pkg/errors"
"gopkg.in/src-d/go-git.v4/plumbing"
)
const (
// Debug tag ID for an individual autogit operation
ctxAutogitOpID = "AGID"
)
type ctxAutogitTagKey int
const (
ctxAutogitIDKey ctxAutogitTagKey = iota
)
type browserCacheKey struct {
fs *libfs.FS
repoName string
branch plumbing.ReferenceName
subdir string
}
type browserCacheValue struct {
repoFS *libfs.FS
browser *Browser
}
// AutogitManager can clone and pull source git repos into a
// destination folder, potentially across different TLFs. New
// requests for an operation in a destination repo are blocked by any
// ongoing requests for the same folder, and multiple outstanding
// requests for the same destination folder get rolled up into one.
type AutogitManager struct {
config libkbfs.Config
log logger.Logger
deferLog logger.Logger
registryLock sync.RWMutex
registeredFBs map[data.FolderBranch]bool
repoNodesForWatchedIDs map[libkbfs.NodeID]*repoDirNode
watchedNodes []libkbfs.Node // preventing GC on the watched nodes
deleteCancels map[string]context.CancelFunc
shutdown bool
sharedInBrowserCache sharedInBrowserCache
browserLock sync.Mutex
browserCache *lru.Cache
doRemoveSelfCheckouts sync.Once
}
// NewAutogitManager constructs a new AutogitManager instance.
func NewAutogitManager(
config libkbfs.Config, browserCacheSize int) *AutogitManager {
log := config.MakeLogger("")
browserCache, err := lru.New(browserCacheSize)
if err != nil {
panic(err.Error())
}
sharedCache, err := newLRUSharedInBrowserCache()
if err != nil {
panic(err.Error())
}
return &AutogitManager{
config: config,
log: log,
deferLog: log.CloneWithAddedDepth(1),
registeredFBs: make(map[data.FolderBranch]bool),
repoNodesForWatchedIDs: make(map[libkbfs.NodeID]*repoDirNode),
deleteCancels: make(map[string]context.CancelFunc),
browserCache: browserCache,
sharedInBrowserCache: sharedCache,
}
}
// Shutdown shuts down this manager.
func (am *AutogitManager) Shutdown() {
am.registryLock.Lock()
defer am.registryLock.Unlock()
am.shutdown = true
for _, cancel := range am.deleteCancels {
cancel()
}
}
func (am *AutogitManager) removeOldCheckoutsForHandle(
ctx context.Context, h *tlfhandle.Handle, branch data.BranchName) {
// Make an "unwrapped" FS, so we don't end up recursively entering
// the virtual autogit nodes again.
fs, err := libfs.NewUnwrappedFS(
ctx, am.config, h, branch, "", "", keybase1.MDPriorityNormal)
if err != nil {
am.log.CDebugf(ctx, "Error making unwrapped FS for TLF %s: %+v",
h.GetCanonicalPath(), err)
return
}
fi, err := fs.Stat(AutogitRoot)
if os.IsNotExist(errors.Cause(err)) {
// No autogit repos to remove.
return
} else if err != nil {
am.log.CDebugf(ctx,
"Error checking autogit in unwrapped FS for TLF %s: %+v",
h.GetCanonicalPath(), err)
return
}
ctx, ok := func() (context.Context, bool) {
am.registryLock.Lock()
defer am.registryLock.Unlock()
if am.shutdown {
return nil, false
}
p := h.GetCanonicalPath()
if _, ok := am.deleteCancels[p]; ok {
return nil, false
}
ctx, cancel := context.WithCancel(ctx)
am.deleteCancels[p] = cancel
return ctx, true
}()
if !ok {
return
}
am.log.CDebugf(ctx, "Recursively deleting old autogit data in TLF %s",
h.GetCanonicalPath())
defer func() {
am.log.CDebugf(ctx, "Recursive delete of autogit done: %+v", err)
am.registryLock.Lock()
defer am.registryLock.Unlock()
delete(am.deleteCancels, h.GetCanonicalPath())
}()
err = libfs.RecursiveDelete(ctx, fs, fi)
}
func (am *AutogitManager) removeOldCheckouts(node libkbfs.Node) {
ctx := libkbfs.CtxWithRandomIDReplayable(
context.Background(), ctxAutogitIDKey, ctxAutogitOpID, am.log)
h, err := am.config.KBFSOps().GetTLFHandle(ctx, node)
if err != nil {
am.log.CDebugf(ctx, "Error getting handle: %+v", err)
return
}
am.removeOldCheckoutsForHandle(ctx, h, node.GetFolderBranch().Branch)
}
func (am *AutogitManager) removeSelfCheckouts() {
ctx := libkbfs.CtxWithRandomIDReplayable(
context.Background(), ctxAutogitIDKey, ctxAutogitOpID, am.log)
session, err := am.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
am.log.CDebugf(ctx,
"Unable to get session; ignoring self-autogit delete: +%v", err)
return
}
h, err := libkbfs.GetHandleFromFolderNameAndType(
ctx, am.config.KBPKI(), am.config.MDOps(),
am.config, string(session.Name), tlf.Private)
if err != nil {
am.log.CDebugf(ctx,
"Unable to get private handle; ignoring self-autogit delete: +%v",
err)
return
}
am.removeOldCheckoutsForHandle(ctx, h, data.MasterBranch)
}
func (am *AutogitManager) registerRepoNode(
nodeToWatch libkbfs.Node, rdn *repoDirNode) {
am.registryLock.Lock()
defer am.registryLock.Unlock()
am.repoNodesForWatchedIDs[nodeToWatch.GetID()] = rdn
fb := nodeToWatch.GetFolderBranch()
if am.registeredFBs[fb] {
return
}
go am.removeOldCheckouts(rdn)
am.doRemoveSelfCheckouts.Do(func() { go am.removeSelfCheckouts() })
am.watchedNodes = append(am.watchedNodes, nodeToWatch)
err := am.config.Notifier().RegisterForChanges(
[]data.FolderBranch{fb}, am)
if err != nil {
am.log.CWarningf(
context.TODO(), "Error registering %s: +%v", fb.Tlf, err)
return
}
am.registeredFBs[fb] = true
}
// LocalChange implements the libkbfs.Observer interface for AutogitManager.
func (am *AutogitManager) LocalChange(
ctx context.Context, node libkbfs.Node, wr libkbfs.WriteRange) {
// Do nothing.
}
func (am *AutogitManager) getNodesToInvalidate(
affectedNodeIDs []libkbfs.NodeID) (
nodes []libkbfs.Node, repoNodeIDs []libkbfs.NodeID) {
am.registryLock.RLock()
defer am.registryLock.RUnlock()
for _, nodeID := range affectedNodeIDs {
node, ok := am.repoNodesForWatchedIDs[nodeID]
if ok {
nodes = append(nodes, node)
repoNodeIDs = append(repoNodeIDs, nodeID)
}
}
return nodes, repoNodeIDs
}
func (am *AutogitManager) clearInvalidatedBrowsers(
repoNodeIDs []libkbfs.NodeID) {
am.browserLock.Lock()
defer am.browserLock.Unlock()
keys := am.browserCache.Keys()
for _, k := range keys {
// Clear all cached browsers associated with
tmp, ok := am.browserCache.Get(k)
if !ok {
continue
}
v, ok := tmp.(browserCacheValue)
if !ok {
continue
}
rootNodeID := v.repoFS.RootNode().GetID()
// Note that in almost all cases, `repoNodeIDs` should only
// have one entry (since only one repo is updated in a single
// metadata update), so iterating here should be cheaper than
// making a map.
for _, nodeID := range repoNodeIDs {
if rootNodeID == nodeID {
am.log.CDebugf(
context.TODO(), "Invalidating browser for %s",
v.repoFS.Root())
am.browserCache.Remove(k)
break
}
}
}
}
// BatchChanges implements the libkbfs.Observer interface for AutogitManager.
func (am *AutogitManager) BatchChanges(
ctx context.Context, _ []libkbfs.NodeChange,
affectedNodeIDs []libkbfs.NodeID) {
nodes, repoNodeIDs := am.getNodesToInvalidate(affectedNodeIDs)
go am.clearInvalidatedBrowsers(repoNodeIDs)
for _, node := range nodes {
node := node
go func() {
ctx := libkbfs.CtxWithRandomIDReplayable(
context.Background(), ctxAutogitIDKey, ctxAutogitOpID, am.log)
err := am.config.KBFSOps().InvalidateNodeAndChildren(ctx, node)
if err != nil {
am.log.CDebugf(ctx, "Error invalidating children: %+v", err)
}
}()
}
}
// TlfHandleChange implements the libkbfs.Observer interface for
// AutogitManager.
func (am *AutogitManager) TlfHandleChange(
ctx context.Context, newHandle *tlfhandle.Handle) {
// Do nothing.
}
func (am *AutogitManager) getBrowserForRepoLocked(
ctx context.Context, gitFS *libfs.FS, repoName string,
branch plumbing.ReferenceName, subdir string) (*libfs.FS, *Browser, error) {
repoName = normalizeRepoName(repoName)
key := browserCacheKey{gitFS, repoName, branch, subdir}
tmp, ok := am.browserCache.Get(key)
if ok {
b, ok := tmp.(browserCacheValue)
if !ok {
return nil, nil, errors.Errorf("Bad browser in cache: %T", tmp)
}
return b.repoFS, b.browser, nil
}
// It's kind of dumb to hold the browser lock through all of this,
// but it doesn't seem worthwhile to build the whole
// channel/notification system that would be needed to manage
// multiple concurrent requests for the same repo node.
am.log.CDebugf(ctx, "Making browser for repo=%s, branch=%s, subdir=%s",
repoName, branch, subdir)
// Recurse to get the root browser, and then chroot to the subdir.
if subdir != "" {
repoFS, rootB, err := am.getBrowserForRepoLocked(
ctx, gitFS, repoName, branch, "")
if err != nil {
return nil, nil, err
}
b, err := rootB.Chroot(subdir)
if err != nil {
return nil, nil, err
}
browser, ok := b.(*Browser)
if !ok {
return nil, nil, errors.Errorf("Bad browser type: %T", b)
}
am.browserCache.Add(key, browserCacheValue{repoFS, browser})
return repoFS, browser, nil
}
billyFS, err := gitFS.Chroot(repoName)
if err != nil {
return nil, nil, err
}
repoFS := billyFS.(*libfs.FS)
browser, err := NewBrowser(
repoFS, am.config.Clock(), branch, am.sharedInBrowserCache)
if err != nil {
return nil, nil, err
}
am.browserCache.Add(key, browserCacheValue{repoFS, browser})
return repoFS, browser, nil
}
// GetBrowserForRepo returns the root FS for the specified repo and a
// `Browser` for the branch and subdir.
func (am *AutogitManager) GetBrowserForRepo(
ctx context.Context, gitFS *libfs.FS, repoName string,
branch plumbing.ReferenceName, subdir string) (*libfs.FS, *Browser, error) {
am.browserLock.Lock()
defer am.browserLock.Unlock()
return am.getBrowserForRepoLocked(ctx, gitFS, repoName, branch, subdir)
}
// StartAutogit launches autogit, and returns a function that should
// be called on shutdown.
func StartAutogit(config libkbfs.Config, browserCacheSize int) func() {
am := NewAutogitManager(config, browserCacheSize)
rw := rootWrapper{am}
config.AddRootNodeWrapper(rw.wrap)
return am.Shutdown
}