-
Notifications
You must be signed in to change notification settings - Fork 28
/
main.go
378 lines (332 loc) · 9.08 KB
/
main.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Copyright 2023 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/mendersoftware/go-lib-micro/config"
"github.com/mendersoftware/go-lib-micro/log"
"github.com/pkg/errors"
"github.com/urfave/cli"
cinv "github.com/mendersoftware/deviceauth/client/inventory"
"github.com/mendersoftware/deviceauth/client/orchestrator"
"github.com/mendersoftware/deviceauth/client/tenant"
"github.com/mendersoftware/deviceauth/cmd"
dconfig "github.com/mendersoftware/deviceauth/config"
"github.com/mendersoftware/deviceauth/store/mongo"
)
const (
cliDefaultRateLimit = 50
)
func main() {
doMain(os.Args)
}
func doMain(args []string) {
var configPath string
var debug bool
app := cli.NewApp()
app.Usage = "Device Authentication Service"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "config",
Usage: "Configuration `FILE`." +
" Supports JSON, TOML, YAML and HCL formatted configs.",
Destination: &configPath,
},
cli.BoolFlag{
Name: "debug",
Usage: "Enable debug logging",
Destination: &debug,
},
}
app.Commands = []cli.Command{
{
Name: "server",
Usage: "Run the service as a server",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "automigrate",
Usage: "Run database migrations before starting.",
},
},
Action: cmdServer,
},
{
Name: "migrate",
Usage: "Run migrations and exit",
Flags: []cli.Flag{
cli.StringFlag{
Name: "tenant",
Usage: "Tenant ID (optional).",
},
cli.BoolFlag{
Name: "list-tenants",
Usage: "List Tenant IDs. Not performing migrations.",
},
},
Action: cmdMigrate,
},
{
Name: "propagate-inventory-statuses",
Usage: "Push device statuses to inventory",
Flags: []cli.Flag{
cli.StringFlag{
Name: "tenant_id",
Usage: "Tenant ID (optional) - propagate for just a single tenant.",
},
cli.StringFlag{
Name: "force-set-migration",
Usage: "Migration version to be stored in migration_info collection.",
},
cli.BoolFlag{
Name: "dry-run",
Usage: "Do not perform any inventory modifications," +
" just scan and print devices.",
},
},
Action: cmdPropagateStatusesInventory,
},
{
Name: "propagate-inventory-id-data",
Usage: "Push device id_data to inventory",
Flags: []cli.Flag{
cli.StringFlag{
Name: "tenant_id",
Usage: "Tenant ID (optional) - propagate for just a single tenant.",
},
cli.BoolFlag{
Name: "dry-run",
Usage: "Do not perform any inventory modifications," +
" just scan and print devices.",
},
},
Action: cmdPropagateIdDataInventory,
},
{
Name: "propagate-reporting",
Usage: "Trigger a reindex of all the devices in the reporting services ",
Flags: []cli.Flag{
cli.StringFlag{
Name: "tenant_id",
Usage: "Tenant ID (optional) - propagate for just a single tenant.",
},
cli.UintFlag{
Name: "rate-limit",
Usage: "`N`umber of reindexing batch requests per second.",
Value: cliDefaultRateLimit,
},
cli.BoolFlag{
Name: "dry-run",
Usage: "Do not perform any inventory modifications," +
" just scan and print devices.",
},
},
Action: cmdPropagateReporting,
},
{
Name: "maintenance",
Usage: "Run maintenance operations and exit",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "decommissioning-cleanup",
Usage: "Cleanup devauth database from leftovers after failed decommissioning",
},
cli.StringFlag{
Name: "tenant",
Usage: "Tenant ID (optional).",
},
cli.BoolFlag{
Name: "dry-run",
Usage: "Do not perform any modifications and serves" +
" only as a way to inspect changes and detect if any are necessary",
},
},
Action: cmdMaintenance,
}, {
Name: "check-device-limits",
Usage: "Warn users if user is approaching device limit",
Description: "Loops through all tenant databases and " +
"checks if the number of devices is over a " +
"threshold of the allowed limit and sends an " +
"email asking the user to upgrade or decomission" +
"unused devices.",
Flags: []cli.Flag{
cli.Float64Flag{
Name: "threshold, t",
Value: 90.0,
Usage: "Threshold in percent (%) of " +
"device limit that trigger " +
"email event.",
},
},
Action: cmdCheckDeviceLimits,
},
}
app.Action = cmdServer
app.Before = func(args *cli.Context) error {
log.Setup(debug)
err := config.FromConfigFile(configPath, dconfig.Defaults)
if err != nil {
return cli.NewExitError(
fmt.Sprintf("error loading configuration: %s", err),
1)
}
// Enable setting config values by environment variables
config.Config.SetEnvPrefix("DEVICEAUTH")
config.Config.AutomaticEnv()
return nil
}
_ = app.Run(args)
}
func cmdServer(args *cli.Context) error {
l := log.New(log.Ctx{})
db, err := mongo.NewDataStoreMongo(makeDataStoreConfig())
if err != nil {
return cli.NewExitError(
fmt.Sprintf("failed to connect to db: %v", err),
2)
}
if args.Bool("automigrate") {
db = db.WithAutomigrate().(*mongo.DataStoreMongo)
}
if config.Config.Get(dconfig.SettingTenantAdmAddr) != "" {
db = db.WithMultitenant()
}
ctx := context.Background()
err = db.Migrate(ctx, mongo.DbVersion)
if err != nil {
return cli.NewExitError(
fmt.Sprintf("failed to run migrations: %v", err),
3)
}
l.Print("Device Authentication Service starting up")
err = RunServer(config.Config)
if err != nil {
return cli.NewExitError(err.Error(), 4)
}
return nil
}
func cmdMigrate(args *cli.Context) error {
err := cmd.Migrate(config.Config, args.String("tenant"), args.Bool("list-tenants"))
if err != nil {
return cli.NewExitError(err, 5)
}
return nil
}
func cmdMaintenance(args *cli.Context) error {
err := cmd.Maintenance(
args.Bool("decommissioning-cleanup"),
args.String("tenant"),
args.Bool("dry-run"),
)
if err != nil {
return cli.NewExitError(err, 6)
}
return nil
}
func cmdPropagateStatusesInventory(args *cli.Context) error {
db, err := mongo.NewDataStoreMongo(makeDataStoreConfig())
if err != nil {
return err
}
inv := config.Config.GetString(dconfig.SettingInventoryAddr)
c := cinv.NewClient(inv, false)
err = cmd.PropagateStatusesInventory(db,
c,
args.String("tenant_id"),
args.String("force-set-migration"),
args.Bool("dry-run"))
if err != nil {
return cli.NewExitError(err, 7)
}
return nil
}
func cmdPropagateIdDataInventory(args *cli.Context) error {
db, err := mongo.NewDataStoreMongo(makeDataStoreConfig())
if err != nil {
return err
}
inv := config.Config.GetString(dconfig.SettingInventoryAddr)
c := cinv.NewClient(inv, false)
err = cmd.PropagateIdDataInventory(db,
c,
args.String("tenant_id"),
args.Bool("dry-run"))
if err != nil {
return cli.NewExitError(err, 7)
}
return nil
}
func cmdPropagateReporting(args *cli.Context) error {
if !config.Config.GetBool(dconfig.SettingEnableReporting) {
return cli.NewExitError(errors.New("reporting support not enabled"), 1)
}
db, err := mongo.NewDataStoreMongo(makeDataStoreConfig())
if err != nil {
return err
}
wflows := orchestrator.NewClient(orchestrator.Config{
OrchestratorAddr: config.Config.GetString(
dconfig.SettingOrchestratorAddr,
),
})
var requestPeriod time.Duration
if rateLimit := args.Uint("rate-limit"); rateLimit > 0 {
requestPeriod = time.Second / time.Duration(rateLimit)
}
err = cmd.PropagateReporting(
db,
wflows,
args.String("tenant_id"),
requestPeriod,
args.Bool("dry-run"),
)
if err != nil {
return cli.NewExitError(err, 7)
}
return nil
}
func makeDataStoreConfig() mongo.DataStoreMongoConfig {
return mongo.DataStoreMongoConfig{
ConnectionString: config.Config.GetString(dconfig.SettingDb),
SSL: config.Config.GetBool(dconfig.SettingDbSSL),
SSLSkipVerify: config.Config.GetBool(dconfig.SettingDbSSLSkipVerify),
Username: config.Config.GetString(dconfig.SettingDbUsername),
Password: config.Config.GetString(dconfig.SettingDbPassword),
}
}
func cmdCheckDeviceLimits(args *cli.Context) error {
mgoConf := makeDataStoreConfig()
ds, err := mongo.NewDataStoreMongo(mgoConf)
if err != nil {
return errors.Wrap(err, "cmd: failed to initialize DataStore client")
}
// Initialize tenantadm and workflows clients.
tadm := tenant.NewClient(tenant.Config{
TenantAdmAddr: config.Config.GetString(
dconfig.SettingTenantAdmAddr,
),
})
wflows := orchestrator.NewClient(orchestrator.Config{
OrchestratorAddr: config.Config.GetString(
dconfig.SettingOrchestratorAddr,
),
})
return cmd.CheckDeviceLimits(
args.Float64("threshold"),
ds, tadm, wflows,
)
}