/
service_apply.go
258 lines (228 loc) · 7.82 KB
/
service_apply.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
/*
Copyright (c) 2022-2023 NTT Communications Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package core
import (
"context"
"fmt"
"path/filepath"
"strings"
extgogit "github.com/go-git/go-git/v5"
"github.com/nttcom/kuesta/internal/gogit"
"github.com/nttcom/kuesta/internal/logger"
"github.com/nttcom/kuesta/internal/util"
"github.com/nttcom/kuesta/internal/validator"
"github.com/nttcom/kuesta/pkg/kuesta"
"go.uber.org/multierr"
)
type ServiceApplyCfg struct {
RootCfg
}
// Validate validates exposed fields according to the `validate` tag.
func (c *ServiceApplyCfg) Validate() error {
return validator.Validate(c)
}
// Mask returns the copy whose sensitive data are masked.
func (c *ServiceApplyCfg) Mask() *ServiceApplyCfg {
cc := *c
cc.RootCfg = *c.RootCfg.Mask()
return &cc
}
// RunServiceApply runs the main process of the `service apply` command.
func RunServiceApply(ctx context.Context, cfg *ServiceApplyCfg) error {
l := logger.FromContext(ctx)
l.Debugw("service apply called", "config", cfg.Mask())
git, err := gogit.NewGit(cfg.ConfigGitOptions())
if err != nil {
return fmt.Errorf("init git: %w", err)
}
w, err := git.Checkout()
if err != nil {
return fmt.Errorf("git checkout: %w", err)
}
stmap, err := w.Status()
if err != nil {
return fmt.Errorf("git status: %w", err)
}
if err := CheckGitStatus(stmap); err != nil {
return fmt.Errorf("check git status: %w", err)
}
scPlan := NewServiceCompilePlan(stmap, cfg.ConfigRootPath)
if scPlan.IsEmpty() {
l.Info("no services updated")
return nil
}
err = scPlan.Do(ctx,
func(ctx context.Context, sp kuesta.ServicePath) error {
l.Infow("deleting service config", "service", sp.Service, "keys", sp.Keys)
if _, err := w.Remove(sp.ServiceComputedDirPath(kuesta.ExcludeRoot)); err != nil {
return fmt.Errorf("git remove: %w", err)
}
return nil
},
func(ctx context.Context, sp kuesta.ServicePath) error {
l.Infow("compiling service config", "service", sp.Service, "keys", sp.Keys)
cfg := &ServiceCompileCfg{RootCfg: cfg.RootCfg, Service: sp.Service, Keys: sp.Keys}
if err := RunServiceCompile(ctx, cfg); err != nil {
return fmt.Errorf("service updating: %w", err)
}
if _, err := w.Add(sp.ServiceComputedDirPath(kuesta.ExcludeRoot)); err != nil {
return fmt.Errorf("git add: %w", err)
}
return nil
})
if err != nil {
return err
}
stmap, err = w.Status()
if err != nil {
return fmt.Errorf("git status %w", err)
}
dcPlan := NewDeviceCompositePlan(stmap, cfg.ConfigRootPath)
if dcPlan.IsEmpty() {
l.Info("no devices updated")
return nil
}
err = dcPlan.Do(ctx,
func(ctx context.Context, dp kuesta.DevicePath) error {
l.Infow("updating device config", "device", dp.Device)
cfg := &DeviceCompositeCfg{RootCfg: cfg.RootCfg, Device: dp.Device}
if err := RunDeviceComposite(ctx, cfg); err != nil {
return fmt.Errorf("device composite: %w", err)
}
if _, err := w.Add(dp.DeviceConfigPath(kuesta.ExcludeRoot)); err != nil {
return fmt.Errorf("git add: %w", err)
}
return nil
})
if err != nil {
return err
}
return nil
}
// CheckGitStatus checks all git tracked files are in the proper status for service apply operation.
func CheckGitStatus(stmap extgogit.Status) error {
var err error
for path, st := range stmap {
err = multierr.Append(err, CheckGitFileStatus(path, *st))
}
if err != nil {
return util.JoinErr("check git status:", err)
}
return nil
}
// CheckGitFileStatus checks the given file status is in the proper status for service apply operation.
func CheckGitFileStatus(path string, st extgogit.FileStatus) error {
dir, file := filepath.Split(path)
dir = strings.TrimRight(dir, string(filepath.Separator))
if strings.HasSuffix(dir, kuesta.DirComputed) {
if gogit.IsEitherWorktreeOrStagingTrackedAndChanged(st) {
return fmt.Errorf("changes in compilation result is not allowd, you need to reset it: %s", path)
}
}
if strings.HasPrefix(dir, kuesta.DirDevices) && file == kuesta.FileConfigCue {
if gogit.IsEitherWorktreeOrStagingTrackedAndChanged(st) {
return fmt.Errorf("changes in device config is not allowd, you need to reset it: %s", path)
}
}
if gogit.IsBothWorktreeAndStagingTrackedAndChanged(st) {
return fmt.Errorf("both worktree and staging are modified, only change in worktree or staging is allowed: %s", path)
}
if st.Worktree == extgogit.UpdatedButUnmerged {
return fmt.Errorf("updated but unmerged changes remain. you have to solve it in advance: %s", path)
}
return nil
}
type (
ServiceFunc func(ctx context.Context, sp kuesta.ServicePath) error
DeviceFunc func(ctx context.Context, sp kuesta.DevicePath) error
)
type ServiceCompilePlan struct {
update []kuesta.ServicePath
delete []kuesta.ServicePath
}
// NewServiceCompilePlan creates new ServiceCompilePlan from the given git file statuses.
func NewServiceCompilePlan(stmap extgogit.Status, root string) *ServiceCompilePlan {
plan := &ServiceCompilePlan{}
for path, st := range stmap {
if !gogit.IsTrackedAndChanged(st.Staging) {
continue
}
service, keys, err := kuesta.ParseServiceInputPath(path)
if err != nil {
continue
}
sp := kuesta.ServicePath{RootDir: root, Service: service, Keys: keys}
if st.Staging == extgogit.Deleted {
plan.delete = append(plan.delete, sp)
} else {
plan.update = append(plan.update, sp)
}
}
return plan
}
// Do executes given delete ServiceFunc and update ServiceFunc according to its execution plan.
func (p *ServiceCompilePlan) Do(ctx context.Context, deleteFunc ServiceFunc, updateFunc ServiceFunc) error {
for _, sp := range p.delete {
if err := deleteFunc(ctx, sp); err != nil {
return err
}
}
for _, sp := range p.update {
if err := updateFunc(ctx, sp); err != nil {
return err
}
}
return nil
}
// IsEmpty returns True when there are no planned targets.
func (p *ServiceCompilePlan) IsEmpty() bool {
return len(p.update)+len(p.delete) == 0
}
type DeviceCompositePlan struct {
composite []kuesta.DevicePath
}
// NewDeviceCompositePlan creates new DeviceCompositePlan from the given git file statuses.
func NewDeviceCompositePlan(stmap extgogit.Status, root string) *DeviceCompositePlan {
updated := util.NewSet[kuesta.DevicePath]()
for path, st := range stmap {
if st.Staging == extgogit.Unmodified {
continue
}
device, err := kuesta.ParseServiceComputedFilePath(path)
if err != nil {
continue
}
updated.Add(kuesta.DevicePath{RootDir: root, Device: device})
}
plan := &DeviceCompositePlan{composite: updated.List()}
return plan
}
// Do executes given composite DeviceFunc according to its execution plan.
func (p *DeviceCompositePlan) Do(ctx context.Context, compositeFunc DeviceFunc) error {
for _, dp := range p.composite {
if err := compositeFunc(ctx, dp); err != nil {
return err
}
}
return nil
}
// IsEmpty returns True when there are no planned targets.
func (p *DeviceCompositePlan) IsEmpty() bool {
return len(p.composite) == 0
}