-
Notifications
You must be signed in to change notification settings - Fork 2
/
tm.go
213 lines (175 loc) · 5.42 KB
/
tm.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
// Package tm implements Type Models for txn2 projects.
package tm
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/txn2/ack"
"github.com/txn2/es/v2"
"github.com/txn2/micro"
"go.uber.org/zap"
)
// ModelResult returned from Elastic
type ModelResult struct {
es.Result
Source Model `json:"_source"`
}
// ModelResultAck
type ModelResultAck struct {
ack.Ack
Payload ModelResult `json:"payload"`
}
// Config
type Config struct {
Logger *zap.Logger
HttpClient *micro.Client
// used for communication with Elasticsearch
// if nil, HttpClient will be used.
Elastic *es.Client
ElasticServer string
}
// Api
type Api struct {
*Config
}
// NewApi
func NewApi(cfg *Config) (*Api, error) {
a := &Api{Config: cfg}
if a.Elastic == nil {
// Configure an elastic client
a.Elastic = es.CreateClient(es.Config{
Log: cfg.Logger,
HttpClient: cfg.HttpClient.Http,
ElasticServer: cfg.ElasticServer,
})
}
// check for elasticsearch
backOff := []int{10, 10, 15, 15, 30, 30, 45}
for _, boff := range backOff {
code, _, _ := a.Elastic.Get("")
a.Logger.Info("Attempting to contact Elasticsearch", zap.String("server", a.Elastic.ElasticServer))
if code == 200 {
a.Logger.Info("Connection to Elastic search successful.", zap.String("server", a.Elastic.ElasticServer))
break
}
a.Logger.Warn("Unable to contact Elasticsearch rolling back off.", zap.Int("wait_seconds", boff))
<-time.After(time.Duration(boff) * time.Second)
}
// send template mappings for models index
_, _, errMessage, err := a.Elastic.SendEsMapping(GetModelsTemplateMapping())
if err != nil {
a.Logger.Error("NewApi error adding templates", zap.Error(err))
if errMessage != nil {
zap.String("es_error_response", errMessage.Message)
}
return nil, err
}
return a, nil
}
// GetModel
func (a *Api) GetModel(account string, id string) (int, *ModelResult, error) {
locFmt := "%s-%s/_doc/%s"
// CONVENTION: if the account ends in an underscore "_" then
// it is a system model (SYSTEM_IdxModel)
if strings.HasSuffix(account, "_") {
locFmt = "%s%s/_doc/%s"
}
code, ret, err := a.Elastic.Get(fmt.Sprintf(locFmt, account, IdxModel, id))
if err != nil {
a.Logger.Error("EsError", zap.Error(err), zap.ByteString("returned_data", ret))
return code, nil, errors.New(err.Error() + " Elastic returned " + string(ret))
}
if code != 200 {
return code, nil, errors.New("Elastic returned " + string(ret))
}
modelResult := &ModelResult{}
err = json.Unmarshal(ret, modelResult)
if err != nil {
return code, nil, err
}
return code, modelResult, nil
}
// GetModelHandler
func (a *Api) GetModelHandler(c *gin.Context) {
ak := ack.Gin(c)
// GetModelHandler must be security screened in
// upstream middleware to protect account access.
account := c.Param("account")
id := c.Param("id")
code, modelResult, err := a.GetModel(account, id)
if err != nil {
a.Logger.Error("EsError", zap.Error(err))
ak.SetPayloadType("EsError")
ak.SetPayload("Error communicating with database.")
ak.GinErrorAbort(500, "EsError", err.Error())
return
}
if code >= 400 && code < 500 {
ak.SetPayload("Model " + id + " not found.")
ak.GinErrorAbort(404, "ModelNotFound", "Model not found")
return
}
ak.SetPayloadType("ModelResult")
ak.GinSend(modelResult)
}
// UpsertModel
func (a *Api) UpsertModel(account string, model *Model) (int, es.Result, *es.ErrorResponse, error) {
a.Logger.Info("Upsert model record", zap.String("account", account), zap.String("machine_name", model.MachineName))
// send template mappings for models index
code, templateMappingResult, errorResult, err := a.Elastic.SendEsMapping(MakeModelTemplateMapping(account, model))
if errorResult != nil {
a.Logger.Error("Elastic error result", zap.String("error_result", errorResult.Message))
return code, templateMappingResult, errorResult, err
}
if err != nil {
a.Logger.Error("UpsertModel error", zap.Error(err))
return code, templateMappingResult, errorResult, err
}
locFmt := "%s-%s/_doc/%s"
// CONVENTION: if the account ends in an underscore "_" then
// it is a system model (SYSTEM_IdxModel)
if strings.HasSuffix(account, "_") {
locFmt = "%s%s/_doc/%s"
}
return a.Elastic.PutObj(fmt.Sprintf(locFmt, account, IdxModel, model.MachineName), model)
}
// UpsertModelHandler
func (a *Api) UpsertModelHandler(c *gin.Context) {
ak := ack.Gin(c)
// UpsertModelHandler must be security screened in
// upstream middleware to protect account access.
account := c.Param("account")
model := &Model{}
err := ak.UnmarshalPostAbort(model)
if err != nil {
a.Logger.Error("Upsert failure.", zap.Error(err))
return
}
// ensure lowercase machine name
model.MachineName = strings.ToLower(model.MachineName)
//ak.GinSend(MakeModelTemplateMapping(account, model))
//return
code, esResult, esErrorResult, err := a.UpsertModel(account, model)
if err != nil {
a.Logger.Error("Upsert failure.", zap.Error(err))
ak.SetPayloadType("ErrorMessage")
ak.SetPayload("there was a problem upserting the model: " + esErrorResult.Message)
ak.GinErrorAbort(500, "UpsertError", err.Error())
return
}
if code < 200 || code >= 300 {
a.Logger.Error("Es returned a non 200")
ak.SetPayloadType("EsError")
ak.SetPayload(esResult)
if esErrorResult != nil {
ak.SetPayload(esErrorResult.Message)
}
ak.GinErrorAbort(code, "EsError", "Es returned a non 200")
return
}
ak.SetPayloadType("EsResult")
ak.GinSend(esResult)
}