-
Notifications
You must be signed in to change notification settings - Fork 118
/
add_mysql.go
253 lines (216 loc) · 9.25 KB
/
add_mysql.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
// Copyright 2019 Percona LLC
//
// 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 management
import (
"fmt"
"strconv"
"strings"
"github.com/AlekSi/pointer"
"github.com/alecthomas/units"
"github.com/pkg/errors"
"github.com/percona/pmm/admin/agentlocal"
"github.com/percona/pmm/admin/commands"
"github.com/percona/pmm/api/managementpb/json/client"
mysql "github.com/percona/pmm/api/managementpb/json/client/my_sql"
)
const (
// MysqlQuerySourceSlowLog defines available source name for profiler.
MysqlQuerySourceSlowLog = "slowlog"
// MysqlQuerySourcePerfSchema defines available source name for profiler.
MysqlQuerySourcePerfSchema = "perfschema"
// MysqlQuerySourceNone defines available source name for profiler.
MysqlQuerySourceNone = "none"
)
var addMySQLResultT = commands.ParseTemplate(`
MySQL Service added.
Service ID : {{ .Service.ServiceID }}
Service name: {{ .Service.ServiceName }}
{{ .TablestatStatus }}
`)
type addMySQLResult struct {
Service *mysql.AddMySQLOKBodyService `json:"service"`
MysqldExporter *mysql.AddMySQLOKBodyMysqldExporter `json:"mysqld_exporter,omitempty"`
TableCount int32 `json:"table_count,omitempty"`
}
func (res *addMySQLResult) Result() {}
func (res *addMySQLResult) String() string {
return commands.RenderTemplate(addMySQLResultT, res)
}
func (res *addMySQLResult) TablestatStatus() string {
if res.MysqldExporter == nil {
return ""
}
status := "enabled"
if res.MysqldExporter.TablestatsGroupDisabled {
status = "disabled"
}
s := "Table statistics collection " + status
switch {
case res.MysqldExporter.TablestatsGroupTableLimit == 0: // no limit
s += " (the table count limit is not set)."
case res.MysqldExporter.TablestatsGroupTableLimit < 0: // always disabled
s += " (always)."
default:
count := "unknown"
if res.TableCount > 0 {
count = strconv.Itoa(int(res.TableCount))
}
s += fmt.Sprintf(" (the limit is %d, the actual table count is %s).", res.MysqldExporter.TablestatsGroupTableLimit, count)
}
return s
}
// AddMySQLCommand is used by Kong for CLI flags and commands.
type AddMySQLCommand struct {
ServiceName string `name:"name" arg:"" default:"${hostname}-mysql" help:"Service name (autodetected default: ${hostname}-mysql)"`
Address string `arg:"" optional:"" help:"MySQL address and port (default: 127.0.0.1:3306)"`
Socket string `help:"Path to MySQL socket"`
NodeID string `help:"Node ID (default is autodetected)"`
PMMAgentID string `help:"The pmm-agent identifier which runs this instance (default is autodetected)"`
Username username `help:"MySQL username"`
Password string `help:"MySQL password"`
AgentPassword string `help:"Custom password for /metrics endpoint"`
ServiceParamsSource string `help:"Path to file with service parameters"`
// TODO add "auto", make it default
QuerySource string `default:"${mysqlQuerySourceDefault}" enum:"${mysqlQuerySourcesEnum}" help:"Source of SQL queries, one of: ${mysqlQuerySourcesEnum} (default: ${mysqlQuerySourceDefault})"`
MaxQueryLength int32 `placeholder:"NUMBER" help:"Limit query length in QAN (default: server-defined; -1: no limit)"`
DisableQueryExamples bool `name:"disable-queryexamples" help:"Disable collection of query examples"`
MaxSlowlogFileSize units.Base2Bytes `name:"size-slow-logs" placeholder:"size" help:"Rotate slow log file at this size (default: server-defined; negative value disables rotation). Ex.: 1GiB"`
DisableTablestats bool `help:"Disable table statistics collection"`
DisableTablestatsLimit uint16 `placeholder:"NUMBER" help:"Table statistics collection will be disabled if there are more than specified number of tables (default: server-defined)"`
Environment string `help:"Environment name"`
Cluster string `help:"Cluster name"`
ReplicationSet string `help:"Replication set name"`
CustomLabels map[string]string `mapsep:"," help:"Custom user-assigned labels"`
SkipConnectionCheck bool `help:"Skip connection check"`
TLS bool `help:"Use TLS to connect to the database"`
TLSSkipVerify bool `help:"Skip TLS certificates validation"`
TLSCaFile string `name:"tls-ca" help:"Path to certificate authority certificate file"`
TLSCertFile string `name:"tls-cert" help:"Path to client certificate file"`
TLSKeyFile string `name:"tls-key" help:"Path to client key file"`
CreateUser bool `hidden:"" help:"Create pmm user"`
MetricsMode string `enum:"${metricsModesEnum}" default:"auto" help:"Metrics flow mode, can be push - agent will push metrics, pull - server scrape metrics from agent or auto - chosen by server"`
DisableCollectors []string `help:"Comma-separated list of collector names to exclude from exporter"`
AddCommonFlags
AddLogLevelNoFatalFlags
}
func (cmd *AddMySQLCommand) GetServiceName() string {
return cmd.ServiceName
}
// GetDefaultUsername Default username for mysql connections.
func (cmd *AddMySQLCommand) GetDefaultUsername() string {
return "root"
}
func (cmd *AddMySQLCommand) GetAddress() string {
return cmd.Address
}
func (cmd *AddMySQLCommand) GetDefaultAddress() string {
return "127.0.0.1:3306"
}
func (cmd *AddMySQLCommand) GetSocket() string {
return cmd.Socket
}
func (cmd *AddMySQLCommand) RunCmd() (commands.Result, error) {
customLabels := commands.ParseCustomLabels(cmd.CustomLabels)
if cmd.CreateUser {
return nil, errors.New("Unrecognized option. To create a user, see " +
"'https://www.percona.com/doc/percona-monitoring-and-management/2.x/concepts/services-mysql.html#pmm-conf-mysql-user-account-creating'")
}
var (
err error
tlsCa, tlsCert, tlsKey string
)
if cmd.TLS {
tlsCa, err = commands.ReadFile(cmd.TLSCaFile)
if err != nil {
return nil, err
}
tlsCert, err = commands.ReadFile(cmd.TLSCertFile)
if err != nil {
return nil, err
}
tlsKey, err = commands.ReadFile(cmd.TLSKeyFile)
if err != nil {
return nil, err
}
}
if cmd.PMMAgentID == "" || cmd.NodeID == "" {
status, err := agentlocal.GetStatus(agentlocal.DoNotRequestNetworkInfo)
if err != nil {
return nil, err
}
if cmd.PMMAgentID == "" {
cmd.PMMAgentID = status.AgentID
}
if cmd.NodeID == "" {
cmd.NodeID = status.NodeID
}
}
if cmd.ServiceParamsSource == "" && !usernameParameterSpecified {
cmd.Username = username(cmd.GetDefaultUsername())
}
serviceName, socket, host, port, err := processGlobalAddFlagsWithSocket(cmd, cmd.AddCommonFlags)
if err != nil {
return nil, err
}
tablestatsGroupTableLimit := int32(cmd.DisableTablestatsLimit)
if cmd.DisableTablestats {
if tablestatsGroupTableLimit != 0 {
return nil, errors.Errorf("both --disable-tablestats and --disable-tablestats-limit are passed")
}
tablestatsGroupTableLimit = -1
}
params := &mysql.AddMySQLParams{
Body: mysql.AddMySQLBody{
NodeID: cmd.NodeID,
ServiceName: serviceName,
Address: host,
Socket: socket,
Port: int64(port),
PMMAgentID: cmd.PMMAgentID,
Environment: cmd.Environment,
Cluster: cmd.Cluster,
ReplicationSet: cmd.ReplicationSet,
Username: string(cmd.Username),
Password: cmd.Password,
AgentPassword: cmd.AgentPassword,
CustomLabels: customLabels,
ServiceParamsSource: cmd.ServiceParamsSource,
QANMysqlSlowlog: cmd.QuerySource == MysqlQuerySourceSlowLog,
QANMysqlPerfschema: cmd.QuerySource == MysqlQuerySourcePerfSchema,
SkipConnectionCheck: cmd.SkipConnectionCheck,
MaxQueryLength: cmd.MaxQueryLength,
DisableQueryExamples: cmd.DisableQueryExamples,
MaxSlowlogFileSize: strconv.FormatInt(int64(cmd.MaxSlowlogFileSize), 10),
TLS: cmd.TLS,
TLSSkipVerify: cmd.TLSSkipVerify,
TLSCa: tlsCa,
TLSCert: tlsCert,
TLSKey: tlsKey,
TablestatsGroupTableLimit: tablestatsGroupTableLimit,
MetricsMode: pointer.ToString(strings.ToUpper(cmd.MetricsMode)),
DisableCollectors: commands.ParseDisableCollectors(cmd.DisableCollectors),
LogLevel: &cmd.AddLogLevel,
},
Context: commands.Ctx,
}
resp, err := client.Default.MySQL.AddMySQL(params)
if err != nil {
return nil, err
}
return &addMySQLResult{
Service: resp.Payload.Service,
MysqldExporter: resp.Payload.MysqldExporter,
TableCount: resp.Payload.TableCount,
}, nil
}