/
profiles.go
283 lines (245 loc) · 8.42 KB
/
profiles.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
package profile
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import (
"errors"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/util/ims"
"net/http"
"strconv"
"time"
"github.com/apache/trafficcontrol/lib/go-log"
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/lib/go-tc/tovalidate"
"github.com/apache/trafficcontrol/lib/go-util"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/parameter"
validation "github.com/go-ozzo/ozzo-validation"
"github.com/jmoiron/sqlx"
)
const (
CDNQueryParam = "cdn"
DescriptionQueryParam = "description"
IDQueryParam = "id"
NameQueryParam = "name"
ParamQueryParam = "param"
TypeQueryParam = "type"
)
//we need a type alias to define functions on
type TOProfile struct {
api.APIInfoImpl `json:"-"`
tc.ProfileNullable
}
func (v *TOProfile) GetLastUpdated() (*time.Time, bool, error) {
return api.GetLastUpdated(v.APIInfo().Tx, *v.ID, "profile")
}
func (v *TOProfile) SetLastUpdated(t tc.TimeNoMod) { v.LastUpdated = &t }
func (v *TOProfile) InsertQuery() string { return insertQuery() }
func (v *TOProfile) UpdateQuery() string { return updateQuery() }
func (v *TOProfile) DeleteQuery() string { return deleteQuery() }
func (prof TOProfile) GetKeyFieldsInfo() []api.KeyFieldInfo {
return []api.KeyFieldInfo{{IDQueryParam, api.GetIntKey}}
}
//Implementation of the Identifier, Validator interface functions
func (prof TOProfile) GetKeys() (map[string]interface{}, bool) {
if prof.ID == nil {
return map[string]interface{}{IDQueryParam: 0}, false
}
return map[string]interface{}{IDQueryParam: *prof.ID}, true
}
func (prof *TOProfile) SetKeys(keys map[string]interface{}) {
i, _ := keys[IDQueryParam].(int) //this utilizes the non panicking type assertion, if the thrown away ok variable is false i will be the zero of the type, 0 here.
prof.ID = &i
}
func (prof *TOProfile) GetAuditName() string {
if prof.Name != nil {
return *prof.Name
}
if prof.ID != nil {
return strconv.Itoa(*prof.ID)
}
return "unknown"
}
func (prof *TOProfile) GetType() string {
return "profile"
}
func (prof *TOProfile) Validate() error {
errs := validation.Errors{
NameQueryParam: validation.Validate(prof.Name, validation.Required),
DescriptionQueryParam: validation.Validate(prof.Description, validation.Required),
CDNQueryParam: validation.Validate(prof.CDNID, validation.Required),
TypeQueryParam: validation.Validate(prof.Type, validation.Required),
}
if errs != nil {
return util.JoinErrs(tovalidate.ToErrors(errs))
}
return nil
}
func (prof *TOProfile) Read(h http.Header, useIMS bool) ([]interface{}, error, error, int, *time.Time) {
var maxTime time.Time
var runSecond bool
// Query Parameters to Database Query column mappings
// see the fields mapped in the SQL query
queryParamsToQueryCols := map[string]dbhelpers.WhereColumnInfo{
CDNQueryParam: dbhelpers.WhereColumnInfo{"c.id", nil},
NameQueryParam: dbhelpers.WhereColumnInfo{"prof.name", nil},
IDQueryParam: dbhelpers.WhereColumnInfo{"prof.id", api.IsInt},
}
where, orderBy, pagination, queryValues, errs := dbhelpers.BuildWhereAndOrderByAndPagination(prof.APIInfo().Params, queryParamsToQueryCols)
// Narrow down if the query parameter is 'param'
// TODO add generic where clause to api.GenericRead
if paramValue, ok := prof.APIInfo().Params[ParamQueryParam]; ok {
queryValues["parameter_id"] = paramValue
if len(paramValue) > 0 {
where += " LEFT JOIN profile_parameter pp ON prof.id = pp.profile where pp.parameter=:parameter_id"
}
}
if len(errs) > 0 {
return nil, util.JoinErrs(errs), nil, http.StatusBadRequest, nil
}
if useIMS {
runSecond, maxTime = ims.TryIfModifiedSinceQuery(prof.APIInfo().Tx, h, queryValues, selectMaxLastUpdatedQuery(where))
if !runSecond {
log.Debugln("IMS HIT")
return []interface{}{}, nil, nil, http.StatusNotModified, &maxTime
}
log.Debugln("IMS MISS")
} else {
log.Debugln("Non IMS request")
}
query := selectProfilesQuery() + where + orderBy + pagination
log.Debugln("Query is ", query)
rows, err := prof.ReqInfo.Tx.NamedQuery(query, queryValues)
if err != nil {
return nil, nil, errors.New("profile read querying: " + err.Error()), http.StatusInternalServerError, nil
}
defer rows.Close()
profiles := []tc.ProfileNullable{}
for rows.Next() {
var p tc.ProfileNullable
if err = rows.StructScan(&p); err != nil {
return nil, nil, errors.New("profile read scanning: " + err.Error()), http.StatusInternalServerError, nil
}
profiles = append(profiles, p)
}
rows.Close()
profileInterfaces := []interface{}{}
for _, profile := range profiles {
// Attach Parameters if the 'id' parameter is sent
if _, ok := prof.APIInfo().Params[IDQueryParam]; ok {
profile.Parameters, err = ReadParameters(prof.ReqInfo.Tx, prof.APIInfo().Params, prof.ReqInfo.User, profile)
if err != nil {
return nil, nil, errors.New("profile read reading parameters: " + err.Error()), http.StatusInternalServerError, nil
}
}
profileInterfaces = append(profileInterfaces, profile)
}
return profileInterfaces, nil, nil, http.StatusOK, &maxTime
}
func selectMaxLastUpdatedQuery(where string) string {
return `SELECT max(t) from (
SELECT max(prof.last_updated) as t FROM profile prof
LEFT JOIN cdn c ON prof.cdn = c.id ` + where +
` UNION ALL
select max(last_updated) as t from last_deleted l where l.table_name='profile') as res`
}
func selectProfilesQuery() string {
query := `SELECT
prof.description,
prof.id,
prof.last_updated,
prof.name,
prof.routing_disabled,
prof.type,
c.id as cdn,
c.name as cdn_name
FROM profile prof
LEFT JOIN cdn c ON prof.cdn = c.id`
return query
}
func ReadParameters(tx *sqlx.Tx, parameters map[string]string, user *auth.CurrentUser, profile tc.ProfileNullable) ([]tc.ParameterNullable, error) {
privLevel := user.PrivLevel
queryValues := make(map[string]interface{})
queryValues["profile_id"] = *profile.ID
query := selectParametersQuery()
rows, err := tx.NamedQuery(query, queryValues)
if err != nil {
return nil, errors.New("querying: " + err.Error())
}
defer rows.Close()
var params []tc.ParameterNullable
for rows.Next() {
var param tc.ParameterNullable
if err = rows.StructScan(¶m); err != nil {
return nil, errors.New("scanning: " + err.Error())
}
var isSecure bool
if param.Secure != nil {
isSecure = *param.Secure
}
if isSecure && (privLevel < auth.PrivLevelAdmin) {
param.Value = ¶meter.HiddenField
}
params = append(params, param)
}
return params, nil
}
func selectParametersQuery() string {
return `SELECT
p.id,
p.name,
p.config_file,
p.value,
p.secure
FROM parameter p
JOIN profile_parameter pp ON pp.parameter = p.id
WHERE pp.profile = :profile_id`
}
func (pr *TOProfile) Update(h http.Header) (error, error, int) { return api.GenericUpdate(h, pr) }
func (pr *TOProfile) Create() (error, error, int) { return api.GenericCreate(pr) }
func (pr *TOProfile) Delete() (error, error, int) { return api.GenericDelete(pr) }
func updateQuery() string {
query := `UPDATE
profile SET
cdn=:cdn,
description=:description,
name=:name,
routing_disabled=:routing_disabled,
type=:type
WHERE id=:id RETURNING last_updated`
return query
}
func insertQuery() string {
query := `INSERT INTO profile (
cdn,
description,
name,
routing_disabled,
type) VALUES (
:cdn,
:description,
:name,
:routing_disabled,
:type) RETURNING id,last_updated`
return query
}
func deleteQuery() string {
return `DELETE FROM profile WHERE id = :id`
}