/
watcher.go
294 lines (267 loc) · 8.13 KB
/
watcher.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
//go:build !js && !wasm
// +build !js,!wasm
package plugin_compiler
import (
"context"
"crypto/sha256"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
debounce_fswatcher "github.com/aperturerobotics/util/debounce-fswatcher"
"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// Watcher watches a set of packages and re-generates an output plugin codegen
// and binary when the code files change.
type Watcher struct {
le *logrus.Entry
packageLookupPath string
packagePaths []string
}
// NewWatcher constructs a new watcher.
//
// Recognizes and replaces {buildHash} in the output filename.
// The output path should be output-plugin-dir/output-plugin-{buildHash}.cbus.so
func NewWatcher(le *logrus.Entry, packageLookupPath string, packagePaths []string) *Watcher {
return &Watcher{
le: le,
packagePaths: packagePaths,
packageLookupPath: packageLookupPath,
}
}
// WatchCompilePlugin watches and compiles package.
// Detects if the output with the same {buildHash} already exists.
// Replaces {buildHash} in output filename and in plugin binary version.
func (w *Watcher) WatchCompilePlugin(
ctx context.Context,
pluginCodegenPath string,
pluginOutputPath string,
pluginBinaryID string,
pluginBinaryVersion string,
compiledCb func(packages []string, outpPath string) error,
) error {
le := w.le
le.
WithField("codegen-path", pluginCodegenPath).
Info("hot: starting to build/watch plugin")
// hhBaseKey is the seed key to use for blake3 (32 bytes)
var hhBaseKey []byte
{
hs := sha256.New()
_, _ = hs.Write([]byte(pluginBinaryID))
_, _ = hs.Write([]byte(pluginOutputPath))
hhBaseKey = hs.Sum(nil)
}
// passOutputPath may or may not contain {buildHash}
compilePluginOnce := func(
ctx context.Context,
an *Analysis,
buildPrefix string,
passOutputPath string,
pluginBinaryVersion string,
) error {
moduleCompiler, err := NewModuleCompiler(
ctx,
w.le,
buildPrefix,
pluginCodegenPath,
pluginBinaryID,
)
if err != nil {
return err
}
if err := moduleCompiler.GenerateModules(an, pluginBinaryVersion); err != nil {
return err
}
err = moduleCompiler.CompilePlugin(passOutputPath)
moduleCompiler.Cleanup()
return err
}
compilePlugin := func() (*Analysis, error) {
rctx := ctx
ctx, compileCtxCancel := context.WithCancel(rctx)
defer compileCtxCancel()
le.
WithField("plugin-output-filename", path.Base(pluginOutputPath)).
Debugf("analyzing packages: %v", w.packagePaths)
an, err := AnalyzePackages(ctx, w.le, w.packageLookupPath, w.packagePaths)
if err != nil {
return nil, err
}
// pass 1: codegen + build with static build prefix.
passBinDir := filepath.Join(pluginCodegenPath, "bin")
if err := os.MkdirAll(passBinDir, 0o755); err != nil {
return nil, err
}
pass1OutputPath := filepath.Join(passBinDir, "pass1.cbus.so")
if err := compilePluginOnce(ctx, an, "pass1", pass1OutputPath, pluginBinaryVersion); err != nil {
return nil, err
}
buildHash, err := HashPluginForBuildID(hhBaseKey, pass1OutputPath)
if err != nil {
return nil, err
}
buildHashShort := buildHash[:16]
passBuildPluginVersion := strings.ReplaceAll(pluginBinaryVersion, buildHashConstTag, buildHashShort)
targetOutputPath := pluginOutputPath
if strings.Contains(targetOutputPath, buildHashConstTag) {
targetOutputPath = strings.ReplaceAll(targetOutputPath, buildHashConstTag, buildHashShort)
if _, err := os.Stat(targetOutputPath); !os.IsNotExist(err) {
le.Info("detected that output would be identical, skipping")
return an, nil
}
if err := CleanupOldVersions(le, pluginOutputPath); err != nil {
return an, err
}
}
// pass 2: codegen + build with the build hash
pass2OutputPath := filepath.Join(passBinDir, "pass2.cbus.so")
buildPrefix := "cbus-plugin-" + buildHashShort
if err := compilePluginOnce(ctx, an, buildPrefix, pass2OutputPath, passBuildPluginVersion); err != nil {
return an, err
}
if err := copyFileFromTo(pass2OutputPath, targetOutputPath); err != nil {
return an, err
}
if err == nil && compiledCb != nil {
err = compiledCb(w.packagePaths, targetOutputPath)
}
return an, err
}
for {
an, err := compilePlugin()
if err != nil {
return err
}
// ignoreWatchPrefixes are prefixes to ignore from watching
ignoreWatchPrefixes := []string{"vendor", "node_modules", ".bldr", "(disabled)"}
// build file watchlist
watchedFiles := make(map[string]struct{})
codefileMap := an.GetProgramCodeFiles(w.packagePaths, "")
for _, filePaths := range codefileMap {
FilePathLoop:
for _, filePath := range filePaths {
for _, prefix := range ignoreWatchPrefixes {
if strings.HasPrefix(filePath, prefix) {
continue FilePathLoop
}
}
watchedFiles[filePath] = struct{}{}
}
}
watchedSourcePaths := make(map[string]struct{}, len(watchedFiles))
watchedSourceDirs := make(map[string]struct{}, len(watchedFiles))
for filePath := range watchedFiles {
watchedSourcePaths[filePath] = struct{}{}
sourceDir := filepath.Dir(filePath)
if _, ok := watchedSourceDirs[sourceDir]; !ok {
watchedSourceDirs[sourceDir] = struct{}{}
}
}
le.Debugf(
"hot: watching %d packages with %d files",
len(w.packagePaths),
len(watchedFiles),
)
// It's best to watch the entire directory tree and filter the events.
//
// This is both more efficient on the kernel side and avoids nasty quriks
// with git and other editors deleting and re-creating files.
//
// See fsnotify comments:
// Watching individual files (rather than directories) is generally not
// recommended as many programs (especially editors) update files atomically: it
// will write to a temporary file which is then moved to to destination,
// overwriting the original (or some variant thereof). The watcher on the
// original file is now lost, as that no longer exists.
//
// It's necessary to create one watcher per directory:
// https://github.com/fsnotify/fsnotify/issues/18
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
for watchedDirPath := range watchedSourceDirs {
le.Infof("watching dir path: %s", watchedDirPath)
err = watcher.Add(watchedDirPath)
if err != nil {
_ = watcher.Close()
return err
}
}
// wait for a file change
happened, err := debounce_fswatcher.DebounceFSWatcherEvents(
ctx,
watcher,
time.Millisecond*500,
func(event fsnotify.Event) (match bool, err error) {
if _, ok := watchedSourcePaths[event.Name]; !ok {
return false, nil
}
return true, nil
},
)
_ = watcher.Close()
if err != nil {
return err
}
le.Infof("re-analyzing packages after %d filesystem events", len(happened))
}
}
// CleanupOldVersions cleans up old versions from the target path.
func CleanupOldVersions(le *logrus.Entry, pluginOutputPath string) error {
pluginOutputFilename := path.Base(pluginOutputPath)
pluginOutputDirectory := path.Dir(pluginOutputPath)
// cleanup old versions
if !strings.Contains(pluginOutputFilename, buildHashConstTag) {
return nil
}
pts := strings.Split(pluginOutputFilename, buildHashConstTag)
if len(pts) != 2 {
return errors.Errorf(
"expected one instance of %s but found %d",
buildHashConstTag,
len(pts)-1,
)
}
filenameRe, err := regexp.Compile(strings.Join([]string{
// match part 0
"(", regexp.QuoteMeta(pts[0]), ")",
// match build id
"([a-zA-Z0-9]*)",
// match part 1
"(", regexp.QuoteMeta(pts[1]), ")",
}, ""))
if err != nil {
return err
}
le.
WithField("filename-match-re", filenameRe.String()).
Debug("compilation complete, cleaning up old versions")
// list files in target dir
dirContents, err := os.ReadDir(pluginOutputDirectory)
if err != nil {
return err
}
for _, df := range dirContents {
if df.IsDir() || !df.Type().IsRegular() {
continue
}
dfName := df.Name()
if !filenameRe.MatchString(dfName) {
continue
}
dfBase := path.Base(dfName)
if err := os.RemoveAll(path.Join(pluginOutputDirectory, dfBase)); err != nil {
le.WithError(err).Warn("could not delete old version")
continue
} else {
le.Debugf("deleted old version: %s", dfBase)
}
}
return nil
}