forked from brocaar/chirpstack-application-server
/
device_profile.go
438 lines (387 loc) · 11.6 KB
/
device_profile.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package storage
import (
"context"
"time"
"github.com/gofrs/uuid"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"github.com/brocaar/lora-app-server/internal/config"
"github.com/brocaar/loraserver/api/ns"
)
// DeviceProfile defines the device-profile.
type DeviceProfile struct {
NetworkServerID int64 `db:"network_server_id"`
OrganizationID int64 `db:"organization_id"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
Name string `db:"name"`
DeviceProfile ns.DeviceProfile `db:"-"`
}
// DeviceProfileMeta defines the device-profile meta record.
type DeviceProfileMeta struct {
DeviceProfileID uuid.UUID `db:"device_profile_id"`
NetworkServerID int64 `db:"network_server_id"`
OrganizationID int64 `db:"organization_id"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
Name string `db:"name"`
}
// Validate validates the device-profile data.
func (dp DeviceProfile) Validate() error {
if dp.Name == "" {
return ErrDeviceProfileInvalidName
}
return nil
}
// CreateDeviceProfile creates the given device-profile.
// This will create the device-profile at the network-server side and will
// create a local reference record.
func CreateDeviceProfile(db sqlx.Ext, dp *DeviceProfile) error {
if err := dp.Validate(); err != nil {
return errors.Wrap(err, "validate error")
}
dpID, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid v4 error")
}
now := time.Now()
dp.DeviceProfile.Id = dpID.Bytes()
dp.CreatedAt = now
dp.UpdatedAt = now
_, err = db.Exec(`
insert into device_profile (
device_profile_id,
network_server_id,
organization_id,
created_at,
updated_at,
name
) values ($1, $2, $3, $4, $5, $6)`,
dpID,
dp.NetworkServerID,
dp.OrganizationID,
dp.CreatedAt,
dp.UpdatedAt,
dp.Name,
)
if err != nil {
log.WithField("id", dpID).Errorf("create device-profile error: %s", err)
return handlePSQLError(Insert, err, "insert error")
}
n, err := GetNetworkServer(db, dp.NetworkServerID)
if err != nil {
return errors.Wrap(err, "get network-server error")
}
nsClient, err := config.C.NetworkServer.Pool.Get(n.Server, []byte(n.CACert), []byte(n.TLSCert), []byte(n.TLSKey))
if err != nil {
return errors.Wrap(err, "get network-server client error")
}
_, err = nsClient.CreateDeviceProfile(context.Background(), &ns.CreateDeviceProfileRequest{
DeviceProfile: &dp.DeviceProfile,
})
if err != nil {
return handleGrpcError(err, "create device-profile error")
}
log.WithFields(log.Fields{
"id": dpID,
}).Info("device-profile created")
return nil
}
// GetDeviceProfile returns the device-profile matching the given id.
func GetDeviceProfile(db sqlx.Queryer, id uuid.UUID) (DeviceProfile, error) {
var dp DeviceProfile
row := db.QueryRowx(`
select
network_server_id,
organization_id,
created_at,
updated_at,
name
from device_profile
where
device_profile_id = $1`,
id,
)
if err := row.Err(); err != nil {
return dp, handlePSQLError(Select, err, "select error")
}
err := row.Scan(&dp.NetworkServerID, &dp.OrganizationID, &dp.CreatedAt, &dp.UpdatedAt, &dp.Name)
if err != nil {
return dp, handlePSQLError(Scan, err, "scan error")
}
n, err := GetNetworkServer(db, dp.NetworkServerID)
if err != nil {
return dp, errors.Wrap(err, "get network-server error")
}
nsClient, err := config.C.NetworkServer.Pool.Get(n.Server, []byte(n.CACert), []byte(n.TLSCert), []byte(n.TLSKey))
if err != nil {
return dp, errors.Wrap(err, "get network-server client error")
}
resp, err := nsClient.GetDeviceProfile(context.Background(), &ns.GetDeviceProfileRequest{
Id: id.Bytes(),
})
if err != nil {
return dp, handleGrpcError(err, "get device-profile error")
}
if resp.DeviceProfile == nil {
return dp, errors.New("device_profile must not be nil")
}
dp.DeviceProfile = *resp.DeviceProfile
return dp, nil
}
// UpdateDeviceProfile updates the given device-profile.
func UpdateDeviceProfile(db sqlx.Ext, dp *DeviceProfile) error {
if err := dp.Validate(); err != nil {
return errors.Wrap(err, "validate error")
}
dpID, err := uuid.FromBytes(dp.DeviceProfile.Id)
if err != nil {
return errors.Wrap(err, "uuid from bytes error")
}
n, err := GetNetworkServer(db, dp.NetworkServerID)
if err != nil {
return errors.Wrap(err, "get network-server error")
}
nsClient, err := config.C.NetworkServer.Pool.Get(n.Server, []byte(n.CACert), []byte(n.TLSCert), []byte(n.TLSKey))
if err != nil {
return errors.Wrap(err, "get network-server client error")
}
_, err = nsClient.UpdateDeviceProfile(context.Background(), &ns.UpdateDeviceProfileRequest{
DeviceProfile: &dp.DeviceProfile,
})
if err != nil {
return handleGrpcError(err, "update device-profile error")
}
dp.UpdatedAt = time.Now()
res, err := db.Exec(`
update device_profile
set
updated_at = $2,
name = $3
where device_profile_id = $1`,
dpID,
dp.UpdatedAt,
dp.Name,
)
if err != nil {
return handlePSQLError(Update, err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"id": dpID,
}).Info("device-profile updated")
return nil
}
// DeleteDeviceProfile deletes the device-profile matching the given id.
func DeleteDeviceProfile(db sqlx.Ext, id uuid.UUID) error {
n, err := GetNetworkServerForDeviceProfileID(db, id)
if err != nil {
return errors.Wrap(err, "get network-server error")
}
nsClient, err := config.C.NetworkServer.Pool.Get(n.Server, []byte(n.CACert), []byte(n.TLSCert), []byte(n.TLSKey))
if err != nil {
return errors.Wrap(err, "get network-server client error")
}
res, err := db.Exec("delete from device_profile where device_profile_id = $1", id)
if err != nil {
return handlePSQLError(Delete, err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
_, err = nsClient.DeleteDeviceProfile(context.Background(), &ns.DeleteDeviceProfileRequest{
Id: id.Bytes(),
})
if err != nil && grpc.Code(err) != codes.NotFound {
return handleGrpcError(err, "delete device-profile error")
}
log.WithField("id", id).Info("device-profile deleted")
return nil
}
// GetDeviceProfileCount returns the total number of device-profiles.
func GetDeviceProfileCount(db sqlx.Queryer) (int, error) {
var count int
err := sqlx.Get(db, &count, "select count(*) from device_profile")
if err != nil {
return 0, handlePSQLError(Select, err, "select error")
}
return count, nil
}
// GetDeviceProfileCountForOrganizationID returns the total number of
// device-profiles for the given organization id.
func GetDeviceProfileCountForOrganizationID(db sqlx.Queryer, organizationID int64) (int, error) {
var count int
err := sqlx.Get(db, &count, "select count(*) from device_profile where organization_id = $1", organizationID)
if err != nil {
return 0, handlePSQLError(Select, err, "select error")
}
return count, nil
}
// GetDeviceProfileCountForUser returns the total number of device-profiles
// for the given username.
func GetDeviceProfileCountForUser(db sqlx.Queryer, username string) (int, error) {
var count int
err := sqlx.Get(db, &count, `
select
count(dp.*)
from device_profile dp
inner join organization o
on o.id = dp.organization_id
inner join organization_user ou
on ou.organization_id = o.id
inner join "user" u
on u.id = ou.user_id
where
u.username = $1`,
username,
)
if err != nil {
return 0, handlePSQLError(Select, err, "select error")
}
return count, nil
}
// GetDeviceProfileCountForApplicationID returns the total number of
// device-profiles that can be used for the given application id (based
// on the service-profile of the application).
func GetDeviceProfileCountForApplicationID(db sqlx.Queryer, applicationID int64) (int, error) {
var count int
err := sqlx.Get(db, &count, `
select
count(dp.*)
from device_profile dp
inner join network_server ns
on ns.id = dp.network_server_id
inner join service_profile sp
on sp.network_server_id = ns.id
inner join application a
on a.service_profile_id = sp.service_profile_id
where
a.id = $1
and dp.organization_id = a.organization_id`,
applicationID,
)
if err != nil {
return 0, handlePSQLError(Select, err, "select error")
}
return count, nil
}
// GetDeviceProfiles returns a slice of device-profiles.
func GetDeviceProfiles(db sqlx.Queryer, limit, offset int) ([]DeviceProfileMeta, error) {
var dps []DeviceProfileMeta
err := sqlx.Select(db, &dps, `
select *
from device_profile
order by name
limit $1 offset $2`,
limit,
offset,
)
if err != nil {
return nil, handlePSQLError(Select, err, "select error")
}
return dps, nil
}
// GetDeviceProfilesForOrganizationID returns a slice of device-profiles
// for the given organization id.
func GetDeviceProfilesForOrganizationID(db sqlx.Queryer, organizationID int64, limit, offset int) ([]DeviceProfileMeta, error) {
var dps []DeviceProfileMeta
err := sqlx.Select(db, &dps, `
select *
from device_profile
where
organization_id = $1
order by name
limit $2 offset $3`,
organizationID,
limit,
offset,
)
if err != nil {
return nil, handlePSQLError(Select, err, "select error")
}
return dps, nil
}
// GetDeviceProfilesForUser returns a slice of device-profiles for the given
// username.
func GetDeviceProfilesForUser(db sqlx.Queryer, username string, limit, offset int) ([]DeviceProfileMeta, error) {
var dps []DeviceProfileMeta
err := sqlx.Select(db, &dps, `
select dp.*
from device_profile dp
inner join organization o
on o.id = dp.organization_id
inner join organization_user ou
on ou.organization_id = o.id
inner join "user" u
on u.id = ou.user_id
where
u.username = $1
order by dp.name
limit $2 offset $3`,
username,
limit,
offset,
)
if err != nil {
return nil, handlePSQLError(Select, err, "select error")
}
return dps, nil
}
// GetDeviceProfilesForApplicationID returns a slice of device-profiles that
// can be used for the given application id (based on the service-profile
// of the application).
func GetDeviceProfilesForApplicationID(db sqlx.Queryer, applicationID int64, limit, offset int) ([]DeviceProfileMeta, error) {
var dps []DeviceProfileMeta
err := sqlx.Select(db, &dps, `
select
dp.*
from device_profile dp
inner join network_server ns
on ns.id = dp.network_server_id
inner join service_profile sp
on sp.network_server_id = ns.id
inner join application a
on a.service_profile_id = sp.service_profile_id
where
a.id = $1
and dp.organization_id = a.organization_id
order by dp.name
limit $2 offset $3`,
applicationID,
limit,
offset,
)
if err != nil {
return nil, handlePSQLError(Select, err, "select error")
}
return dps, nil
}
// DeleteAllDeviceProfilesForOrganizationID deletes all device-profiles
// given an organization id.
func DeleteAllDeviceProfilesForOrganizationID(db sqlx.Ext, organizationID int64) error {
var dps []DeviceProfileMeta
err := sqlx.Select(db, &dps, "select * from device_profile where organization_id = $1", organizationID)
if err != nil {
return handlePSQLError(Select, err, "select error")
}
for _, dp := range dps {
err = DeleteDeviceProfile(db, dp.DeviceProfileID)
if err != nil {
return errors.Wrap(err, "delete device-profile error")
}
}
return nil
}