-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathservice.go
More file actions
323 lines (299 loc) · 8.21 KB
/
Copy pathservice.go
File metadata and controls
323 lines (299 loc) · 8.21 KB
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
package module
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"slices"
"github.com/leg100/pug/internal"
"github.com/leg100/pug/internal/logging"
"github.com/leg100/pug/internal/pubsub"
"github.com/leg100/pug/internal/resource"
"github.com/leg100/pug/internal/task"
)
type Service struct {
table moduleTable
tasks taskCreator
workdir internal.Workdir
pluginCache bool
logger logging.Interface
terragrunt bool
*pubsub.Broker[*Module]
}
type ServiceOptions struct {
Tasks *task.Service
Workdir internal.Workdir
PluginCache bool
Logger logging.Interface
Terragrunt bool
}
type taskCreator interface {
Create(spec task.Spec) (*task.Task, error)
}
type moduleTable interface {
Add(id resource.ID, row *Module)
Update(id resource.ID, updater func(existing *Module) error) (*Module, error)
Delete(id resource.ID)
Get(id resource.ID) (*Module, error)
List() []*Module
}
func NewService(opts ServiceOptions) *Service {
broker := pubsub.NewBroker[*Module](opts.Logger)
table := resource.NewTable(broker)
opts.Logger.AddArgsUpdater(&logging.ReferenceUpdater[*Module]{
Getter: table,
Name: "module",
Field: "ModuleID",
})
return &Service{
table: table,
Broker: broker,
tasks: opts.Tasks,
workdir: opts.Workdir,
pluginCache: opts.PluginCache,
logger: opts.Logger,
terragrunt: opts.Terragrunt,
}
}
// Reload searches the working directory recursively for modules and adds them
// to the store before pruning those that are currently stored but can no longer
// be found.
//
// TODO: separate into Load and Reload
func (s *Service) Reload() (added []string, removed []string, err error) {
ch, errc := find(context.TODO(), s.workdir)
var found []string
for ch != nil || errc != nil {
select {
case opts, ok := <-ch:
if !ok {
ch = nil
break
}
found = append(found, opts.Path)
// handle found module
if mod, err := s.GetByPath(opts.Path); errors.Is(err, resource.ErrNotFound) {
// Not found, so add to pug
mod := New(opts)
s.table.Add(mod.ID, mod)
added = append(added, opts.Path)
} else if err != nil {
s.logger.Error("reloading modules", "error", err)
} else {
// Update in-place; the backend may have changed.
s.table.Update(mod.ID, func(existing *Module) error {
existing.Backend = opts.Backend
return nil
})
}
case err, ok := <-errc:
if !ok {
errc = nil
break
}
if err != nil {
s.logger.Error("reloading modules", "error", err)
}
}
}
// Cleanup existing modules, removing those that are no longer to be found
for _, existing := range s.table.List() {
if !slices.Contains(found, existing.Path) {
s.table.Delete(existing.ID)
removed = append(removed, existing.Path)
}
}
s.logger.Info("reloaded modules", "added", added, "removed", removed)
if s.terragrunt {
if err := s.loadTerragruntDependencies(); err != nil {
s.logger.Error("loading terragrunt dependencies: %w", err)
}
}
return
}
func (s *Service) loadTerragruntDependencies() error {
task, err := s.tasks.Create(task.Spec{
Execution: task.Execution{
TerraformCommand: []string{"graph-dependencies"},
},
Wait: true,
})
if err != nil {
return err
}
return s.loadTerragruntDependenciesFromDigraph(task.NewReader(false))
}
func (s *Service) loadTerragruntDependenciesFromDigraph(r io.Reader) error {
results, err := parseTerragruntGraph(r)
if err != nil {
return fmt.Errorf("parsing terragrunt dependency graph: %w", err)
}
for path, depPaths := range results {
// If absolute path then convert to path relative to pug's working
// directory.
if filepath.IsAbs(path) {
var err error
if path, err = s.workdir.Rel(path); err != nil {
s.logger.Error("loading terragrunt dependencies", "error", err)
// Skip loading dependencies for this module
continue
}
}
// Retrieve module. If it cannot be found it is probably because the
// module is outside of pug's working directory, in which case classify
// it as a warning rather than an error.
mod, err := s.GetByPath(path)
if err != nil {
if errors.Is(err, resource.ErrNotFound) {
s.logger.Warn("loading terragrunt dependencies", "error", err)
} else {
s.logger.Error("loading terragrunt dependencies", "error", err)
}
// Skip handling dependencies for this module.
continue
}
// Convert dependency paths to module IDs
dependencyIDs := make([]resource.ID, 0, len(depPaths))
for _, path := range depPaths {
// If absolute path then convert to path relative to pug's working
// directory.
if filepath.IsAbs(path) {
var err error
if path, err = s.workdir.Rel(path); err != nil {
// Skip loading this dependency
return err
}
}
// Retrieve module. If it cannot be found it is probably because the
// module is outside of pug's working directory, in which case classify
// it as a warning rather than an error.
mod, err := s.GetByPath(path)
if err != nil {
if errors.Is(err, resource.ErrNotFound) {
s.logger.Warn("loading terragrunt dependency", "error", err)
} else {
s.logger.Error("loading terragrunt dependency", "error", err)
}
// Skip loading this dependency
continue
}
dependencyIDs = append(dependencyIDs, mod.ID)
}
s.table.Update(mod.ID, func(existing *Module) error {
existing.dependencies = dependencyIDs
return nil
})
}
return nil
}
const InitTask task.Identifier = "init"
// InitOptions configures a terraform init task.
type InitOptions struct {
// Upgrade adds the -upgrade flag.
Upgrade bool
// Reconfigure adds the -reconfigure flag.
Reconfigure bool
}
// Init invokes terraform init on the module.
func (s *Service) Init(moduleID resource.ID, opts InitOptions) (task.Spec, error) {
mod, err := s.table.Get(moduleID)
if err != nil {
return task.Spec{}, err
}
args := []string{"-input=false"}
if opts.Upgrade {
args = append(args, "-upgrade")
}
if opts.Reconfigure {
args = append(args, "-reconfigure")
}
spec := task.Spec{
ModuleID: mod.ID,
Path: mod.Path,
Identifier: InitTask,
Execution: task.Execution{
TerraformCommand: []string{"init"},
Args: args,
},
Blocking: true,
// The terraform plugin cache is not concurrency-safe, so only allow one
// init task to run at any given time.
Exclusive: s.pluginCache,
}
return spec, nil
}
func (s *Service) Format(moduleID resource.ID) (task.Spec, error) {
mod, err := s.table.Get(moduleID)
if err != nil {
return task.Spec{}, err
}
spec := task.Spec{
ModuleID: mod.ID,
Path: mod.Path,
Execution: task.Execution{
TerraformCommand: []string{"fmt"},
},
Immediate: true,
Short: true,
}
return spec, nil
}
func (s *Service) Validate(moduleID resource.ID) (task.Spec, error) {
mod, err := s.table.Get(moduleID)
if err != nil {
return task.Spec{}, err
}
spec := task.Spec{
ModuleID: mod.ID,
Path: mod.Path,
Execution: task.Execution{
TerraformCommand: []string{"validate"},
},
Immediate: true,
Short: true,
}
return spec, nil
}
func (s *Service) List() []*Module {
return s.table.List()
}
func (s *Service) Get(id resource.ID) (*Module, error) {
return s.table.Get(id)
}
func (s *Service) GetByPath(path string) (*Module, error) {
for _, mod := range s.table.List() {
if path == mod.Path {
return mod, nil
}
}
return nil, fmt.Errorf("%s: %w", path, resource.ErrNotFound)
}
// SetCurrent sets the current workspace for the module.
func (s *Service) SetCurrent(moduleID, workspaceID resource.ID) error {
_, err := s.table.Update(moduleID, func(existing *Module) error {
existing.CurrentWorkspaceID = workspaceID
return nil
})
return err
}
// Execute a program in a module's directory.
func (s *Service) Execute(moduleID resource.ID, program string, args ...string) (task.Spec, error) {
mod, err := s.table.Get(moduleID)
if err != nil {
return task.Spec{}, err
}
spec := task.Spec{
ModuleID: mod.ID,
Path: mod.Path,
Execution: task.Execution{
Program: program,
Args: args,
},
// We're executing an arbitrary program which could be performing
// mutually exclusive actions that prevent other tasks from running as
// expected, so we make it a blocking task to be on the safe side.
Blocking: true,
}
return spec, nil
}