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