-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
database_handlers.go
224 lines (195 loc) · 6.21 KB
/
database_handlers.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
package handlers
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path"
"strconv"
"time"
"github.com/layer5io/meshery/server/meshmodel"
"github.com/layer5io/meshery/server/models"
"github.com/layer5io/meshkit/models/meshmodel/registry"
"github.com/layer5io/meshkit/utils"
meshsyncmodel "github.com/layer5io/meshsync/pkg/model"
"github.com/spf13/viper"
"gorm.io/gorm/clause"
)
// swagger:route GET /api/system/database GetSystemDatabase idGetSystemDatabase
// Handle GET request for getting summary about the system database.
//
// # Tables can be further filtered through query parameter
//
// ```?order={field}``` orders on the passed field
//
// ```?sort={[asc/desc]}``` Default behavior is asc
//
// ```?page={page-number}``` Default page number is 1
//
// ```?pagesize={pagesize}``` Default pagesize is 10. To return all results: ```pagesize=all```
//
// ```?search={tablename}``` If search is non empty then a greedy search is performed
// responses:
//
// 200: systemDatabaseResponseWrapper
func (h *Handler) GetSystemDatabase(w http.ResponseWriter, r *http.Request, _ *models.Preference, _ *models.User, provider models.Provider) {
var tables []*models.SqliteSchema
var recordCount int
var totalTables int64
limitstr := r.URL.Query().Get("pagesize")
var limit int
if limitstr != "all" {
limit, _ = strconv.Atoi(limitstr)
if limit <= 0 {
limit = defaultPageSize
}
}
pagestr := r.URL.Query().Get("page")
page, _ := strconv.Atoi(pagestr)
if page <= 0 {
page = 1
}
offset := (page - 1) * limit
order := r.URL.Query().Get("order")
sort := r.URL.Query().Get("sort")
search := r.URL.Query().Get("search")
tableFinder := h.dbHandler.DB.Table("sqlite_schema").
Where("type = ?", "table")
if search != "" {
tableFinder = tableFinder.Where("name LIKE ?", "%"+search+"%")
}
tableFinder.Count(&totalTables)
if limit != 0 {
tableFinder = tableFinder.Limit(limit)
}
if offset != 0 {
tableFinder = tableFinder.Offset(offset)
}
order = models.SanitizeOrderInput(order, []string{"created_at", "updated_at", "name"})
if order != "" {
if sort == "desc" {
tableFinder = tableFinder.Order(clause.OrderByColumn{Column: clause.Column{Name: order}, Desc: true})
} else {
tableFinder = tableFinder.Order(order)
}
}
tableFinder.Find(&tables)
for _, table := range tables {
h.dbHandler.DB.Table(table.Name).Count(&table.Count)
recordCount += int(table.Count)
}
databaseSummary := &models.DatabaseSummary{
Page: page,
PageSize: limit,
TotalTables: int(totalTables),
RecordCount: recordCount,
Tables: tables,
}
w.Header().Set("Content-Type", "application/json")
val, err := json.Marshal(databaseSummary)
if err != nil {
fmt.Println(err)
}
fmt.Fprint(w, string(val))
}
// swagger:route DELETE /api/system/database/reset ResetSystemDatabase
// Reset the system database to its initial state.
//
// This endpoint resets the system database to its initial state by performing the following steps:
// - Creates an archive of the current database contents.
// - Drops all existing tables in the database.
// - Applies auto migration to recreate the necessary tables.
//
// responses:
// 200:
// 500:
// Reset the system database to its initial state.
func (h *Handler) ResetSystemDatabase(w http.ResponseWriter, r *http.Request, _ *models.Preference, _ *models.User, provider models.Provider) {
mesherydbPath := path.Join(utils.GetHome(), ".meshery/config")
err := os.Mkdir(path.Join(mesherydbPath, ".archive"), os.ModePerm)
if err != nil && os.IsNotExist(err) {
http.Error(w, "Directory could not be created due to a non-existent path.", http.StatusInternalServerError)
return
}
src := path.Join(mesherydbPath, "mesherydb.sql")
currentTime := time.Now().Format("20060102150407")
newFileName := ".archive/mesherydb" + currentTime + ".sql"
dst := path.Join(mesherydbPath, newFileName)
fin, err := os.Open(src)
if err != nil {
http.Error(w, "The database does not exist or you don't have enough permission to access it", http.StatusInternalServerError)
return
}
defer fin.Close()
fout, err := os.Create(dst)
if err != nil {
http.Error(w, "Destination file can not be created", http.StatusInternalServerError)
return
}
defer fout.Close()
_, err = io.Copy(fout, fin)
if err != nil {
http.Error(w, "Can not copy file from source to destination", http.StatusInternalServerError)
return
}
dbHandler := provider.GetGenericPersister()
if dbHandler == nil {
http.Error(w, "Failed to obtain database handler", http.StatusInternalServerError)
return
} else {
dbHandler.Lock()
defer dbHandler.Unlock()
tables, err := dbHandler.Migrator().GetTables()
if err != nil {
http.Error(w, "Can not access database tables", http.StatusInternalServerError)
return
}
for _, table := range tables {
err = dbHandler.Migrator().DropTable(table)
if err != nil {
http.Error(w, "Cannot drop table from database", http.StatusInternalServerError)
return
}
}
err = dbHandler.AutoMigrate(
&meshsyncmodel.KubernetesKeyValue{},
&meshsyncmodel.KubernetesResource{},
&meshsyncmodel.KubernetesResourceSpec{},
&meshsyncmodel.KubernetesResourceStatus{},
&meshsyncmodel.KubernetesResourceObjectMeta{},
&models.PerformanceProfile{},
&models.MesheryResult{},
&models.MesheryPattern{},
&models.MesheryFilter{},
&models.PatternResource{},
&models.MesheryApplication{},
&models.UserPreference{},
&models.PerformanceTestConfig{},
&models.SmiResultWithID{},
&models.K8sContext{},
)
if err != nil {
http.Error(w, "Can not migrate tables to database", http.StatusInternalServerError)
return
}
rm, err := registry.NewRegistryManager(dbHandler)
if err != nil {
http.Error(w, "Can not migrate tables to database", http.StatusInternalServerError)
return
}
h.registryManager = rm
krh, err := models.NewKeysRegistrationHelper(dbHandler, h.log)
if err != nil {
http.Error(w, "Can not migrate tables to database", http.StatusInternalServerError)
return
}
ch := meshmodel.NewEntityRegistrationHelper(h.config, h.registryManager, h.log)
go func() {
ch.SeedComponents()
krh.SeedKeys(viper.GetString("KEYS_PATH"))
}()
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, "Database reset successful")
}
}