-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
281 lines (259 loc) · 6.84 KB
/
main.go
File metadata and controls
281 lines (259 loc) · 6.84 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
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
package main
import (
"database/sql"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"runtime"
"strconv"
"sync"
"syscall"
"time"
_ "github.com/go-sql-driver/mysql"
pb "github.com/mc0/go-api-skeleton/proto"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
"gopkg.in/tylerb/graceful.v1"
"strings"
)
var (
namespace = "base"
subsystem = "goapiskeleton"
grpcPort = new(int)
httpPort = new(int)
mysqlUsername = new(string)
mysqlPassword = new(string)
mysqlHostname = new(string)
mysqlPort = new(int)
mysqlDatabase = new(string)
errorLockChan chan bool
db = new(sql.DB)
metrics = struct {
OpenConnections prometheus.Gauge
Latency prometheus.Summary
ErrorBackoffs prometheus.Counter
FailedRequests prometheus.Counter
Panics prometheus.Counter
}{
prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "open_connections",
Help: "Number of currently open connections.",
}),
prometheus.NewSummary(prometheus.SummaryOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "latency",
Help: "Request latency.",
}),
prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "error_backoffs",
Help: "How many times the service has reached an error backoff state.",
}),
prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "failed_requests",
Help: "Requests which did not complete successfully.",
}),
prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "panics",
Help: "Requests which paniced.",
}),
}
)
// The SkeletonServer that we use for gRPC
type SkeletonServer struct {
}
func init() {
parseIntEnv(grpcPort, "GRPC_PORT", 24601)
parseIntEnv(httpPort, "HTTP_PORT", 8080)
parseEnv(mysqlUsername, "MYSQL_USERNAME", "username")
parseEnv(mysqlPassword, "MYSQL_PASSWORD", "password")
parseEnv(mysqlHostname, "MYSQL_HOSTNAME", "mysql")
parseIntEnv(mysqlPort, "MYSQL_PORT", 3306)
parseEnv(mysqlDatabase, "MYSQL_DATABASE", "skeleton")
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
mysqlArgs := strings.Join([]string{
"readTimeout=1h",
"writeTimeout=60s",
// do not tune the following
"interpolateParams=true",
"charset=utf8",
"collation=utf8_general_ci",
}, "&")
var err error
dsn := fmt.Sprintf(
"%s:%s@tcp(%s)/%s?%s",
*mysqlUsername,
*mysqlPassword,
net.JoinHostPort(*mysqlHostname, strconv.Itoa(*mysqlPort)),
*mysqlDatabase,
mysqlArgs)
db, err = sql.Open("mysql", dsn)
if err != nil {
log.Printf("unable to create mysql db: %s", err)
os.Exit(1)
}
prometheus.MustRegister(
metrics.OpenConnections,
metrics.Latency,
metrics.ErrorBackoffs,
metrics.FailedRequests,
metrics.Panics,
)
}
func parseIntEnv(target *int, name string, defaultValue int) {
if v := os.Getenv(name); v != "" {
s, err := strconv.ParseInt(v, 10, 0)
if err != nil {
e := err.(*strconv.NumError)
log.Printf("Invalid integer for %s: %s\n%s\n", name, e.Num, e.Err.Error())
} else {
*target = int(s)
return
}
}
*target = defaultValue
}
func parseEnv(target *string, name, defaultValue string) {
if v := os.Getenv(name); v != "" {
*target = v
} else {
*target = defaultValue
}
}
// GetObject serves an RPC call that returns the object details.
func (server *SkeletonServer) GetObject(ctx context.Context, obj *pb.Object) (res *pb.Object, err error) {
// This deferred function closes over the err return value of the main function, so it will attain
// the most recent value of the err variable.
defer (func(start time.Time) {
metrics.Latency.Observe(time.Since(start).Seconds())
if err != nil {
metrics.FailedRequests.Inc()
log.Printf("GetObject error: Id: %s, %s", obj.Id, err)
} else if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
metrics.Panics.Inc()
stack := make([]byte, 1<<16)
runtime.Stack(stack, false)
log.Printf("GetObject panic: Id: %s, %s\n%s", obj.Id, err, stack)
}
})(time.Now())
query := `
SELECT name
FROM object
WHERE id = ?
`
err = db.QueryRow(query, obj.GetId()).Scan(&obj.Name)
if err != nil {
return obj, err
}
return obj, err
}
func main() {
errChan := make(chan int, 1000)
errorLockChan = make(chan bool, 1)
// Weird error backoff mechanism.
var errorLock sync.RWMutex
// This lets us have a "lock acquisition timeout" on the requests
go (func() {
for {
errorLock.RLock()
errorLock.RUnlock()
errorLockChan <- true
}
})()
// This handles locking and unlocking based on important errors, with an exponential ramp up
// Somewhat in the vein of a circuit breaker
go (func() {
recentErrors := 0
ticker := time.NewTicker(time.Second * 3)
lastLock := time.Now()
resetBackoff := time.NewTicker(time.Minute)
initialBackoff := time.Second * 3
backoffTime := initialBackoff
backoffLimit := 50
for {
select {
case <-errChan:
recentErrors++
// TODO: change logic in this conditional to be less opaque
if recentErrors > backoffLimit {
lastLock = time.Now()
errorLock.Lock()
metrics.ErrorBackoffs.Inc()
time.Sleep(backoffTime)
recentErrors = 0
if backoffTime <= initialBackoff*8 {
backoffTime *= 2
} else {
outer:
for {
// Clear the channel in case the issue's stopped
select {
case <-errChan:
default:
break outer
}
}
}
errorLock.Unlock()
}
case <-ticker.C:
recentErrors = 0
case <-resetBackoff.C:
if time.Since(lastLock) > time.Second*60 {
backoffTime = initialBackoff
continue
}
}
}
})()
// This waitgroup is for waiting on both servers to gracefully close
var wg sync.WaitGroup
wg.Add(2)
// Spin up json endpoint listener
go (func() {
mux := http.NewServeMux()
promHandler := promhttp.Handler()
mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
promHandler.ServeHTTP(w, r)
})
// Another magic number: in-flight requests have 15 seconds to complete.
graceful.Run(fmt.Sprintf(":%d", *httpPort), 15*time.Second, mux)
wg.Done()
})()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *grpcPort))
if err != nil {
grpclog.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
skeleton := &SkeletonServer{}
pb.RegisterSkeletonServer(grpcServer, skeleton)
// Listen for SIGTERM and SIGINT to shutdown gracefully
shutdownSig := make(chan os.Signal, 1)
signal.Notify(shutdownSig, syscall.SIGINT, syscall.SIGTERM)
go (func() {
<-shutdownSig
grpcServer.GracefulStop()
wg.Done()
})()
grpcServer.Serve(lis)
wg.Wait()
}