-
Notifications
You must be signed in to change notification settings - Fork 4
/
config.go
303 lines (239 loc) · 8.25 KB
/
config.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
// Package config manages configuration parameters. It manages the configuration for
// the Windows Agent so that only a single config file needs to exist.
package config
import (
"context"
"crypto/sha512"
"encoding/base64"
"errors"
"fmt"
"path/filepath"
"sync"
log "github.com/canonical/ubuntu-pro-for-wsl/common/grpc/logstreamer"
"github.com/canonical/ubuntu-pro-for-wsl/windows-agent/internal/distros/database"
"github.com/ubuntu/decorate"
)
// Config manages configuration parameters. It is a wrapper around a dictionary
// that reads and updates the config file.
type Config struct {
// data
configState
// disk backing
storagePath string
// Sync
mu *sync.Mutex
// observers are notified after any configuration changes.
notifyLandsape LandscapeNotifier
notifyUbuntuPro UbuntuProNotifier
}
// UbuntuProNotifier is a function that is called when the Ubuntu Pro subscription changes.
type UbuntuProNotifier func(ctx context.Context, token string)
// LandscapeNotifier is a function that is called when the Landscape configuration changes.
type LandscapeNotifier func(ctx context.Context, config string, uid string)
// configState contains the actual configuration data.
//
// Its methods must be public for proper YAML (un)marshalling.
type configState struct {
Subscription subscription
Landscape landscapeConf
}
// New creates and initializes a new Config object.
func New(ctx context.Context, cachePath string) (m *Config) {
m = &Config{
storagePath: filepath.Join(cachePath, "config"),
mu: &sync.Mutex{},
// No-ops to avoid nil checks
notifyUbuntuPro: func(ctx context.Context, token string) {},
notifyLandsape: func(ctx context.Context, config string, uid string) {},
}
return m
}
// SetLandscapeNotifier sets the function to be called when the Landscape configuration changes.
func (c *Config) SetLandscapeNotifier(notify LandscapeNotifier) {
c.mu.Lock()
defer c.mu.Unlock()
c.notifyLandsape = notify
}
// SetUbuntuProNotifier sets the function to be called when the Ubuntu Pro subscription changes.
func (c *Config) SetUbuntuProNotifier(notify UbuntuProNotifier) {
c.mu.Lock()
defer c.mu.Unlock()
c.notifyUbuntuPro = notify
}
// Subscription returns the ProToken and the method it was acquired with (if any).
func (c *Config) Subscription() (token string, source Source, err error) {
s, err := c.get()
if err != nil {
return "", SourceNone, fmt.Errorf("config: could not get Ubuntu Pro subscription: %v", err)
}
token, source = s.Subscription.resolve()
return token, source, nil
}
// LandscapeClientConfig returns the value of the landscape server URL and
// the method it was acquired with (if any).
func (c *Config) LandscapeClientConfig() (string, Source, error) {
s, err := c.get()
if err != nil {
return "", SourceNone, fmt.Errorf("config: could not get Landscape configuration: %v", err)
}
conf, src := s.Landscape.resolve()
return conf, src, nil
}
// SetUserSubscription overwrites the value of the user-provided Ubuntu Pro token.
func (c *Config) SetUserSubscription(ctx context.Context, proToken string) (err error) {
defer decorate.OnError(&err, "config: could not set user-provided Ubuntu Pro subscription")
s, err := c.get()
if err != nil {
return fmt.Errorf("could not get exiting Ubuntu Pro subscription: %v", err)
}
if _, src := s.Subscription.resolve(); src > SourceUser {
return errors.New("higher priority subscription active")
}
isNew, err := c.set(&c.configState.Subscription.User, proToken)
if err != nil {
return err
}
if isNew {
c.notifyUbuntuPro(ctx, proToken)
}
return nil
}
// SetStoreSubscription overwrites the value of the store-provided Ubuntu Pro token.
func (c *Config) SetStoreSubscription(ctx context.Context, proToken string) (err error) {
defer decorate.OnError(&err, "could not set Microsoft-Store-provided Ubuntu Pro subscription")
s, err := c.get()
if err != nil {
return fmt.Errorf("could not get exiting Ubuntu Pro subscription: %v", err)
}
if _, src := s.Subscription.resolve(); src > SourceMicrosoftStore {
return errors.New("higher priority subscription active")
}
isNew, err := c.set(&c.configState.Subscription.Store, proToken)
if err != nil {
return err
}
if isNew {
c.notifyUbuntuPro(ctx, proToken)
}
return nil
}
// SetUserLandscapeConfig overwrites the value of the user-provided Landscape configuration.
func (c *Config) SetUserLandscapeConfig(ctx context.Context, landscapeConfig string) error {
if _, src := c.Landscape.resolve(); src > SourceUser {
return errors.New("attempted to set a user-provided landscape configuration when there already is a higher priority one")
}
isNew, err := c.set(&c.Landscape.UserConfig, landscapeConfig)
if err != nil {
return errors.New("config: could not set Landscape configuration")
}
if isNew {
c.notifyLandsape(ctx, landscapeConfig, c.Landscape.UID)
}
return nil
}
// SetLandscapeAgentUID overrides the Landscape agent UID.
func (c *Config) SetLandscapeAgentUID(uid string) error {
if _, err := c.set(&c.Landscape.UID, uid); err != nil {
return fmt.Errorf("config: could not set Landscape agent UID: %v", err)
}
return nil
}
func (c *Config) get() (s configState, err error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.load(); err != nil {
return s, err
}
return c.configState, nil
}
// set is a generic method to safely modify the config.
func (c *Config) set(field *string, value string) (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.load(); err != nil {
return false, err
}
old := *field
if old == value {
return false, nil
}
*field = value
if err := c.dump(); err != nil {
*field = old
return false, err
}
return true, nil
}
// LandscapeAgentUID returns the UID assigned to this agent by the Landscape server.
// An empty string is returned if no UID has been assigned.
func (c *Config) LandscapeAgentUID() (string, error) {
s, err := c.get()
if err != nil {
return "", fmt.Errorf("config: could not get Landscape agent UID: %v", err)
}
// We do not notify Landscape to avoid a potential infinite loop:
// 1. Start connection
// 2. Get UID
// 3. Notify Landscape
// 4. Landcape drops connection, and reconnects
return s.Landscape.UID, nil
}
// RegistryData contains the data that the Ubuntu Pro registry key can provide.
type RegistryData struct {
UbuntuProToken, LandscapeConfig string
}
// UpdateRegistryData takes in data from the registry and applies it as necessary.
func (c *Config) UpdateRegistryData(ctx context.Context, data RegistryData, db *database.DistroDB) (err error) {
defer decorate.OnError(&err, "config: could not update registry-provided data")
// We must perform the notification outside the lock to avoid deadlocks
afterUnlock := []func(){}
defer func() {
for _, f := range afterUnlock {
f()
}
}()
c.mu.Lock()
defer c.mu.Unlock()
if err := c.load(); err != nil {
return err
}
// Ubuntu Pro subscription
c.configState.Subscription.Organization = data.UbuntuProToken
if hasChanged(data.UbuntuProToken, &c.configState.Subscription.Checksum) {
log.Debug(ctx, "Config: new Ubuntu Pro subscription received from the registry")
// We must resolve the subscription in case a lower priority token becomes active
resolv, _ := c.configState.Subscription.resolve()
afterUnlock = append(afterUnlock, func() {
c.notifyUbuntuPro(ctx, resolv)
})
}
// Landscape configuration
c.Landscape.OrgConfig = data.LandscapeConfig
checksumInput := data.LandscapeConfig + c.Landscape.UID
if hasChanged(checksumInput, &c.Landscape.Checksum) {
log.Debug(ctx, "Config: new Landscape configuration received from the registry")
// We must resolve the landscape config in case a lower priority config becomes active
resolv, _ := c.Landscape.resolve()
afterUnlock = append(afterUnlock, func() {
c.notifyLandsape(ctx, resolv, c.Landscape.UID)
})
}
if err := c.dump(); err != nil {
return err
}
return nil
}
// hasChanged detects if the current value is different from the last time it was used.
// If the value has changed, the checksum will be updated.
func hasChanged(newValue string, checksum *string) bool {
var newCheckSum string
if len(newValue) != 0 {
raw := sha512.Sum512([]byte(newValue))
newCheckSum = base64.StdEncoding.EncodeToString(raw[:])
}
if *checksum == newCheckSum {
return false
}
*checksum = newCheckSum
return true
}