BlueGit

timfa bluegit

Files

bluegit / internal / server / admin_cache.go

admin_cache.go

admin_cache.go 5.3 KiB Download Raw
1package server
2
3import (
4 "encoding/json"
5 "errors"
6 "net/http"
7 "os"
8 "path/filepath"
9 "strconv"
10 "strings"
11
12 "gitlab.com/Timfa/bluegit/internal/i18n"
13 "gitlab.com/Timfa/bluegit/internal/readcache"
14 "gitlab.com/Timfa/bluegit/internal/state"
15)
16
17// cacheFile staat in de state-map en wint van config.yml, net als storage_path.
18const cacheFile = "cache.json"
19
20// CacheSetting is het gekozen cachepad. Leeg = geen cache.
21type CacheSetting struct {
22 Path string `json:"path"`
23 MaxMB int64 `json:"max_mb"`
24}
25
26func (s *Server) savedCache() (CacheSetting, bool) {
27 if s.StateDir == "" {
28 return CacheSetting{}, false
29 }
30 b, err := os.ReadFile(filepath.Join(s.StateDir, cacheFile))
31 if err != nil {
32 return CacheSetting{}, false
33 }
34 var c CacheSetting
35 if json.Unmarshal(b, &c) != nil {
36 return CacheSetting{}, false
37 }
38 return c, true
39}
40
41// CacheConfig is wat nu geldt: opgeslagen keuze, anders config/env.
42func (s *Server) CacheConfig() CacheSetting {
43 if c, ok := s.savedCache(); ok {
44 return c
45 }
46 return CacheSetting{Path: strings.TrimSpace(s.Cfg.CachePath), MaxMB: s.Cfg.CacheMaxMB}
47}
48
49// InitReadCache opent de cache bij het starten. Een fout zet de cache uit.
50func (s *Server) InitReadCache() {
51 c := s.CacheConfig()
52 if err := s.openCache(c); err != nil && s.Log != nil {
53 s.Log.Warn("leescache uit", "path", c.Path, "err", err)
54 }
55}
56
57func (s *Server) openCache(c CacheSetting) error {
58 if strings.TrimSpace(c.Path) == "" {
59 s.SetReadCache(nil)
60 return nil
61 }
62 if !filepath.IsAbs(c.Path) {
63 return i18n.E("err.cacheAbs")
64 }
65 rc, err := readcache.Open(c.Path, c.MaxMB<<20)
66 if err != nil {
67 s.SetReadCache(nil)
68 return err
69 }
70 s.SetReadCache(rc)
71 return nil
72}
73
74func (s *Server) opSetCache(path string, maxMB int64) error {
75 path = strings.TrimSpace(path)
76 if path != "" {
77 path = filepath.Clean(path)
78 if !filepath.IsAbs(path) {
79 return fail(400, i18n.E("err.cacheAbs"))
80 }
81 for _, other := range []string{s.StoragePath(), s.StateDir} {
82 if other != "" && (path == filepath.Clean(other) || strings.HasPrefix(path+"/", filepath.Clean(other)+"/")) {
83 return fail(400, i18n.E("err.cacheInside"))
84 }
85 }
86 if err := os.MkdirAll(filepath.Join(path, "cache"), 0o750); err != nil {
87 return fail(400, i18n.E("err.cacheDir", err.Error()))
88 }
89 probe, err := os.CreateTemp(filepath.Join(path, "cache"), ".tmp-probe-*")
90 if err != nil {
91 return fail(400, i18n.E("err.cacheDir", err.Error()))
92 }
93 probe.Close()
94 _ = os.Remove(probe.Name())
95 }
96 if maxMB < 0 {
97 maxMB = 0
98 }
99 c := CacheSetting{Path: path, MaxMB: maxMB}
100 if s.StateDir == "" {
101 return fail(400, errors.New("geen state-map"))
102 }
103 b, _ := json.Marshal(c)
104 tmp := filepath.Join(s.StateDir, cacheFile+".tmp")
105 if err := os.WriteFile(tmp, b, 0o640); err != nil {
106 return fail(500, err)
107 }
108 if err := os.Rename(tmp, filepath.Join(s.StateDir, cacheFile)); err != nil {
109 return fail(500, err)
110 }
111 if err := s.openCache(c); err != nil {
112 return fail(400, err)
113 }
114 return nil
115}
116
117// cacheInfo is de stand voor Beheer en de API.
118func (s *Server) cacheInfo() map[string]any {
119 c := s.CacheConfig()
120 u := s.ReadCache().Usage()
121 out := map[string]any{
122 "path": c.Path, "max_mb": c.MaxMB, "enabled": s.ReadCache() != nil,
123 "bytes": u.Bytes, "max_bytes": u.Max, "entries": u.Entries, "hits": u.Hits, "misses": u.Misses,
124 "locations": s.locations(),
125 "bytes_h": state.Format(uint64(u.Bytes)), "max_h": state.Format(uint64(u.Max)),
126 }
127 return out
128}
129
130// locations zegt waar wat staat, met het soort schijf.
131func (s *Server) locations() []map[string]string {
132 var out []map[string]string
133 add := func(what, p string) {
134 if p != "" {
135 out = append(out, map[string]string{"what": what, "path": p, "disk": state.DiskKind(p)})
136 }
137 }
138 add("database", filepath.Join(s.StateDir, "bluegit.db"))
139 add("logos", filepath.Join(s.StateDir, "logos"))
140 if st := s.StoragePath(); st != "" {
141 add("repos", filepath.Join(st, "repos"))
142 add("artifacts", filepath.Join(st, "artifacts"))
143 }
144 if c := s.ReadCache(); c != nil {
145 add("cache", c.Dir())
146 }
147 return out
148}
149
150func (s *Server) apiAdminCache(w http.ResponseWriter, r *http.Request) {
151 if !apiUser(r).InstanceAdmin {
152 s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
153 return
154 }
155 if r.Method == http.MethodPut {
156 var in CacheSetting
157 if err := readJSON(r, &in); err != nil {
158 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
159 return
160 }
161 if !s.apiOK(w, r, s.opSetCache(in.Path, in.MaxMB)) {
162 return
163 }
164 }
165 writeJSON(w, http.StatusOK, s.cacheInfo())
166}
167
168func (s *Server) apiAdminCacheClear(w http.ResponseWriter, r *http.Request) {
169 if !apiUser(r).InstanceAdmin {
170 s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
171 return
172 }
173 s.ReadCache().Clear()
174 writeJSON(w, http.StatusOK, s.cacheInfo())
175}
176
177func (s *Server) setupCacheSave(w http.ResponseWriter, r *http.Request) {
178 if _, ok := s.adminOnly(w, r); !ok || !s.csrfOK(w, r) {
179 return
180 }
181 maxMB, _ := strconv.ParseInt(strings.TrimSpace(r.FormValue("max_mb")), 10, 64)
182 if err := s.opSetCache(r.FormValue("cache_path"), maxMB); err != nil {
183 s.renderSetup(w, r, s.trErr(r, err), "")
184 return
185 }
186 s.redirect(w, r, "/setup", s.tr(r, "setup.cacheSaved"), "")
187}
188
189func (s *Server) setupCacheClear(w http.ResponseWriter, r *http.Request) {
190 if _, ok := s.adminOnly(w, r); !ok || !s.csrfOK(w, r) {
191 return
192 }
193 s.ReadCache().Clear()
194 s.redirect(w, r, "/setup", s.tr(r, "setup.cacheCleared"), "")
195}