/
nodestatus_repo.go
100 lines (76 loc) · 2.18 KB
/
nodestatus_repo.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
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2023-present, Ukama Inc.
*/
package db
import (
log "github.com/sirupsen/logrus"
"github.com/ukama/ukama/systems/common/sql"
"github.com/ukama/ukama/systems/common/ukama"
"gorm.io/gorm"
)
type NodeStatusRepo interface {
Update(*NodeStatus) error
Get(ukama.NodeID) (*NodeStatus, error)
Delete(ukama.NodeID) error
GetAll() ([]NodeStatus, error)
GetNodeCount() (onlineNodeCount, offlineNodeCount int64, err error)
}
type nodeStatusRepo struct {
Db sql.Db
}
func NewNodeStatusRepo(db sql.Db) NodeStatusRepo {
return &nodeStatusRepo{
Db: db,
}
}
func (n *nodeStatusRepo) Update(ns *NodeStatus) error {
err := n.Db.GetGormDb().Transaction(func(tx *gorm.DB) error {
t := tx.Where("node_id = ?", ns.NodeId).Delete(&NodeStatus{})
if t.RowsAffected > 0 {
log.Debugf("Marking old state.")
}
result := tx.Create(ns)
if result.Error != nil {
return result.Error
}
return nil
})
return err
}
func (n *nodeStatusRepo) Delete(id ukama.NodeID) error {
result := n.Db.GetGormDb().Where("node_id=?", id.StringLowercase()).Delete(&NodeStatus{})
if result.Error != nil {
return result.Error
}
return nil
}
func (n *nodeStatusRepo) Get(id ukama.NodeID) (*NodeStatus, error) {
var ns NodeStatus
result := n.Db.GetGormDb().First(&ns, "node_id=?", id.StringLowercase())
if result.Error != nil {
return nil, result.Error
}
return &ns, nil
}
func (n *nodeStatusRepo) GetAll() ([]NodeStatus, error) {
var ns []NodeStatus
result := n.Db.GetGormDb().Find(&ns)
if result.Error != nil {
return nil, result.Error
}
return ns, nil
}
func (n *nodeStatusRepo) GetNodeCount() (onlineNodeCount, offlineNodeCount int64, err error) {
db := n.Db.GetGormDb()
if err := db.Model(&NodeStatus{}).Where("conn = ?", Online).Count(&onlineNodeCount).Error; err != nil {
return 0, 0, err
}
if err := db.Model(&NodeStatus{}).Where("conn = ?", Offline).Count(&offlineNodeCount).Error; err != nil {
return 0, 0, err
}
return onlineNodeCount, offlineNodeCount, nil
}