-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
Copy pathbackend.go
262 lines (215 loc) · 6.13 KB
/
backend.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package inmem
import (
"errors"
"fmt"
"maps"
"os"
"sort"
"sync"
"time"
"github.com/zclconf/go-cty/cty"
"github.com/hashicorp/terraform/internal/backend"
"github.com/hashicorp/terraform/internal/backend/backendbase"
"github.com/hashicorp/terraform/internal/configs/configschema"
statespkg "github.com/hashicorp/terraform/internal/states"
"github.com/hashicorp/terraform/internal/states/remote"
"github.com/hashicorp/terraform/internal/states/statemgr"
"github.com/hashicorp/terraform/internal/tfdiags"
)
// we keep the states and locks in package-level variables, so that they can be
// accessed from multiple instances of the backend. This better emulates
// backend instances accessing a single remote data store.
var (
states stateMap
locks lockMap
)
func init() {
Reset()
}
// Reset clears out all existing state and lock data.
// This is used to initialize the package during init, as well as between
// tests.
func Reset() {
states = stateMap{
m: map[string]*remote.State{},
}
locks = lockMap{
m: map[string]*statemgr.LockInfo{},
}
}
// New creates a new backend for Inmem remote state.
//
// Currently the inmem backend is available for end users to use if they know it exists (it is not in any docs), but it was intended as a test resource.
// Making the inmem backend unavailable to end users and only available during tests is a breaking change.
// As a compromise for now, the inmem backend includes test-specific code that is enabled by setting the TF_INMEM_TEST environment variable.
// Test-specific behaviors include:
// * A more complex schema for testing code related to backend configurations
//
// Note: The alternative choice would be to add a duplicate of inmem in the codebase that's user-inaccessible, and this would be harder to maintain.
func New() backend.Backend {
if os.Getenv("TF_INMEM_TEST") != "" {
// We use a different schema for testing. This isn't user facing unless they
// dig into the code.
fmt.Println("TF_INMEM_TEST is set: Using test schema for the inmem backend")
return &Backend{
Base: backendbase.Base{
Schema: testSchema(),
},
}
}
// Default schema that's user-facing
return &Backend{
Base: backendbase.Base{
Schema: &configschema.Block{
Attributes: defaultSchemaAttrs,
},
},
}
}
var defaultSchemaAttrs = map[string]*configschema.Attribute{
"lock_id": {
Type: cty.String,
Optional: true,
Description: "initializes the state in a locked configuration",
},
}
func testSchema() *configschema.Block {
var newSchemaAttrs = make(map[string]*configschema.Attribute)
maps.Copy(newSchemaAttrs, defaultSchemaAttrs)
// Append test-specific attributes to the default attributes
newSchemaAttrs["test_nested_attr_single"] = &configschema.Attribute{
Description: "An attribute that contains nested attributes, where nesting mode is NestingSingle",
NestedType: &configschema.Object{
Nesting: configschema.NestingSingle,
Attributes: map[string]*configschema.Attribute{
"child": {
Type: cty.String,
Optional: true,
Description: "A nested attribute inside the parent attribute `test_nested_attr_single`",
},
},
},
}
return &configschema.Block{
Attributes: newSchemaAttrs,
}
}
type Backend struct {
backendbase.Base
}
func (b *Backend) Configure(configVal cty.Value) tfdiags.Diagnostics {
states.Lock()
defer states.Unlock()
defaultClient := &RemoteClient{
Name: backend.DefaultStateName,
}
states.m[backend.DefaultStateName] = &remote.State{
Client: defaultClient,
}
// set the default client lock info per the test config
if v := configVal.GetAttr("lock_id"); !v.IsNull() {
info := statemgr.NewLockInfo()
info.ID = v.AsString()
info.Operation = "test"
info.Info = "test config"
locks.lock(backend.DefaultStateName, info)
}
return nil
}
func (b *Backend) Workspaces() ([]string, error) {
states.Lock()
defer states.Unlock()
var workspaces []string
for s := range states.m {
workspaces = append(workspaces, s)
}
sort.Strings(workspaces)
return workspaces, nil
}
func (b *Backend) DeleteWorkspace(name string, _ bool) error {
states.Lock()
defer states.Unlock()
if name == backend.DefaultStateName || name == "" {
return fmt.Errorf("can't delete default state")
}
delete(states.m, name)
return nil
}
func (b *Backend) StateMgr(name string) (statemgr.Full, error) {
states.Lock()
defer states.Unlock()
s := states.m[name]
if s == nil {
s = &remote.State{
Client: &RemoteClient{
Name: name,
},
}
states.m[name] = s
// to most closely replicate other implementations, we are going to
// take a lock and create a new state if it doesn't exist.
lockInfo := statemgr.NewLockInfo()
lockInfo.Operation = "init"
lockID, err := s.Lock(lockInfo)
if err != nil {
return nil, fmt.Errorf("failed to lock inmem state: %s", err)
}
defer s.Unlock(lockID)
// If we have no state, we have to create an empty state
if v := s.State(); v == nil {
if err := s.WriteState(statespkg.NewState()); err != nil {
return nil, err
}
if err := s.PersistState(nil); err != nil {
return nil, err
}
}
}
return s, nil
}
type stateMap struct {
sync.Mutex
m map[string]*remote.State
}
// Global level locks for inmem backends.
type lockMap struct {
sync.Mutex
m map[string]*statemgr.LockInfo
}
func (l *lockMap) lock(name string, info *statemgr.LockInfo) (string, error) {
l.Lock()
defer l.Unlock()
lockInfo := l.m[name]
if lockInfo != nil {
lockErr := &statemgr.LockError{
Info: lockInfo,
}
lockErr.Err = errors.New("state locked")
// make a copy of the lock info to avoid any testing shenanigans
*lockErr.Info = *lockInfo
return "", lockErr
}
info.Created = time.Now().UTC()
l.m[name] = info
return info.ID, nil
}
func (l *lockMap) unlock(name, id string) error {
l.Lock()
defer l.Unlock()
lockInfo := l.m[name]
if lockInfo == nil {
return errors.New("state not locked")
}
lockErr := &statemgr.LockError{
Info: &statemgr.LockInfo{},
}
if id != lockInfo.ID {
lockErr.Err = errors.New("invalid lock id")
*lockErr.Info = *lockInfo
return lockErr
}
delete(l.m, name)
return nil
}