forked from OpenAtomFoundation/pikiwidb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
354 lines (309 loc) · 8.99 KB
/
main.go
File metadata and controls
354 lines (309 loc) · 8.99 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// Copyright 2016 CodisLabs. All Rights Reserved.
// Licensed under the MIT (MIT-LICENSE.txt) license.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/docopt/docopt-go"
"pika/codis/v2/pkg/models"
"pika/codis/v2/pkg/proxy"
"pika/codis/v2/pkg/topom"
"pika/codis/v2/pkg/utils"
"pika/codis/v2/pkg/utils/log"
"pika/codis/v2/pkg/utils/math2"
)
func main() {
const usage = `
Usage:
codis-proxy [--ncpu=N [--max-ncpu=MAX]] [--config=CONF] [--log=FILE] [--log-level=LEVEL] [--host-admin=ADDR] [--host-proxy=ADDR] [--dashboard=ADDR|--zookeeper=ADDR [--zookeeper-auth=USR:PWD]|--etcd=ADDR [--etcd-auth=USR:PWD]|--filesystem=ROOT|--fillslots=FILE] [--ulimit=NLIMIT] [--pidfile=FILE] [--product_name=NAME] [--product_auth=AUTH] [--session_auth=AUTH]
codis-proxy --default-config
codis-proxy --version
Options:
--ncpu=N set runtime.GOMAXPROCS to N, default is runtime.NumCPU().
-c CONF, --config=CONF run with the specific configuration.
-l FILE, --log=FILE set path/name of daliy rotated log file.
--log-level=LEVEL set the log-level, should be INFO,WARN,DEBUG or ERROR, default is INFO.
--ulimit=NLIMIT run 'ulimit -n' to check the maximum number of open file descriptors.
`
d, err := docopt.Parse(usage, nil, true, "", false)
if err != nil {
log.PanicError(err, "parse arguments failed")
}
switch {
case d["--default-config"]:
fmt.Println(proxy.DefaultConfig)
return
case d["--version"].(bool):
fmt.Printf("-----------Codis Proxy----------\n")
fmt.Println("codis_version:", utils.Version)
fmt.Println("codis_git_sha:", utils.Gitsha)
fmt.Println("codis_build_compile_date:", utils.Compile)
fmt.Println("go version:", utils.GoVersion)
return
}
if s, ok := utils.Argument(d, "--log"); ok {
w, err := log.NewRollingFile(s, log.DailyRolling)
if err != nil {
log.PanicErrorf(err, "open log file %s failed", s)
} else {
log.StdLog = log.New(w, "")
}
}
log.SetLevel(log.LevelInfo)
if s, ok := utils.Argument(d, "--log-level"); ok {
if !log.SetLevelString(s) {
log.Panicf("option --log-level = %s", s)
}
}
if n, ok := utils.ArgumentInteger(d, "--ulimit"); ok {
b, err := exec.Command("/bin/sh", "-c", "ulimit -n").Output()
if err != nil {
log.PanicErrorf(err, "run ulimit -n failed")
}
if v, err := strconv.Atoi(strings.TrimSpace(string(b))); err != nil || v < n {
log.PanicErrorf(err, "ulimit too small: %d, should be at least %d", v, n)
}
}
var ncpu int
if n, ok := utils.ArgumentInteger(d, "--ncpu"); ok {
ncpu = n
} else {
ncpu = 4
}
runtime.GOMAXPROCS(ncpu)
var maxncpu int
if n, ok := utils.ArgumentInteger(d, "--max-ncpu"); ok {
maxncpu = math2.MaxInt(ncpu, n)
} else {
maxncpu = math2.MaxInt(ncpu, runtime.NumCPU())
}
log.Warnf("set ncpu = %d, max-ncpu = %d", ncpu, maxncpu)
if ncpu < maxncpu {
go AutoGOMAXPROCS(ncpu, maxncpu)
}
config := proxy.NewDefaultConfig()
if s, ok := utils.Argument(d, "--config"); ok {
if err := config.LoadFromFile(s); err != nil {
log.PanicErrorf(err, "load config %s failed", s)
}
config.ConfigFileName = s
log.Warnf("option --config = %s", s)
}
models.SetMaxSlotNum(config.MaxSlotNum)
if s, ok := utils.Argument(d, "--host-admin"); ok {
config.HostAdmin = s
log.Warnf("option --host-admin = %s", s)
}
if s, ok := utils.Argument(d, "--host-proxy"); ok {
config.HostProxy = s
log.Warnf("option --host-proxy = %s", s)
}
var dashboard string
if s, ok := utils.Argument(d, "--dashboard"); ok {
dashboard = s
log.Warnf("option --dashboard = %s", s)
}
var coordinator struct {
name string
addr string
auth string
}
switch {
case d["--zookeeper"] != nil:
coordinator.name = "zookeeper"
coordinator.addr = utils.ArgumentMust(d, "--zookeeper")
if d["--zookeeper-auth"] != nil {
coordinator.auth = utils.ArgumentMust(d, "--zookeeper-auth")
}
case d["--etcd"] != nil:
coordinator.name = "etcd"
coordinator.addr = utils.ArgumentMust(d, "--etcd")
if d["--etcd-auth"] != nil {
coordinator.auth = utils.ArgumentMust(d, "--etcd-auth")
}
case d["--filesystem"] != nil:
coordinator.name = "filesystem"
coordinator.addr = utils.ArgumentMust(d, "--filesystem")
}
if coordinator.name != "" {
log.Warnf("option --%s = %s", coordinator.name, coordinator.addr)
}
var slots []*models.Slot
if s, ok := utils.Argument(d, "--fillslots"); ok {
b, err := ioutil.ReadFile(s)
if err != nil {
log.PanicErrorf(err, "load slots from file failed")
}
if err := json.Unmarshal(b, &slots); err != nil {
log.PanicErrorf(err, "decode slots from json failed")
}
}
if s, ok := utils.Argument(d, "--product_name"); ok {
config.ProductName = s
log.Warnf("option --product_name = %s", s)
}
if s, ok := utils.Argument(d, "--product_auth"); ok {
config.ProductAuth = s
log.Warnf("option --product_auth = %s", s)
}
if s, ok := utils.Argument(d, "--session_auth"); ok {
config.SessionAuth = s
log.Warnf("option --session_auth = %s", s)
}
s, err := proxy.New(config)
if err != nil {
log.PanicErrorf(err, "create proxy with config file failed\n%s", config)
}
defer s.Close()
proxy.RefreshPeriod.Set(config.MaxDelayRefreshTimeInterval.Int64())
log.Warnf("create proxy with config\n%s", config)
if s, ok := utils.Argument(d, "--pidfile"); ok {
if pidfile, err := filepath.Abs(s); err != nil {
log.WarnErrorf(err, "parse pidfile = '%s' failed", s)
} else if err := ioutil.WriteFile(pidfile, []byte(strconv.Itoa(os.Getpid())), 0644); err != nil {
log.WarnErrorf(err, "write pidfile = '%s' failed", pidfile)
} else {
defer func() {
if err := os.Remove(pidfile); err != nil {
log.WarnErrorf(err, "remove pidfile = '%s' failed", pidfile)
}
}()
log.Warnf("option --pidfile = %s", pidfile)
}
}
go func() {
defer s.Close()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)
sig := <-c
log.Warnf("[%p] proxy receive signal = '%v'", s, sig)
}()
switch {
case dashboard != "":
go AutoOnlineWithDashboard(s, dashboard)
case coordinator.name != "":
go AutoOnlineWithCoordinator(s, coordinator.name, coordinator.addr, coordinator.auth)
case slots != nil:
go AutoOnlineWithFillSlots(s, slots)
}
for !s.IsClosed() && !s.IsOnline() {
log.Warnf("[%p] proxy waiting online ...", s)
time.Sleep(time.Second)
}
log.Warnf("[%p] proxy is working ...", s)
for !s.IsClosed() {
time.Sleep(time.Second)
}
log.Warnf("[%p] proxy is exiting ...", s)
}
func AutoGOMAXPROCS(min, max int) {
for {
var ncpu = runtime.GOMAXPROCS(0)
var less, more int
var usage [10]float64
for i := 0; i < len(usage) && more == 0; i++ {
u, _, err := utils.CPUUsage(time.Second)
if err != nil {
log.WarnErrorf(err, "get cpu usage failed")
time.Sleep(time.Second * 30)
continue
}
u /= float64(ncpu)
switch {
case u < 0.30 && ncpu > min:
less++
case u > 0.70 && ncpu < max:
more++
}
usage[i] = u
}
var nn = ncpu
switch {
case more != 0:
nn = ncpu + ((max - ncpu + 3) / 4)
case less == len(usage):
nn = ncpu - 1
}
if nn != ncpu {
runtime.GOMAXPROCS(nn)
var b bytes.Buffer
for i, u := range usage {
if i != 0 {
fmt.Fprintf(&b, ", ")
}
fmt.Fprintf(&b, "%.3f", u)
}
log.Warnf("ncpu = %d -> %d, usage = [%s]", ncpu, nn, b.Bytes())
}
}
}
func AutoOnlineWithDashboard(p *proxy.Proxy, dashboard string) {
for i := 0; i < 10; i++ {
if p.IsClosed() || p.IsOnline() {
return
}
if OnlineProxy(p, dashboard) {
return
}
time.Sleep(time.Second * 3)
}
log.Panicf("online proxy failed")
}
func AutoOnlineWithCoordinator(p *proxy.Proxy, name, addr, auth string) {
client, err := models.NewClient(name, addr, auth, time.Minute)
if err != nil {
log.PanicErrorf(err, "create '%s' client to '%s' failed", name, addr)
}
defer client.Close()
for i := 0; i < 30; i++ {
if p.IsClosed() || p.IsOnline() {
return
}
t, err := models.LoadTopom(client, p.Config().ProductName, false)
if err != nil {
log.WarnErrorf(err, "load & decode topom failed")
} else if t != nil && OnlineProxy(p, t.AdminAddr) {
return
}
time.Sleep(time.Second * 3)
}
log.Panicf("online proxy failed")
}
func AutoOnlineWithFillSlots(p *proxy.Proxy, slots []*models.Slot) {
if err := p.FillSlots(slots); err != nil {
log.PanicErrorf(err, "fill slots failed")
}
if err := p.Start(); err != nil {
log.PanicErrorf(err, "start proxy failed")
}
}
func OnlineProxy(p *proxy.Proxy, dashboard string) bool {
client := topom.NewApiClient(dashboard)
t, err := client.Model()
if err != nil {
log.WarnErrorf(err, "rpc fetch model failed")
return false
}
if t.ProductName != p.Config().ProductName {
log.Panicf("unexcepted product name, got model =\n%s", t.Encode())
}
client.SetXAuth(p.Config().ProductName)
if err := client.OnlineProxy(p.Model().AdminAddr); err != nil {
log.WarnErrorf(err, "rpc online proxy failed")
return false
} else {
log.Warnf("rpc online proxy seems OK")
return true
}
}