/
util.go
286 lines (234 loc) · 6.97 KB
/
util.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
/*
Copyright 2018 Pressinfra SRL
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"bufio"
"database/sql"
"fmt"
"io"
"os"
"path"
"strconv"
"strings"
"github.com/go-ini/ini"
_ "github.com/go-sql-driver/mysql"
"github.com/golang/glog"
api "github.com/presslabs/mysql-operator/pkg/apis/mysql/v1alpha1"
"github.com/presslabs/mysql-operator/pkg/mysqlcluster"
orc "github.com/presslabs/mysql-operator/pkg/util/orchestrator"
)
var (
// BackupPort is the port on which xtrabackup expose backups, 3306
BackupPort = strconv.Itoa(mysqlcluster.HelperXtrabackupPort)
// MysqlPort represents port on wich mysql works
MysqlPort = strconv.Itoa(mysqlcluster.MysqlPort)
// ConfigDir is the mysql configs path, /etc/mysql
ConfigDir = mysqlcluster.ConfVolumeMountPath
// ConfDPath is /etc/mysql/conf.d
ConfDPath = mysqlcluster.ConfDPath
// MountConfigDir is the mounted configs that needs processing
MountConfigDir = mysqlcluster.ConfMapVolumeMountPath
// DataDir is the mysql data. /var/lib/mysql
DataDir = mysqlcluster.DataVolumeMountPath
// ToolsDbName is the name of the tools table
ToolsDbName = "tools"
// ToolsTableName is the name of the init table
ToolsInitTableName = "init"
// UtilityUser is the name of the percona utility user.
UtilityUser = "sys_utility_helper"
// OrcTopologyDir contains the path where the secret with orc credentails is
// mounted.
OrcTopologyDir = mysqlcluster.OrcTopologyDir
NameOfStatefulSet = api.StatefulSet
HelperProbePath = mysqlcluster.HelperProbePath
HelperProbePort = mysqlcluster.HelperProbePort
)
const (
// rcloneConfigFile represents the path to the file that contains rclon
// configs. This path should be the same as defined in docker entrypoint
// script from mysql-helper/docker-entrypoint.sh. /etc/rclone.conf
RcloneConfigFile = "/etc/rclone.conf"
)
func GetHostname() string {
return os.Getenv("HOSTNAME")
}
func GetClusterName() string {
return getEnvValue("MY_CLUSTER_NAME")
}
func GetNamespace() string {
return getEnvValue("MY_NAMESPACE")
}
func GetServiceName() string {
return getEnvValue("MY_SERVICE_NAME")
}
func NodeRole() string {
if GetMasterHost() == GetHostFor(GetServerId()) {
return "master"
}
return "slave"
}
func getOrdinal() int {
hn := GetHostname()
// mysql-master-1
// or
// stateful-ceva-3
l := strings.Split(hn, "-")
for i := len(l) - 1; i >= 0; i-- {
if o, err := strconv.ParseInt(l[i], 10, 8); err == nil {
return int(o)
}
}
return 0
}
func GetServerId() int {
return 100 + getOrdinal()
}
// GetHostFor returns the host for given server id
func GetHostFor(id int) string {
base := api.GetNameForResource(NameOfStatefulSet, GetClusterName())
govSVC := GetServiceName()
namespace := GetNamespace()
return fmt.Sprintf("%s-%d.%s.%s", base, id-100, govSVC, namespace)
}
func getEnvValue(key string) string {
value := os.Getenv(key)
if len(value) == 0 {
glog.Warning(fmt.Sprintf("%s is not set!", key))
}
return value
}
// GetReplUser returns the replication user name from env variable
// MYSQL_REPLICATION_USER
func GetReplUser() string {
return getEnvValue("MYSQL_REPLICATION_USER")
}
// GetReplPass returns the replication password from env variable
// MYSQL_REPLICATION_PASSWORD
func GetReplPass() string {
return getEnvValue("MYSQL_REPLICATION_PASSWORD")
}
// GetExporterUser returns the replication user name from env variable
// MYSQL_METRICS_EXPORTER_USER
func GetExporterUser() string {
return getEnvValue("MYSQL_METRICS_EXPORTER_USER")
}
// GetExporterPass returns the replication password from env variable
// MYSQL_METRICS_EXPORTER_PASSWORD
func GetExporterPass() string {
return getEnvValue("MYSQL_METRICS_EXPORTER_PASSWORD")
}
// GetInitBucket returns the bucket uri from env variable
// INIT_BUCKET_URI
func GetInitBucket() string {
return getEnvValue("INIT_BUCKET_URI")
}
// GetMasterHost returns the master host
func GetMasterHost() string {
orcUri := getOrcUri()
if len(orcUri) == 0 {
glog.Warning("Orchestrator is not used!")
return GetHostFor(100)
}
fqClusterName := fmt.Sprintf("%s.%s", GetClusterName(), GetNamespace())
client := orc.NewFromUri(orcUri)
inst, err := client.Master(fqClusterName)
if err != nil {
glog.Errorf("Failed to connect to orc for finding master, err: %s."+
" Fallback to determine master by its id.", err)
return GetHostFor(100)
}
return inst.Key.Hostname
}
// GetOrcTopologyUser returns the orchestrator topology user from env variable
// MYSQL_ORC_TOPOLOGY_USER
func GetOrcUser() string {
return getEnvValue("MYSQL_ORC_TOPOLOGY_USER")
}
// GetOrcTopologyPass returns the orchestrator topology passowrd from env variable
// MYSQL_ORC_TOPOLOGY_PASSWORD
func GetOrcPass() string {
return getEnvValue("MYSQL_ORC_TOPOLOGY_PASSWORD")
}
func readFileContent(fileName string) string {
f, err := os.Open(fileName)
if err != nil {
glog.Warningf("%s is not set, or can't be readed, see err: %s", fileName, err)
return ""
}
defer f.Close()
scanner := bufio.NewScanner(f)
if !scanner.Scan() {
glog.Warningf("can't scan file: %s", fileName)
return ""
}
return scanner.Text()
}
func GetMySQLConnectionString() (dsn string, err error) {
cnfPath := path.Join(ConfigDir, "client.cnf")
cfg, err := ini.Load(cnfPath)
if err != nil {
return "", fmt.Errorf("Could not open %s: %s", cnfPath, err)
}
client := cfg.Section("client")
host := client.Key("host").String()
user := client.Key("user").String()
passowrd := client.Key("password").String()
port, err := client.Key("port").Int()
if err != nil {
return "", fmt.Errorf("Invalid port in %s: %s", cnfPath, err)
}
dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/?timeout=5s&multiStatements=true",
user, passowrd, host, port,
)
return
}
func RunQuery(q string) (err error) {
dsn, err := GetMySQLConnectionString()
if err != nil {
glog.Warningf("Could not get mysql connection dsn: %s", err)
return
}
db, err := sql.Open("mysql", dsn)
if err != nil {
glog.Warningf("Could not open mysql connection: %s", err)
return
}
if _, err := db.Query(q); err != nil {
glog.V(2).Infof("QUERY: %s", q)
glog.Warningf("Could not query mysql: %s", err)
return err
}
return
}
func getOrcUri() string {
return getEnvValue("ORCHESTRATOR_URI")
}
// CopyFile the src file to dst. Any existing file will be overwritten and will not
// copy file attributes.
func CopyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
return out.Close()
}