repo_cache.go

  1package cache
  2
  3import (
  4	"fmt"
  5	"io"
  6	"io/ioutil"
  7	"os"
  8	"path"
  9	"path/filepath"
 10	"strconv"
 11	"sync"
 12
 13	"github.com/MichaelMure/git-bug/bug"
 14	"github.com/MichaelMure/git-bug/entity"
 15	"github.com/MichaelMure/git-bug/identity"
 16	"github.com/MichaelMure/git-bug/repository"
 17	"github.com/MichaelMure/git-bug/util/process"
 18)
 19
 20// 1: original format
 21// 2: added cache for identities with a reference in the bug cache
 22const formatVersion = 2
 23
 24const lruCacheSize = 100
 25
 26var _ repository.RepoCommon = &RepoCache{}
 27
 28// RepoCache is a cache for a Repository. This cache has multiple functions:
 29//
 30// 1. After being loaded, a Bug is kept in memory in the cache, allowing for fast
 31// 		access later.
 32// 2. The cache maintain in memory and on disk a pre-digested excerpt for each bug,
 33// 		allowing for fast querying the whole set of bugs without having to load
 34//		them individually.
 35// 3. The cache guarantee that a single instance of a Bug is loaded at once, avoiding
 36// 		loss of data that we could have with multiple copies in the same process.
 37// 4. The same way, the cache maintain in memory a single copy of the loaded identities.
 38//
 39// The cache also protect the on-disk data by locking the git repository for its
 40// own usage, by writing a lock file. Of course, normal git operations are not
 41// affected, only git-bug related one.
 42type RepoCache struct {
 43	// the underlying repo
 44	repo repository.ClockedRepo
 45
 46	// the name of the repository, as defined in the MultiRepoCache
 47	name string
 48
 49	muBug sync.RWMutex
 50	// excerpt of bugs data for all bugs
 51	bugExcerpts map[entity.Id]*BugExcerpt
 52	// bug loaded in memory
 53	bugs map[entity.Id]*BugCache
 54
 55	// presentBugs is an LRU cache that records which bugs the cache has loaded in
 56	presentBugs *LRUIdCache
 57
 58	muIdentity sync.RWMutex
 59	// excerpt of identities data for all identities
 60	identitiesExcerpts map[entity.Id]*IdentityExcerpt
 61	// identities loaded in memory
 62	identities map[entity.Id]*IdentityCache
 63
 64	// the user identity's id, if known
 65	userIdentityId entity.Id
 66}
 67
 68func NewRepoCache(r repository.ClockedRepo) (*RepoCache, error) {
 69	return NewNamedRepoCache(r, "")
 70}
 71
 72func NewNamedRepoCache(r repository.ClockedRepo, name string) (*RepoCache, error) {
 73	c := &RepoCache{
 74		repo:       r,
 75		name:       name,
 76		bugs:       make(map[entity.Id]*BugCache),
 77		identities: make(map[entity.Id]*IdentityCache),
 78	}
 79
 80	err := c.lock()
 81	if err != nil {
 82		return &RepoCache{}, err
 83	}
 84
 85	err = c.load()
 86	if err == nil {
 87		return c, nil
 88	}
 89
 90	// Cache is either missing, broken or outdated. Rebuilding.
 91	err = c.buildCache()
 92	if err != nil {
 93		return nil, err
 94	}
 95
 96	return c, c.write()
 97}
 98
 99// load will try to read from the disk all the cache files
100func (c *RepoCache) load() error {
101	err := c.loadBugCache()
102	if err != nil {
103		return err
104	}
105	return c.loadIdentityCache()
106}
107
108// write will serialize on disk all the cache files
109func (c *RepoCache) write() error {
110	err := c.writeBugCache()
111	if err != nil {
112		return err
113	}
114	return c.writeIdentityCache()
115}
116
117func (c *RepoCache) lock() error {
118	lockPath := repoLockFilePath(c.repo)
119
120	err := repoIsAvailable(c.repo)
121	if err != nil {
122		return err
123	}
124
125	err = os.MkdirAll(filepath.Dir(lockPath), 0777)
126	if err != nil {
127		return err
128	}
129
130	f, err := os.Create(lockPath)
131	if err != nil {
132		return err
133	}
134
135	pid := fmt.Sprintf("%d", os.Getpid())
136	_, err = f.WriteString(pid)
137	if err != nil {
138		return err
139	}
140
141	return f.Close()
142}
143
144func (c *RepoCache) Close() error {
145	c.muBug.Lock()
146	defer c.muBug.Unlock()
147	c.muIdentity.Lock()
148	defer c.muIdentity.Unlock()
149
150	c.identities = make(map[entity.Id]*IdentityCache)
151	c.identitiesExcerpts = nil
152	c.bugs = nil
153	c.bugExcerpts = nil
154
155	lockPath := repoLockFilePath(c.repo)
156	return os.Remove(lockPath)
157}
158
159func (c *RepoCache) buildCache() error {
160	c.muBug.Lock()
161	defer c.muBug.Unlock()
162	c.muIdentity.Lock()
163	defer c.muIdentity.Unlock()
164
165	_, _ = fmt.Fprintf(os.Stderr, "Building identity cache... ")
166
167	c.identitiesExcerpts = make(map[entity.Id]*IdentityExcerpt)
168
169	allIdentities := identity.ReadAllLocalIdentities(c.repo)
170
171	for i := range allIdentities {
172		if i.Err != nil {
173			return i.Err
174		}
175
176		c.identitiesExcerpts[i.Identity.Id()] = NewIdentityExcerpt(i.Identity)
177	}
178
179	_, _ = fmt.Fprintln(os.Stderr, "Done.")
180
181	_, _ = fmt.Fprintf(os.Stderr, "Building bug cache... ")
182
183	presentBugs, err := NewLRUIdCache(lruCacheSize, c.onEvict)
184	if err != nil {
185		return err
186	}
187	c.presentBugs = presentBugs
188
189	c.bugExcerpts = make(map[entity.Id]*BugExcerpt)
190
191	allBugs := bug.ReadAllLocalBugs(c.repo)
192
193	for i := 0; i < lruCacheSize; i++ {
194		if len(allBugs) == 0 {
195			break
196		}
197
198		b := <-allBugs
199		if b.Err != nil {
200			return b.Err
201		}
202
203		snap := b.Bug.Compile()
204		c.bugExcerpts[b.Bug.Id()] = NewBugExcerpt(b.Bug, &snap)
205	}
206
207	_, _ = fmt.Fprintln(os.Stderr, "Done.")
208	return nil
209}
210
211func repoLockFilePath(repo repository.Repo) string {
212	return path.Join(repo.GetPath(), "git-bug", lockfile)
213}
214
215// repoIsAvailable check is the given repository is locked by a Cache.
216// Note: this is a smart function that will cleanup the lock file if the
217// corresponding process is not there anymore.
218// If no error is returned, the repo is free to edit.
219func repoIsAvailable(repo repository.Repo) error {
220	lockPath := repoLockFilePath(repo)
221
222	// Todo: this leave way for a racey access to the repo between the test
223	// if the file exist and the actual write. It's probably not a problem in
224	// practice because using a repository will be done from user interaction
225	// or in a context where a single instance of git-bug is already guaranteed
226	// (say, a server with the web UI running). But still, that might be nice to
227	// have a mutex or something to guard that.
228
229	// Todo: this will fail if somehow the filesystem is shared with another
230	// computer. Should add a configuration that prevent the cleaning of the
231	// lock file
232
233	f, err := os.Open(lockPath)
234
235	if err != nil && !os.IsNotExist(err) {
236		return err
237	}
238
239	if err == nil {
240		// lock file already exist
241		buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
242		if err != nil {
243			return err
244		}
245		if len(buf) == 10 {
246			return fmt.Errorf("the lock file should be < 10 bytes")
247		}
248
249		pid, err := strconv.Atoi(string(buf))
250		if err != nil {
251			return err
252		}
253
254		if process.IsRunning(pid) {
255			return fmt.Errorf("the repository you want to access is already locked by the process pid %d", pid)
256		}
257
258		// The lock file is just laying there after a crash, clean it
259
260		fmt.Println("A lock file is present but the corresponding process is not, removing it.")
261		err = f.Close()
262		if err != nil {
263			return err
264		}
265
266		err = os.Remove(lockPath)
267		if err != nil {
268			return err
269		}
270	}
271
272	return nil
273}