-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.go
More file actions
238 lines (190 loc) · 4.98 KB
/
common.go
File metadata and controls
238 lines (190 loc) · 4.98 KB
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
package platform
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/pborman/uuid"
"github.com/sirupsen/logrus"
)
var (
cachedIp string
loggers = map[string]*logrus.Logger{}
loggersMutex = sync.Mutex{}
logger = GetLogger("platform")
PREVENT_PLATFORM_PANICS = Getenv("PLATFORM_PREVENT_PANICS", "1") == "1"
)
var LOG_LEVEL = strings.ToLower(os.Getenv("LOG_LEVEL"))
var logLevels = map[string]logrus.Level{
"debug": logrus.DebugLevel,
"info": logrus.InfoLevel,
"warn": logrus.WarnLevel,
"error": logrus.ErrorLevel,
"fatal": logrus.FatalLevel,
"panic": logrus.PanicLevel,
}
func CreateUUID() string {
return uuid.New()
}
func generateResponse(request *Request, response *Request) *Request {
response.Uuid = request.Uuid
response.Trace = request.Trace
if response.Routing == nil {
response.Routing = &Routing{}
}
if response.Routing.RouteTo == nil {
response.Routing.RouteTo = []*Route{}
}
if request.Routing != nil && request.Routing.RouteFrom != nil {
response.Routing.RouteTo = append(response.Routing.RouteTo, request.Routing.RouteFrom...)
}
response.Routing.RouteFrom = []*Route{}
return response
}
func Getenv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
// Copied from logrus to prevent field naming conflicts in the JSON formatting
func prefixFieldClashes(data logrus.Fields) {
if t, ok := data["timestamp"]; ok {
data["fields.timestamp"] = t
}
if m, ok := data["msg"]; ok {
data["fields.msg"] = m
}
if l, ok := data["severity"]; ok {
data["fields.severity"] = l
}
}
type DefaultFormatter struct {
}
func (f *DefaultFormatter) Format(entry *logrus.Entry) ([]byte, error) {
data := make(logrus.Fields, len(entry.Data)+3)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/Sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
prefixFieldClashes(data)
data["timestamp"] = entry.Time.Format("01/02/2006 15:04:05.000")
data["msg"] = entry.Message
data["severity"] = entry.Level.String()
logBytes := []byte{}
if os.Getenv("LOG_PRETTY_PRINT") == "true" {
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
return nil, fmt.Errorf("Failed to MarshalIndent fields to JSON: %s", err)
}
logBytes = b
} else {
buffer := bytes.Buffer{}
if err := json.NewEncoder(&buffer).Encode(data); err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
logBytes = buffer.Bytes()
}
return logBytes, nil
}
func GetLogger(prefix string) *logrus.Logger {
logger := logrus.New()
if strings.ToLower(os.Getenv("LOG_FORMATTER")) == "text" {
logger.Formatter = &logrus.TextFormatter{}
} else {
logger.Formatter = &DefaultFormatter{}
}
logger.Level = logrus.GetLevel()
logger.Out = os.Stdout
if logLevel, exists := logLevels[LOG_LEVEL]; exists {
logger.Level = logLevel
} else {
logger.Level = logrus.DebugLevel
}
return logger
}
func getMyIp(client *http.Client, timeout time.Duration) (string, error) {
urls := []string{"http://ifconfig.me/ip", "http://curlmyip.com", "http://icanhazip.com"}
respChan := make(chan *http.Response)
for _, url := range urls {
go func(url string, responseChan chan *http.Response) {
res, err := client.Get(url)
if err == nil {
responseChan <- res
}
}(url, respChan)
}
select {
case res := <-respChan:
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
cachedIp = strings.Trim(string(body), "\n ")
return cachedIp, nil
case <-time.After(timeout):
return "", errors.New("Timed out trying to fetch ip address.")
}
}
func GetMyIp() (string, error) {
if cachedIp != "" {
return cachedIp, nil
}
return getMyIp(http.DefaultClient, 5*time.Second)
}
func IsInternalRequest(request *Request) bool {
if request.Routing == nil {
return false
}
if request.Routing.RouteFrom == nil {
return false
}
if len(request.Routing.RouteFrom) <= 1 {
return false
}
// If the second to last routing has the microservice:/// prefix, it's internal
if strings.HasPrefix(request.Routing.RouteFrom[len(request.Routing.RouteFrom)-2].GetUri(), "microservice:///") {
return true
}
// If the last routing has the microservice:/// prefix, it's internal
if strings.HasPrefix(request.Routing.RouteFrom[len(request.Routing.RouteFrom)-1].GetUri(), "microservice:///") {
return true
}
return false
}
func RouteToUri(uri string) *Routing {
return &Routing{
RouteTo: []*Route{
&Route{
Uri: String(uri),
},
},
}
}
func RouteToSchemeMatches(request *Request, scheme string) bool {
if request.Routing == nil {
return false
}
if len(request.Routing.RouteTo) <= 0 {
return false
}
targetUri, err := url.Parse(request.Routing.RouteTo[0].GetUri())
if err != nil {
return false
}
return targetUri.Scheme == scheme
}