|
| 1 | +package mysqlengine |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "math" |
| 9 | + "regexp" |
| 10 | + "slices" |
| 11 | + "strconv" |
| 12 | + "strings" |
| 13 | + |
| 14 | + "github.com/blackbirdworks/gopherstack/pkgs/container" |
| 15 | +) |
| 16 | + |
| 17 | +const headLimit = 512 |
| 18 | + |
| 19 | +var ( |
| 20 | + // ErrInvalidVariable reports a server variable name or value the engine refuses to put into SQL. |
| 21 | + ErrInvalidVariable = errors.New("mysqlengine: invalid server variable") |
| 22 | + // ErrUnsupported reports an operation the server's version cannot perform. |
| 23 | + ErrUnsupported = errors.New("mysqlengine: unsupported by this server version") |
| 24 | + // ErrExecUnsupported is returned when the container runtime cannot relay standard input to a command. |
| 25 | + ErrExecUnsupported = errors.New("mysqlengine: the container runtime cannot run commands with standard input") |
| 26 | + // ErrInvalidPassword is returned when the root password cannot be handed to a client tool on standard input. |
| 27 | + ErrInvalidPassword = errors.New("mysqlengine: the root password cannot be passed to a client tool") |
| 28 | + |
| 29 | + varNameRE = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) |
| 30 | + canonicalNumberRE = regexp.MustCompile(`^-?(0|[1-9][0-9]*)(\.[0-9]+)?$`) |
| 31 | +) |
| 32 | + |
| 33 | +// protectedVariable reports a variable that points the server at files, programs or plugins, changes who can |
| 34 | +// reach it, or that the emulator itself relies on; SetVariable refuses it. |
| 35 | +func protectedVariable(name string) bool { |
| 36 | + return strings.HasPrefix(name, "ssl_") || slices.Contains([]string{ |
| 37 | + "secure_file_priv", |
| 38 | + "plugin_dir", |
| 39 | + "init_file", |
| 40 | + "general_log_file", |
| 41 | + "slow_query_log_file", |
| 42 | + "local_infile", |
| 43 | + "port", |
| 44 | + "bind_address", |
| 45 | + "admin_address", |
| 46 | + "log_bin", |
| 47 | + "log_bin_basename", |
| 48 | + "log_bin_index", |
| 49 | + "log_error", |
| 50 | + "datadir", |
| 51 | + "basedir", |
| 52 | + "socket", |
| 53 | + "tmpdir", |
| 54 | + "skip_grant_tables", |
| 55 | + "skip_networking", |
| 56 | + "read_only", |
| 57 | + "super_read_only", |
| 58 | + "server_id", |
| 59 | + "gtid_mode", |
| 60 | + "enforce_gtid_consistency", |
| 61 | + "sql_log_bin", |
| 62 | + "lower_case_table_names", |
| 63 | + "early_plugin_load", |
| 64 | + "plugin_load", |
| 65 | + "plugin_load_add", |
| 66 | + "lc_messages_dir", |
| 67 | + "innodb_data_home_dir", |
| 68 | + "innodb_log_group_home_dir", |
| 69 | + "innodb_undo_directory", |
| 70 | + "innodb_directories", |
| 71 | + "innodb_force_recovery", |
| 72 | + "named_pipe", |
| 73 | + "shared_memory", |
| 74 | + "secure_log_path", |
| 75 | + "mysqlx_port", |
| 76 | + "mysqlx_bind_address", |
| 77 | + "mysqlx_socket", |
| 78 | + }, name) |
| 79 | +} |
| 80 | + |
| 81 | +// CheckVariable reports whether SetVariable would accept the name, without touching a server. |
| 82 | +func CheckVariable(name string) error { |
| 83 | + if !varNameRE.MatchString(name) { |
| 84 | + return fmt.Errorf("%w: name", ErrInvalidVariable) |
| 85 | + } |
| 86 | + |
| 87 | + if protectedVariable(name) { |
| 88 | + return fmt.Errorf("%w: %s is managed by the emulator", ErrInvalidVariable, name) |
| 89 | + } |
| 90 | + |
| 91 | + return nil |
| 92 | +} |
| 93 | + |
| 94 | +// SetVariable persists a global system variable (SET PERSIST). static variables use SET PERSIST_ONLY and take |
| 95 | +// effect after the next restart; reset restores the default. name is matched against an identifier pattern and |
| 96 | +// the value is bound as a parameter. MySQL 5.7 has no SET PERSIST, so it only supports dynamic variables, set for |
| 97 | +// the life of the server. |
| 98 | +func (s *Server) SetVariable(ctx context.Context, name, value string, reset, static bool) error { |
| 99 | + if err := CheckVariable(name); err != nil { |
| 100 | + return err |
| 101 | + } |
| 102 | + |
| 103 | + verb := "SET PERSIST " |
| 104 | + if static { |
| 105 | + verb = "SET PERSIST_ONLY " |
| 106 | + } |
| 107 | + |
| 108 | + if s.noPersist() { |
| 109 | + if static { |
| 110 | + return ErrUnsupported |
| 111 | + } |
| 112 | + |
| 113 | + verb = "SET GLOBAL " |
| 114 | + } |
| 115 | + |
| 116 | + if reset { |
| 117 | + return s.exec(ctx, verb+name+" = DEFAULT") |
| 118 | + } |
| 119 | + |
| 120 | + return s.exec(ctx, verb+name+" = ?", variableArg(value)) |
| 121 | +} |
| 122 | + |
| 123 | +// noPersist reports a MySQL 5.7 server, which has no SET PERSIST: its changes last until the server restarts. |
| 124 | +func (s *Server) noPersist() bool { return strings.HasSuffix(s.spec.Image, ":5.7") } |
| 125 | + |
| 126 | +// variableArg binds canonical decimal numbers as numbers (SET rejects a quoted string for a numeric variable) and |
| 127 | +// everything else, including "007", "1e3" and "+5", as the string it is. |
| 128 | +func variableArg(v string) any { |
| 129 | + if !canonicalNumberRE.MatchString(v) { |
| 130 | + return v |
| 131 | + } |
| 132 | + |
| 133 | + if n, err := strconv.ParseInt(v, 10, 64); err == nil { |
| 134 | + return n |
| 135 | + } |
| 136 | + |
| 137 | + if f, err := strconv.ParseFloat(v, 64); err == nil && !math.IsNaN(f) && !math.IsInf(f, 0) { |
| 138 | + return f |
| 139 | + } |
| 140 | + |
| 141 | + return v |
| 142 | +} |
| 143 | + |
| 144 | +// SetReadOnly turns super_read_only (and read_only) on or off, persisted across restarts except on MySQL 5.7. |
| 145 | +func (s *Server) SetReadOnly(ctx context.Context, on bool) error { |
| 146 | + for _, stmt := range readOnlyStmts(on, s.noPersist()) { |
| 147 | + if err := s.exec(ctx, stmt); err != nil { |
| 148 | + return err |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + return nil |
| 153 | +} |
| 154 | + |
| 155 | +func readOnlyStmts(on, noPersist bool) []string { |
| 156 | + v, verb := "OFF", "SET PERSIST " |
| 157 | + if on { |
| 158 | + v = "ON" |
| 159 | + } |
| 160 | + |
| 161 | + if noPersist { |
| 162 | + verb = "SET GLOBAL " |
| 163 | + } |
| 164 | + |
| 165 | + return []string{verb + "read_only = " + v, verb + "super_read_only = " + v} |
| 166 | +} |
| 167 | + |
| 168 | +type headBuf struct{ buf []byte } |
| 169 | + |
| 170 | +func (h *headBuf) Write(p []byte) (int, error) { |
| 171 | + if room := headLimit - len(h.buf); room > 0 { |
| 172 | + h.buf = append(h.buf, p[:min(room, len(p))]...) |
| 173 | + } |
| 174 | + |
| 175 | + return len(p), nil |
| 176 | +} |
| 177 | + |
| 178 | +// clientScript runs a mysql client tool with the root password read from the first line of standard input, so it |
| 179 | +// is never in argv or the exec environment record. |
| 180 | +const clientScript = `IFS= read -r pw; MYSQL_PWD="$pw" exec "$@"` |
| 181 | + |
| 182 | +func (s *Server) stdinRun(ctx context.Context, cmd []string, in io.Reader, out io.Writer) (int, error) { |
| 183 | + x, ok := s.e.cfg.Runtime.(container.StdinExecer) |
| 184 | + if !ok { |
| 185 | + return 0, ErrExecUnsupported |
| 186 | + } |
| 187 | + |
| 188 | + pw := s.pass() |
| 189 | + if strings.ContainsAny(pw, "\r\n") { |
| 190 | + return 0, ErrInvalidPassword |
| 191 | + } |
| 192 | + |
| 193 | + stdin := io.Reader(strings.NewReader(pw + "\n")) |
| 194 | + if in != nil { |
| 195 | + stdin = io.MultiReader(stdin, in) |
| 196 | + } |
| 197 | + |
| 198 | + code, err := x.ExecStdin( |
| 199 | + ctx, |
| 200 | + s.container(), |
| 201 | + append([]string{"sh", "-c", clientScript, "sh"}, cmd...), |
| 202 | + stdin, |
| 203 | + out, |
| 204 | + 0, |
| 205 | + 0, |
| 206 | + ) |
| 207 | + if err != nil { |
| 208 | + return 0, fmt.Errorf("%w: exec: %s", errExec, s.scrub(err.Error())) |
| 209 | + } |
| 210 | + |
| 211 | + return code, nil |
| 212 | +} |
| 213 | + |
| 214 | +// DumpTo streams a logical dump of dbs to w; accounts are not included. Standard error is discarded. |
| 215 | +func (s *Server) DumpTo(ctx context.Context, dbs []string, w io.Writer) error { |
| 216 | + if len(dbs) == 0 { |
| 217 | + return nil |
| 218 | + } |
| 219 | + |
| 220 | + for _, d := range dbs { |
| 221 | + if !dbNameRE.MatchString(d) { |
| 222 | + return ErrInvalidIdentifier |
| 223 | + } |
| 224 | + } |
| 225 | + |
| 226 | + cmd := append([]string{ |
| 227 | + mysqldumpBin, "-u" + RootUser, argSingleTx, argRoutines, argEvents, argTriggers, |
| 228 | + argAddDrop, argGtidOff, argDatabases, |
| 229 | + }, dbs...) |
| 230 | + |
| 231 | + cmd = append([]string{"sh", "-c", `exec "$@" 2>/dev/null`, "sh"}, cmd...) |
| 232 | + |
| 233 | + code, err := s.stdinRun(ctx, cmd, nil, w) |
| 234 | + if err != nil { |
| 235 | + return err |
| 236 | + } |
| 237 | + |
| 238 | + if code != 0 { |
| 239 | + return fmt.Errorf("%w: mysqldump exited %d", errExec, code) |
| 240 | + } |
| 241 | + |
| 242 | + return nil |
| 243 | +} |
| 244 | + |
| 245 | +// RestoreFrom runs a SQL stream such as DumpTo's output. |
| 246 | +func (s *Server) RestoreFrom(ctx context.Context, r io.Reader) error { |
| 247 | + var head headBuf |
| 248 | + |
| 249 | + code, err := s.stdinRun(ctx, []string{mysqlBin, "-u" + RootUser}, r, &head) |
| 250 | + if err != nil { |
| 251 | + return err |
| 252 | + } |
| 253 | + |
| 254 | + if code != 0 { |
| 255 | + return fmt.Errorf("%w: mysql exited %d: %s", errExec, code, s.scrub(strings.TrimSpace(string(head.buf)))) |
| 256 | + } |
| 257 | + |
| 258 | + return nil |
| 259 | +} |
| 260 | + |
| 261 | +var dbNameRE = regexp.MustCompile(`^[A-Za-z0-9_$][A-Za-z0-9_$-]{0,63}$`) |
0 commit comments