-
Notifications
You must be signed in to change notification settings - Fork 488
/
template.go
596 lines (507 loc) · 16.9 KB
/
template.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
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// Copyright 2019 PingCAP, Inc.
//
// Licensed 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package member
import (
"bytes"
"fmt"
"text/template"
)
// TODO(aylei): it is hard to maintain script in go literal, we should figure out a better solution
// tidbStartScriptTpl is the template string of tidb start script
// Note: changing this will cause a rolling-update of tidb-servers
var tidbStartScriptTpl = template.Must(template.New("tidb-start-script").Parse(`#!/bin/sh
# This script is used to start tidb containers in kubernetes cluster
# Use DownwardAPIVolumeFiles to store informations of the cluster:
# https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#the-downward-api
#
# runmode="normal/debug"
#
set -uo pipefail
ANNOTATIONS="/etc/podinfo/annotations"
if [[ ! -f "${ANNOTATIONS}" ]]
then
echo "${ANNOTATIONS} does't exist, exiting."
exit 1
fi
source ${ANNOTATIONS} 2>/dev/null
runmode=${runmode:-normal}
if [[ X${runmode} == Xdebug ]]
then
echo "entering debug mode."
tail -f /dev/null
fi
# Use HOSTNAME if POD_NAME is unset for backward compatibility.
POD_NAME=${POD_NAME:-$HOSTNAME}{{ if .FormatClusterDomain }}
pd_url="{{ .Path }}"
encoded_domain_url=$(echo $pd_url | base64 | tr "\n" " " | sed "s/ //g")
discovery_url="${CLUSTER_NAME}-discovery.${NAMESPACE}.svc{{ .FormatClusterDomain }}:10261"
until result=$(wget -qO- -T 3 http://${discovery_url}/verify/${encoded_domain_url} 2>/dev/null | sed 's/http:\/\///g'); do
echo "waiting for the verification of PD endpoints ..."
sleep $((RANDOM % 5))
done
ARGS="--store=tikv \
--advertise-address=${POD_NAME}.${HEADLESS_SERVICE_NAME}.${NAMESPACE}.svc{{ .FormatClusterDomain }} \
--host=0.0.0.0 \
--path=${result} \
{{ else }}
ARGS="--store=tikv \
--advertise-address=${POD_NAME}.${HEADLESS_SERVICE_NAME}.${NAMESPACE}.svc{{ .FormatClusterDomain }} \
--host=0.0.0.0 \
--path={{ .Path }} \{{ end }}
--config=/etc/tidb/tidb.toml
"
if [[ X${BINLOG_ENABLED:-} == Xtrue ]]
then
ARGS="${ARGS} --enable-binlog=true"
fi
SLOW_LOG_FILE=${SLOW_LOG_FILE:-""}
if [[ ! -z "${SLOW_LOG_FILE}" ]]
then
ARGS="${ARGS} --log-slow-query=${SLOW_LOG_FILE:-}"
fi
{{- if .EnablePlugin }}
ARGS="${ARGS} --plugin-dir {{ .PluginDirectory }} --plugin-load {{ .PluginList }} "
{{- end }}
echo "start tidb-server ..."
echo "/tidb-server ${ARGS}"
exec /tidb-server ${ARGS}
`))
type TidbStartScriptModel struct {
EnablePlugin bool
PluginDirectory string
PluginList string
ClusterDomain string
Path string
}
func (t *TidbStartScriptModel) FormatClusterDomain() string {
if len(t.ClusterDomain) > 0 {
return "." + t.ClusterDomain
}
return ""
}
func RenderTiDBStartScript(model *TidbStartScriptModel) (string, error) {
return renderTemplateFunc(tidbStartScriptTpl, model)
}
// pdStartScriptTpl is the pd start script
// Note: changing this will cause a rolling-update of pd cluster
var pdStartScriptTpl = template.Must(template.New("pd-start-script").Parse(`#!/bin/sh
# This script is used to start pd containers in kubernetes cluster
# Use DownwardAPIVolumeFiles to store informations of the cluster:
# https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#the-downward-api
#
# runmode="normal/debug"
#
set -uo pipefail
ANNOTATIONS="/etc/podinfo/annotations"
if [[ ! -f "${ANNOTATIONS}" ]]
then
echo "${ANNOTATIONS} does't exist, exiting."
exit 1
fi
source ${ANNOTATIONS} 2>/dev/null
runmode=${runmode:-normal}
if [[ X${runmode} == Xdebug ]]
then
echo "entering debug mode."
tail -f /dev/null
fi
# Use HOSTNAME if POD_NAME is unset for backward compatibility.
POD_NAME=${POD_NAME:-$HOSTNAME}
# the general form of variable PEER_SERVICE_NAME is: "<clusterName>-pd-peer"
cluster_name=` + "`" + `echo ${PEER_SERVICE_NAME} | sed 's/-pd-peer//'` + "`" +
`
domain="${POD_NAME}.${PEER_SERVICE_NAME}.${NAMESPACE}.svc{{ .FormatClusterDomain }}"
discovery_url="${cluster_name}-discovery.${NAMESPACE}.svc{{ .FormatClusterDomain }}:10261"
encoded_domain_url=` + "`" + `echo ${domain}:2380 | base64 | tr "\n" " " | sed "s/ //g"` + "`" +
`
elapseTime=0
period=1
threshold=30
while true; do
sleep ${period}
elapseTime=$(( elapseTime+period ))
if [[ ${elapseTime} -ge ${threshold} ]]
then
echo "waiting for pd cluster ready timeout" >&2
exit 1
fi
if nslookup ${domain} 2>/dev/null
then
echo "nslookup domain ${domain}.svc success"
break
else
echo "nslookup domain ${domain} failed" >&2
fi
done
ARGS="--data-dir={{ .DataDir }} \
--name={{- if .ClusterDomain }}${domain}{{- else }}${POD_NAME}{{- end }} \
--peer-urls={{ .Scheme }}://0.0.0.0:2380 \
--advertise-peer-urls={{ .Scheme }}://${domain}:2380 \
--client-urls={{ .Scheme }}://0.0.0.0:2379 \
--advertise-client-urls={{ .Scheme }}://${domain}:2379 \
--config=/etc/pd/pd.toml \
"
if [[ -f {{ .DataDir }}/join ]]
then
# The content of the join file is:
# demo-pd-0=http://demo-pd-0.demo-pd-peer.demo.svc:2380,demo-pd-1=http://demo-pd-1.demo-pd-peer.demo.svc:2380
# The --join args must be:
# --join=http://demo-pd-0.demo-pd-peer.demo.svc:2380,http://demo-pd-1.demo-pd-peer.demo.svc:2380
join=` + "`" + `cat {{ .DataDir }}/join | tr "," "\n" | awk -F'=' '{print $2}' | tr "\n" ","` + "`" + `
join=${join%,}
ARGS="${ARGS} --join=${join}"
elif [[ ! -d {{ .DataDir }}/member/wal ]]
then
until result=$(wget -qO- -T 3 http://${discovery_url}/new/${encoded_domain_url} 2>/dev/null); do
echo "waiting for discovery service to return start args ..."
sleep $((RANDOM % 5))
done
ARGS="${ARGS}${result}"
fi
echo "starting pd-server ..."
sleep $((RANDOM % 10))
echo "/pd-server ${ARGS}"
exec /pd-server ${ARGS}
`))
type PDStartScriptModel struct {
Scheme string
DataDir string
ClusterDomain string
}
func (p *PDStartScriptModel) FormatClusterDomain() string {
if len(p.ClusterDomain) > 0 {
return "." + p.ClusterDomain
}
return ""
}
func RenderPDStartScript(model *PDStartScriptModel) (string, error) {
return renderTemplateFunc(pdStartScriptTpl, model)
}
var tikvStartScriptTpl = template.Must(template.New("tikv-start-script").Parse(`#!/bin/sh
# This script is used to start tikv containers in kubernetes cluster
# Use DownwardAPIVolumeFiles to store informations of the cluster:
# https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#the-downward-api
#
# runmode="normal/debug"
#
set -uo pipefail
ANNOTATIONS="/etc/podinfo/annotations"
if [[ ! -f "${ANNOTATIONS}" ]]
then
echo "${ANNOTATIONS} does't exist, exiting."
exit 1
fi
source ${ANNOTATIONS} 2>/dev/null
runmode=${runmode:-normal}
if [[ X${runmode} == Xdebug ]]
then
echo "entering debug mode."
tail -f /dev/null
fi
# Use HOSTNAME if POD_NAME is unset for backward compatibility.
POD_NAME=${POD_NAME:-$HOSTNAME}{{ if .FormatClusterDomain }}
pd_url="{{ .PDAddress }}"
encoded_domain_url=$(echo $pd_url | base64 | tr "\n" " " | sed "s/ //g")
discovery_url="${CLUSTER_NAME}-discovery.${NAMESPACE}.svc{{ .FormatClusterDomain }}:10261"
until result=$(wget -qO- -T 3 http://${discovery_url}/verify/${encoded_domain_url} 2>/dev/null); do
echo "waiting for the verification of PD endpoints ..."
sleep $((RANDOM % 5))
done
ARGS="--pd=${result} \
{{ else }}
ARGS="--pd={{ .PDAddress }} \{{ end }}
--advertise-addr=${POD_NAME}.${HEADLESS_SERVICE_NAME}.${NAMESPACE}.svc{{ .FormatClusterDomain }}:20160 \
--addr=0.0.0.0:20160 \
--status-addr=0.0.0.0:20180 \{{if .EnableAdvertiseStatusAddr }}
--advertise-status-addr={{ .AdvertiseStatusAddr }}:20180 \{{end}}
--data-dir={{ .DataDir }} \
--capacity=${CAPACITY} \
--config=/etc/tikv/tikv.toml
"
if [ ! -z "${STORE_LABELS:-}" ]; then
LABELS=" --labels ${STORE_LABELS} "
ARGS="${ARGS}${LABELS}"
fi
echo "starting tikv-server ..."
echo "/tikv-server ${ARGS}"
exec /tikv-server ${ARGS}
`))
type TiKVStartScriptModel struct {
EnableAdvertiseStatusAddr bool
AdvertiseStatusAddr string
DataDir string
ClusterDomain string
PDAddress string
}
func (t *TiKVStartScriptModel) FormatClusterDomain() string {
if len(t.ClusterDomain) > 0 {
return "." + t.ClusterDomain
}
return ""
}
func RenderTiKVStartScript(model *TiKVStartScriptModel) (string, error) {
return renderTemplateFunc(tikvStartScriptTpl, model)
}
// pumpStartScriptTpl is the template string of pump start script
// Note: changing this will cause a rolling-update of pump cluster
var pumpStartScriptTpl = template.Must(template.New("pump-start-script").Parse(`set -euo pipefail
/pump \
-pd-urls={{ .Scheme }}://{{ .ClusterName }}-pd:2379 \
-L={{ .LogLevel }} \
-advertise-addr=` + "`" + `echo ${HOSTNAME}` + "`" + `.{{ .ClusterName }}-pump{{ .FormatPumpZone }}:8250 \
-config=/etc/pump/pump.toml \
-data-dir=/data \
-log-file=
if [ $? == 0 ]; then
echo $(date -u +"[%Y/%m/%d %H:%M:%S.%3N %:z]") "pump offline, please delete my pod"
tail -f /dev/null
fi`))
type PumpStartScriptModel struct {
Scheme string
ClusterName string
LogLevel string
Namespace string
ClusterDomain string
}
func (pssm *PumpStartScriptModel) FormatPumpZone() string {
if pssm.ClusterDomain != "" {
return fmt.Sprintf(".%s.svc.%s", pssm.Namespace, pssm.ClusterDomain)
}
return ""
}
func RenderPumpStartScript(model *PumpStartScriptModel) (string, error) {
return renderTemplateFunc(pumpStartScriptTpl, model)
}
// tidbInitStartScriptTpl is the template string of tidb initializer start script
var tidbInitStartScriptTpl = template.Must(template.New("tidb-init-start-script").Parse(`import os, sys, time, MySQLdb
host = '{{ .ClusterName }}-tidb'
permit_host = '{{ .PermitHost }}'
port = 4000
retry_count = 0
for i in range(0, 10):
try:
{{- if .TLS }}
conn = MySQLdb.connect(host=host, port=port, user='root', charset='utf8mb4',connect_timeout=5, ssl={'ca': '{{ .CAPath }}', 'cert': '{{ .CertPath }}', 'key': '{{ .KeyPath }}'})
{{- else }}
conn = MySQLdb.connect(host=host, port=port, user='root', connect_timeout=5, charset='utf8mb4')
{{- end }}
except MySQLdb.OperationalError as e:
print(e)
retry_count += 1
time.sleep(1)
continue
break
if retry_count == 10:
sys.exit(1)
{{- if .PasswordSet }}
password_dir = '/etc/tidb/password'
for file in os.listdir(password_dir):
if file.startswith('.'):
continue
user = file
with open(os.path.join(password_dir, file), 'r') as f:
password = f.read()
if user == 'root':
conn.cursor().execute("set password for 'root'@'%%' = %s;", (password,))
else:
conn.cursor().execute("create user %s@%s identified by %s;", (user, permit_host, password,))
{{- end }}
{{- if .InitSQL }}
with open('/data/init.sql', 'r') as sql:
for line in sql.readlines():
conn.cursor().execute(line)
conn.commit()
{{- end }}
if permit_host != '%%':
conn.cursor().execute("update mysql.user set Host=%s where User='root';", (permit_host,))
conn.cursor().execute("flush privileges;")
conn.commit()
conn.close()
`))
type TiDBInitStartScriptModel struct {
ClusterName string
PermitHost string
PasswordSet bool
InitSQL bool
TLS bool
CAPath string
CertPath string
KeyPath string
}
func RenderTiDBInitStartScript(model *TiDBInitStartScriptModel) (string, error) {
return renderTemplateFunc(tidbInitStartScriptTpl, model)
}
// tidbInitInitStartScriptTpl is the template string of tidb initializer init container start script
var tidbInitInitStartScriptTpl = template.Must(template.New("tidb-init-init-start-script").Parse(`trap exit TERM
host={{ .ClusterName }}-tidb
port=4000
while true; do
nc -zv -w 3 $host $port
if [ $? -eq 0 ]; then
break
else
echo "info: failed to connect to $host:$port, sleep 1 second then retry"
sleep 1
fi
done
echo "info: successfully connected to $host:$port, able to initialize TiDB now"
`))
type TiDBInitInitStartScriptModel struct {
ClusterName string
}
func RenderTiDBInitInitStartScript(model *TiDBInitInitStartScriptModel) (string, error) {
return renderTemplateFunc(tidbInitInitStartScriptTpl, model)
}
func renderTemplateFunc(tpl *template.Template, model interface{}) (string, error) {
buff := new(bytes.Buffer)
err := tpl.Execute(buff, model)
if err != nil {
return "", err
}
return buff.String(), nil
}
// dmMasterStartScriptTpl is the dm-master start script
// Note: changing this will cause a rolling-update of dm-master cluster
var dmMasterStartScriptTpl = template.Must(template.New("dm-master-start-script").Parse(`#!/bin/sh
# This script is used to start dm-master containers in kubernetes cluster
# Use DownwardAPIVolumeFiles to store informations of the cluster:
# https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#the-downward-api
#
# runmode="normal/debug"
#
set -uo pipefail
ANNOTATIONS="/etc/podinfo/annotations"
if [[ ! -f "${ANNOTATIONS}" ]]
then
echo "${ANNOTATIONS} does't exist, exiting."
exit 1
fi
source ${ANNOTATIONS} 2>/dev/null
runmode=${runmode:-normal}
if [[ X${runmode} == Xdebug ]]
then
echo "entering debug mode."
tail -f /dev/null
fi
# Use HOSTNAME if POD_NAME is unset for backward compatibility.
POD_NAME=${POD_NAME:-$HOSTNAME}
# the general form of variable PEER_SERVICE_NAME is: "<clusterName>-dm-master-peer"
cluster_name=` + "`" + `echo ${PEER_SERVICE_NAME} | sed 's/-dm-master-peer//'` + "`" +
`
domain="${POD_NAME}.${PEER_SERVICE_NAME}"
discovery_url={{ .DiscoveryURL }}
encoded_domain_url=` + "`" + `echo ${domain}:8291 | base64 | tr "\n" " " | sed "s/ //g"` + "`" +
`
elapseTime=0
period=1
threshold=30
while true; do
sleep ${period}
elapseTime=$(( elapseTime+period ))
if [[ ${elapseTime} -ge ${threshold} ]]
then
echo "waiting for dm-master cluster ready timeout" >&2
exit 1
fi
if nslookup ${domain} 2>/dev/null
then
echo "nslookup domain ${domain} success"
break
else
echo "nslookup domain ${domain} failed" >&2
fi
done
ARGS="--data-dir={{ .DataDir }} \
--name=${POD_NAME} \
--peer-urls={{ .Scheme }}://0.0.0.0:8291 \
--advertise-peer-urls={{ .Scheme }}://${domain}:8291 \
--master-addr=:8261 \
--advertise-addr=${domain}:8261 \
--config=/etc/dm-master/dm-master.toml \
"
if [[ -f {{ .DataDir }}/join ]]
then
# The content of the join file is:
# demo-dm-master-0=http://demo-dm-master-0.demo-dm-master-peer.demo.svc:8291,demo-dm-master-1=http://demo-dm-master-1.demo-dm-master-peer.demo.svc:8291
# The --join args must be:
# --join=http://demo-dm-master-0.demo-dm-master-peer.demo.svc:8261,http://demo-dm-master-1.demo-dm-master-peer.demo.svc:8261
result=$(cat {{ .DataDir }}/join)
ARGS="${ARGS} --initial-cluster=${result}"
elif [[ ! -d {{ .DataDir }}/member/wal ]]
then
until result=$(wget -qO- -T 3 ${discovery_url}/new/${encoded_domain_url}/dm 2>/dev/null); do
echo "waiting for discovery service to return start args ..."
sleep $((RANDOM % 5))
done
ARGS="${ARGS}${result}"
fi
echo "starting dm-master ..."
sleep $((RANDOM % 10))
echo "/dm-master ${ARGS}"
exec /dm-master ${ARGS}
`))
type DMMasterStartScriptModel struct {
Scheme string
DataDir string
DiscoveryURL string
}
func RenderDMMasterStartScript(model *DMMasterStartScriptModel) (string, error) {
return renderTemplateFunc(dmMasterStartScriptTpl, model)
}
// dmWorkerStartScriptTpl is the dm-worker start script
// Note: changing this will cause a rolling-update of dm-worker cluster
var dmWorkerStartScriptTpl = template.Must(template.New("dm-worker-start-script").Parse(`#!/bin/sh
# This script is used to start dm-worker containers in kubernetes cluster
# Use DownwardAPIVolumeFiles to store informations of the cluster:
# https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#the-downward-api
#
# runmode="normal/debug"
#
set -uo pipefail
ANNOTATIONS="/etc/podinfo/annotations"
if [[ ! -f "${ANNOTATIONS}" ]]
then
echo "${ANNOTATIONS} does't exist, exiting."
exit 1
fi
source ${ANNOTATIONS} 2>/dev/null
runmode=${runmode:-normal}
if [[ X${runmode} == Xdebug ]]
then
echo "entering debug mode."
tail -f /dev/null
fi
# Use HOSTNAME if POD_NAME is unset for backward compatibility.
POD_NAME=${POD_NAME:-$HOSTNAME}
# TODO: dm-worker will support data-dir in the future
ARGS="--name=${POD_NAME} \
--join={{ .MasterAddress }} \
--advertise-addr=${POD_NAME}.${HEADLESS_SERVICE_NAME}:8262 \
--worker-addr=0.0.0.0:8262 \
--config=/etc/dm-worker/dm-worker.toml
"
if [ ! -z "${STORE_LABELS:-}" ]; then
LABELS=" --labels ${STORE_LABELS} "
ARGS="${ARGS}${LABELS}"
fi
echo "starting dm-worker ..."
echo "/dm-worker ${ARGS}"
exec /dm-worker ${ARGS}
`))
type DMWorkerStartScriptModel struct {
DataDir string
MasterAddress string
}
func RenderDMWorkerStartScript(model *DMWorkerStartScriptModel) (string, error) {
return renderTemplateFunc(dmWorkerStartScriptTpl, model)
}