/
helpers.go
324 lines (294 loc) · 9.66 KB
/
helpers.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
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
324
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2017 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package config
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
"strings"
"github.com/snapcore/snapd/jsonutil"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/snap"
)
var validKey = regexp.MustCompile("^(?:[a-z0-9]+-?)*[a-z](?:-?[a-z0-9])*$")
func ParseKey(key string) (subkeys []string, err error) {
if key == "" {
return []string{}, nil
}
subkeys = strings.Split(key, ".")
for _, subkey := range subkeys {
if !validKey.MatchString(subkey) {
return nil, fmt.Errorf("invalid option name: %q", subkey)
}
}
return subkeys, nil
}
func purgeNulls(config interface{}) interface{} {
switch config := config.(type) {
// map of json raw messages is the starting point for purgeNulls, this is the configuration we receive
case map[string]*json.RawMessage:
for k, v := range config {
if cfg := purgeNulls(v); cfg != nil {
config[k] = cfg.(*json.RawMessage)
} else {
delete(config, k)
}
}
case map[string]interface{}:
for k, v := range config {
if cfg := purgeNulls(v); cfg != nil {
config[k] = cfg
} else {
delete(config, k)
}
}
case *json.RawMessage:
if config == nil {
return nil
}
var configm interface{}
if err := jsonutil.DecodeWithNumber(bytes.NewReader(*config), &configm); err != nil {
panic(fmt.Errorf("internal error: cannot unmarshal configuration: %v", err))
}
if cfg := purgeNulls(configm); cfg != nil {
return jsonRaw(cfg)
}
return nil
}
return config
}
func PatchConfig(snapName string, subkeys []string, pos int, config interface{}, value *json.RawMessage) (interface{}, error) {
switch config := config.(type) {
case nil:
// Missing update map. Create and nest final value under it.
configm := make(map[string]interface{})
_, err := PatchConfig(snapName, subkeys, pos, configm, value)
if err != nil {
return nil, err
}
return configm, nil
case *json.RawMessage:
// Raw replaces pristine on commit. Unpack, update, and repack.
var configm map[string]interface{}
if err := jsonutil.DecodeWithNumber(bytes.NewReader(*config), &configm); err != nil {
return nil, fmt.Errorf("snap %q option %q is not a map", snapName, strings.Join(subkeys[:pos], "."))
}
// preserve the invariant that if PatchConfig is
// passed a map[string]interface{} it is not nil.
// If the value was set to null in the same
// transaction use (interface{})(nil) which is handled
// by the first case here.
// (see LP: #1920773)
var cfg interface{}
if configm != nil {
cfg = configm
}
result, err := PatchConfig(snapName, subkeys, pos, cfg, value)
if err != nil {
return nil, err
}
// PatchConfig may have recreated higher level element that was previously set to null in same
// transaction; returning the result for PatchConfig rather than just configm ensures we do
// support cases where a previously unset path is set back.
return jsonRaw(result), nil
case map[string]interface{}:
// Update map to apply against pristine on commit.
if pos+1 == len(subkeys) {
config[subkeys[pos]] = value
return config, nil
} else {
result, err := PatchConfig(snapName, subkeys, pos+1, config[subkeys[pos]], value)
if err != nil {
return nil, err
}
config[subkeys[pos]] = result
return config, nil
}
}
return nil, fmt.Errorf("internal error: unexpected configuration type %T", config)
}
// GetSnapConfig retrieves the raw configuration of a given snap.
func GetSnapConfig(st *state.State, snapName string) (*json.RawMessage, error) {
var config map[string]*json.RawMessage
err := st.Get("config", &config)
if errors.Is(err, state.ErrNoState) {
return nil, nil
}
if err != nil {
return nil, err
}
snapcfg, ok := config[snapName]
if !ok {
return nil, nil
}
return snapcfg, nil
}
// SetSnapConfig replaces the configuration of a given snap.
func SetSnapConfig(st *state.State, snapName string, snapcfg *json.RawMessage) error {
var config map[string]*json.RawMessage
err := st.Get("config", &config)
// empty nil snapcfg should be an empty message, but deal with "null" as well.
isNil := snapcfg == nil || len(*snapcfg) == 0 || bytes.Compare(*snapcfg, []byte("null")) == 0
if errors.Is(err, state.ErrNoState) {
if isNil {
// bail out early
return nil
}
config = make(map[string]*json.RawMessage, 1)
} else if err != nil {
return err
}
if isNil {
delete(config, snapName)
} else {
config[snapName] = snapcfg
}
st.Set("config", config)
return nil
}
// SaveRevisionConfig makes a copy of config -> snapSnape configuration into the versioned config.
// It doesn't do anything if there is no configuration for given snap in the state.
// The caller is responsible for locking the state.
func SaveRevisionConfig(st *state.State, snapName string, rev snap.Revision) error {
var config map[string]*json.RawMessage // snap => configuration
var revisionConfig map[string]map[string]*json.RawMessage // snap => revision => configuration
// Get current configuration of the snap from state
err := st.Get("config", &config)
if errors.Is(err, state.ErrNoState) {
return nil
} else if err != nil {
return fmt.Errorf("internal error: cannot unmarshal configuration: %v", err)
}
snapcfg, ok := config[snapName]
if !ok {
return nil
}
err = st.Get("revision-config", &revisionConfig)
if errors.Is(err, state.ErrNoState) {
revisionConfig = make(map[string]map[string]*json.RawMessage)
} else if err != nil {
return err
}
cfgs := revisionConfig[snapName]
if cfgs == nil {
cfgs = make(map[string]*json.RawMessage)
}
cfgs[rev.String()] = snapcfg
revisionConfig[snapName] = cfgs
st.Set("revision-config", revisionConfig)
return nil
}
// RestoreRevisionConfig restores a given revision of snap configuration into config -> snapName.
// If no configuration exists for given revision it does nothing (no error).
// The caller is responsible for locking the state.
func RestoreRevisionConfig(st *state.State, snapName string, rev snap.Revision) error {
var config map[string]*json.RawMessage // snap => configuration
var revisionConfig map[string]map[string]*json.RawMessage // snap => revision => configuration
err := st.Get("revision-config", &revisionConfig)
if errors.Is(err, state.ErrNoState) {
return nil
} else if err != nil {
return fmt.Errorf("internal error: cannot unmarshal revision-config: %v", err)
}
err = st.Get("config", &config)
if errors.Is(err, state.ErrNoState) {
config = make(map[string]*json.RawMessage)
} else if err != nil {
return fmt.Errorf("internal error: cannot unmarshal configuration: %v", err)
}
if cfg, ok := revisionConfig[snapName]; ok {
if revCfg, ok := cfg[rev.String()]; ok {
config[snapName] = revCfg
st.Set("config", config)
}
}
return nil
}
// DiscardRevisionConfig removes configuration snapshot of given snap/revision.
// If no configuration exists for given revision it does nothing (no error).
// The caller is responsible for locking the state.
func DiscardRevisionConfig(st *state.State, snapName string, rev snap.Revision) error {
var revisionConfig map[string]map[string]*json.RawMessage // snap => revision => configuration
err := st.Get("revision-config", &revisionConfig)
if errors.Is(err, state.ErrNoState) {
return nil
} else if err != nil {
return fmt.Errorf("internal error: cannot unmarshal revision-config: %v", err)
}
if revCfgs, ok := revisionConfig[snapName]; ok {
delete(revCfgs, rev.String())
if len(revCfgs) == 0 {
delete(revisionConfig, snapName)
} else {
revisionConfig[snapName] = revCfgs
}
st.Set("revision-config", revisionConfig)
}
return nil
}
// DeleteSnapConfig removed configuration of given snap from the state.
func DeleteSnapConfig(st *state.State, snapName string) error {
var config map[string]map[string]*json.RawMessage // snap => key => value
err := st.Get("config", &config)
if errors.Is(err, state.ErrNoState) {
return nil
} else if err != nil {
return fmt.Errorf("internal error: cannot unmarshal configuration: %v", err)
}
if _, ok := config[snapName]; ok {
delete(config, snapName)
st.Set("config", config)
}
return nil
}
// ConfSetter is an interface for setting of config values.
type ConfSetter interface {
Set(snapName, key string, value interface{}) error
}
// Patch sets values in cfg for the provided snap's configuration
// based on patch.
// patch keys can be dotted as the key argument to Set.
// The patch is applied according to the order of its keys sorted by depth,
// with top keys sorted first.
func Patch(cfg ConfSetter, snapName string, patch map[string]interface{}) error {
patchKeys := sortPatchKeysByDepth(patch)
for _, key := range patchKeys {
if err := cfg.Set(snapName, key, patch[key]); err != nil {
return err
}
}
return nil
}
func sortPatchKeysByDepth(patch map[string]interface{}) []string {
if len(patch) == 0 {
return nil
}
depths := make(map[string]int, len(patch))
keys := make([]string, 0, len(patch))
for k := range patch {
depths[k] = strings.Count(k, ".")
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return depths[keys[i]] < depths[keys[j]]
})
return keys
}