-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathbind.go
More file actions
260 lines (229 loc) · 8.17 KB
/
Copy pathbind.go
File metadata and controls
260 lines (229 loc) · 8.17 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
package direct
import (
"context"
"fmt"
"os"
"strings"
"github.com/databricks/cli/bundle/config"
"github.com/databricks/cli/bundle/deployplan"
"github.com/databricks/cli/bundle/direct/dresources"
"github.com/databricks/cli/bundle/direct/dstate"
"github.com/databricks/cli/libs/log"
"github.com/databricks/cli/libs/structs/structaccess"
"github.com/databricks/cli/libs/structs/structpath"
"github.com/databricks/databricks-sdk-go"
)
// ErrResourceAlreadyBound is returned when attempting to bind a resource
// that is already bound to a different ID in the state.
type ErrResourceAlreadyBound struct {
ResourceKey string
ExistingID string
NewID string
}
func (e ErrResourceAlreadyBound) Error() string {
if e.ExistingID != e.NewID {
return fmt.Sprintf("Resource already managed\n\n"+
"The bundle is already managing a resource for %s with ID '%s'.\n"+
"To bind to a different resource with ID '%s', you must first unbind the existing resource.",
e.ResourceKey, e.ExistingID, e.NewID)
}
return fmt.Sprintf("Resource already managed\n\nThe bundle is already managing resource for %s and it is bound to the requested ID %s.",
e.ResourceKey, e.ExistingID)
}
// BindResult contains the result of a bind operation including any detected changes.
type BindResult struct {
// HasChanges is true if deploying after bind would make changes to the resource
HasChanges bool
// Action is the planned action for the bound resource (e.g., "skip", "update", "recreate")
Action deployplan.ActionType
// Plan contains the full deployment plan for the bound resource
Plan *deployplan.Plan
// TempStatePath is the path to the temporary state file
TempStatePath string
// StatePath is the path to the final state file
StatePath string
}
// Bind adds an existing workspace resource to a temporary state and calculates
// if there will be any changes when deploying.
//
// Flow:
// 1. Load current state file
// 2. Update id of the target resource
// 3. Update state path to temp file (state file + ".temp-bind")
// 4. Perform plan + update to populate state with resolved config
// 5. Calculate plan again - this is the plan presented to the user
//
// Call Finalize to commit the state or Cancel to discard.
func (b *DeploymentBundle) Bind(ctx context.Context, client *databricks.WorkspaceClient, configRoot *config.Root, statePath, resourceKey, resourceID string) (*BindResult, error) {
// Check if the resource is already managed (bound to a different ID)
var checkStateDB dstate.DeploymentState
if err := checkStateDB.Open(ctx, statePath, dstate.WithRecovery(true), dstate.WithWrite(false)); err == nil {
existingID := checkStateDB.GetResourceID(resourceKey)
if _, err := checkStateDB.Finalize(ctx); err != nil {
log.Warnf(ctx, "failed to finalize state: %v", err)
}
if existingID != "" {
return nil, ErrResourceAlreadyBound{
ResourceKey: resourceKey,
ExistingID: existingID,
NewID: resourceID,
}
}
}
tmpStatePath := statePath + ".temp-bind"
// Copy existing state to temp location if it exists
if data, err := os.ReadFile(statePath); err == nil {
if err := os.WriteFile(tmpStatePath, data, 0o600); err != nil {
return nil, err
}
}
// Open temp state
err := b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(false), dstate.WithWrite(true))
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
// Save state with ID and empty state (like migrate does)
err = b.StateDB.SaveState(resourceKey, resourceID, struct{}{}, nil)
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
// Finalize to persist temp state to disk
_, err = b.StateDB.Finalize(ctx)
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
log.Infof(ctx, "Bound %s to id=%s (in temp state)", resourceKey, resourceID)
// First plan + update: populate state with resolved config
err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(false))
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
plan, err := b.CalculatePlan(ctx, client, configRoot)
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
if _, err := b.StateDB.Finalize(ctx); err != nil {
log.Warnf(ctx, "failed to finalize state: %v", err)
}
// Populate the state with the resolved config
entry := plan.Plan[resourceKey]
sv, ok := b.StateCache.Load(resourceKey)
if ok && sv != nil {
var dependsOn []deployplan.DependsOnEntry
if entry != nil {
dependsOn = entry.DependsOn
}
// Copy etag from remote state for resources that use etag-based drift
// detection (dashboards and genie spaces). The etag is not provided by the
// user; it comes from remote. If we don't store it in state, we won't
// detect remote drift correctly and the next plan shows a bogus update.
if (strings.Contains(resourceKey, ".dashboards.") || strings.Contains(resourceKey, ".genie_spaces.")) && entry != nil && entry.RemoteState != nil {
etag, err := structaccess.Get(entry.RemoteState, structpath.NewStringKey(nil, "etag"))
if err == nil && etag != nil {
if etagStr, ok := etag.(string); ok && etagStr != "" {
_ = structaccess.Set(sv.Value, structpath.NewStringKey(nil, "etag"), etagStr)
}
}
}
adapter, err := b.getAdapterForKey(resourceKey)
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
compacted, err := dresources.CompactState(adapter.ResourceConfig(), sv.Value)
if err != nil {
os.Remove(tmpStatePath)
return nil, fmt.Errorf("compacting state: %w", err)
}
err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(true))
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
err = b.StateDB.SaveState(resourceKey, resourceID, compacted, dependsOn)
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
_, err = b.StateDB.Finalize(ctx)
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
}
// Second plan: this is the plan to present to the user (change between remote resource and config)
err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(false))
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
plan, err = b.CalculatePlan(ctx, client, configRoot)
if _, ferr := b.StateDB.Finalize(ctx); ferr != nil {
log.Warnf(ctx, "failed to finalize state: %v", ferr)
}
if err != nil {
os.Remove(tmpStatePath)
return nil, err
}
// Check if the bound resource has changes
result := &BindResult{
HasChanges: false,
Action: deployplan.Skip,
Plan: plan,
TempStatePath: tmpStatePath,
StatePath: statePath,
}
entry = plan.Plan[resourceKey]
if entry != nil {
result.Action = entry.Action
result.HasChanges = result.Action != deployplan.Skip && result.Action != deployplan.Undefined
}
return result, nil
}
// Finalize completes the bind operation by renaming the temp state to the final location.
func (result *BindResult) Finalize() error {
if result == nil || result.TempStatePath == "" {
return nil
}
return os.Rename(result.TempStatePath, result.StatePath)
}
// Cancel cleans up temp state without committing changes.
func (result *BindResult) Cancel() {
if result != nil && result.TempStatePath != "" {
os.Remove(result.TempStatePath)
}
}
// Unbind removes a resource from direct engine state without deleting
// the workspace resource. Also removes associated permissions/grants entries.
func (b *DeploymentBundle) Unbind(ctx context.Context, statePath, resourceKey string) error {
err := b.StateDB.Open(ctx, statePath, dstate.WithRecovery(true), dstate.WithWrite(true))
if err != nil {
return err
}
// Delete the main resource
err = b.StateDB.DeleteState(resourceKey)
if err != nil {
return err
}
log.Infof(ctx, "Unbound %s", resourceKey)
// Also delete associated permissions/grants if they exist
// These are stored as "resources.jobs.foo.permissions" or "resources.schemas.bar.grants"
permissionsKey := resourceKey + ".permissions"
grantsKey := resourceKey + ".grants"
for key := range b.StateDB.Data.State {
if key == permissionsKey || key == grantsKey || strings.HasPrefix(key, resourceKey+".") {
err = b.StateDB.DeleteState(key)
if err != nil {
return err
}
log.Infof(ctx, "Unbound %s", key)
}
}
_, err = b.StateDB.Finalize(ctx)
return err
}