├── .gitignore ├── README.md ├── LICENSE └── mars.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # backup folders 14 | daily/ 15 | monthly/ 16 | weekly/ 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Mars 2 | ====== 3 | 4 | ### Overview 5 | Mars is a tool for backing up multiple MySQL databases with multiples options. The backups are outputted as a .tar.gz and are stored locally, there is also support for retention in days/weeks/months 6 | 7 | 8 | ### Usage 9 | 10 | ``` 11 | $ go run mars.go -help 12 | -hostname string 13 | Hostname of the mysql server to connect to (default "localhost") 14 | -bind string 15 | Port of the mysql server to connect to (default "3306") 16 | -password string 17 | password of the mysql server to connect to (default "1234") 18 | -username string 19 | username of the mysql server to connect to (default "root") 20 | -additionals string 21 | Additional parameters that will be appended to mysqldump command 22 | -tablethreshold int 23 | Do not split mysqldumps, if rowcount of table is less than dbthreshold value for table (default 5000000) 24 | -batchsize int 25 | Split mysqldumps in order to get each file contains batchsize number of records (default 1000000) 26 | -databases string 27 | List of databases as comma seperated values to dump. OBS: If not specified, --all-databases is the default (default "--all-databases") 28 | -dbthreshold int 29 | Do not split mysqldumps, if total rowcount of tables in database is less than dbthreshold value for whole database (default 10000000) 30 | -excluded-databases string 31 | List of databases excluded to be excluded. OBS: Only valid if -databases is not specified 32 | -forcesplit 33 | Split schema and data dumps even if total rowcount of tables in database is less than dbthreshold value. if false one dump file will be created 34 | -mysqldump-path string 35 | Absolute path for mysqldump executable. (default "/usr/bin/mysqldump") 36 | -output-dir string 37 | Default is the value of os.Getwd(). The backup files will be placed to output-dir {DATE/{DATABASE_NAME}/{DATABASE_NAME}_{TABLENAME|SCHEMA|DATA|ALL}_{TIMESTAMP}.sql 38 | -daily-rotation int 39 | Number of days of retention (default 5) 40 | -weekly-rotation int 41 | Number of weeks of retention (default 2) 42 | -monthly-rotation int 43 | Number of months of retention (default 1) 44 | -verbosity int 45 | 0 = only errors, 1 = important things, 2 = all (default 2) 46 | -test 47 | test 48 | ``` 49 | 50 | ### Rotation folders structure 51 | 52 | **mysqldump-path / daily|weekly|monthly / XXXX-XX-XX / {DATABASE_NAME}-XXXX-XX-XX / {DATABASE_NAME}_{TABLENAME|SCHEMA|DATA|ALL}_{TIMESTAMP}.tar.gz** 53 | 54 | 55 | 56 | 57 | ### Example 58 | Running a backup of only one database: 59 | 60 | $go run mars.go -username "root" -password "123456" -databases "mysql" 61 | 62 | ``` 63 | Running with parameters 64 | { 65 | "HostName": "localhost", 66 | "Bind": "3306", 67 | "UserName": "root", 68 | "Password": "123456", 69 | "Databases": [ 70 | "mysql" 71 | ], 72 | "ExcludedDatabases": [], 73 | "DatabaseRowCountTreshold": 10000000, 74 | "TableRowCountTreshold": 5000000, 75 | "BatchSize": 1000000, 76 | "ForceSplit": false, 77 | "AdditionalMySQLDumpArgs": "", 78 | "Verbosity": 2, 79 | "MySQLDumpPath": "/usr/bin/mysqldump", 80 | "OutputDirectory": "/home/mauro/Downloads/mysql-dump-goland", 81 | "DefaultsProvidedByUser": true, 82 | "ExecutionStartDate": "2017-08-05T22:39:26.473773337-04:00", 83 | "DailyRotation": 5, 84 | "WeeklyRotation": 2, 85 | "MonthlyRotation": 1, 86 | } 87 | Running on operating system : linux 88 | Processing Database : mysql 89 | Getting tables for database : mysql 90 | 30 tables retrived : mysql 91 | options.ForceSplit (false) && totalRowCount (2102) <= options.DatabaseRowCountTreshold (10000000) 92 | Generating single file backup : mysql 93 | mysqldump is being executed with parameters : -hlocalhost -uroot -p1234 -r/home/mauro/Downloads/mysql-dump-goland/daily/2017-08-05/mysql-2017-08-05/mysql_ALL_20170805.sql mysql 94 | mysqldump output is : 95 | Compressing table file : /home/mauro/Downloads/mysql-dump-goland/daily/2017-08-05/mysql-2017-08-05/mysql_ALL_20170805.sql 96 | Single file backup successfull : mysql 97 | Processing done for database : mysql 98 | ``` 99 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /mars.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "archive/tar" 5 | "compress/gzip" 6 | "database/sql" 7 | "encoding/json" 8 | "flag" 9 | "fmt" 10 | "io" 11 | "io/ioutil" 12 | "log" 13 | "os" 14 | "os/exec" 15 | "path" 16 | "path/filepath" 17 | "runtime" 18 | "strconv" 19 | "strings" 20 | "time" 21 | 22 | "github.com/fatih/color" 23 | _ "github.com/go-sql-driver/mysql" 24 | ) 25 | 26 | const ( 27 | // Info messages 28 | Info = 1 << iota // a == 1 (iota has been reset) 29 | 30 | // Warning Messages 31 | Warning = 1 << iota // b == 2 32 | 33 | // Error Messages 34 | Error = 1 << iota // c == 4 35 | ) 36 | 37 | var timeNow = time.Now() 38 | 39 | // Table model struct for table metadata 40 | type Table struct { 41 | TableName string 42 | RowCount int 43 | } 44 | 45 | // Options model for commandline arguments 46 | type Options struct { 47 | HostName string 48 | Bind string 49 | UserName string 50 | Password string 51 | Databases []string 52 | ExcludedDatabases []string 53 | 54 | DatabaseRowCountTreshold int 55 | TableRowCountTreshold int 56 | BatchSize int 57 | ForceSplit bool 58 | 59 | AdditionalMySQLDumpArgs string 60 | 61 | Verbosity int 62 | MySQLDumpPath string 63 | OutputDirectory string 64 | DefaultsProvidedByUser bool 65 | ExecutionStartDate time.Time 66 | 67 | DailyRotation int 68 | WeeklyRotation int 69 | MonthlyRotation int 70 | } 71 | 72 | func main() { 73 | options := GetOptions() 74 | 75 | for _, db := range options.Databases { 76 | printMessage("Processing Database : "+db, options.Verbosity, Info) 77 | 78 | tables := GetTables(options.HostName, options.Bind, options.UserName, options.Password, db, options.Verbosity) 79 | totalRowCount := getTotalRowCount(tables) 80 | 81 | if !options.ForceSplit && totalRowCount <= options.DatabaseRowCountTreshold { 82 | // options.ForceSplit is false 83 | // and if total row count of a database is below defined threshold 84 | // then generate one file containing both schema and data 85 | 86 | printMessage(fmt.Sprintf("options.ForceSplit (%t) && totalRowCount (%d) <= options.DatabaseRowCountTreshold (%d)", options.ForceSplit, totalRowCount, options.DatabaseRowCountTreshold), options.Verbosity, Info) 87 | generateSingleFileBackup(*options, db) 88 | } else if options.ForceSplit && totalRowCount <= options.DatabaseRowCountTreshold { 89 | // options.ForceSplit is true 90 | // and if total row count of a database is below defined threshold 91 | // then generate two files one for schema, one for data 92 | 93 | generateSchemaBackup(*options, db) 94 | generateSingleFileDataBackup(*options, db) 95 | } else if totalRowCount > options.DatabaseRowCountTreshold { 96 | generateSchemaBackup(*options, db) 97 | 98 | for _, table := range tables { 99 | generateTableBackup(*options, db, table) 100 | } 101 | } 102 | 103 | printMessage("Processing done for database : "+db, options.Verbosity, Info) 104 | } 105 | 106 | // Backups retentions validation 107 | BackupRotation(*options) 108 | 109 | } 110 | 111 | // NewTable returns a new Table instance. 112 | func NewTable(tableName string, rowCount int) *Table { 113 | return &Table{ 114 | TableName: tableName, 115 | RowCount: rowCount, 116 | } 117 | } 118 | 119 | // GetTables retrives list of tables with rowcounts 120 | func GetTables(hostname string, bind string, username string, password string, database string, verbosity int) []Table { 121 | printMessage("Getting tables for database : "+database, verbosity, Info) 122 | 123 | db, err := sql.Open("mysql", username+":"+password+"@tcp("+hostname+":"+bind+")/"+database) 124 | 125 | checkErr(err) 126 | 127 | defer db.Close() 128 | 129 | rows, err := db.Query("SELECT table_name as TableName, table_rows as RowCount FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" + database + "'") 130 | checkErr(err) 131 | 132 | var result []Table 133 | 134 | for rows.Next() { 135 | var tableName string 136 | var rowCount int 137 | 138 | err = rows.Scan(&tableName, &rowCount) 139 | checkErr(err) 140 | 141 | result = append(result, *NewTable(tableName, rowCount)) 142 | } 143 | 144 | printMessage(strconv.Itoa(len(result))+" tables retrived : "+database, verbosity, Info) 145 | 146 | return result 147 | } 148 | 149 | // GetDatabaseList retrives list of databases on mysql 150 | func GetDatabaseList(hostname string, bind string, username string, password string, verbosity int) []string { 151 | printMessage("Getting databases : "+hostname, verbosity, Info) 152 | 153 | db, err := sql.Open("mysql", username+":"+password+"@tcp("+hostname+":"+bind+")/mysql") 154 | checkErr(err) 155 | 156 | defer db.Close() 157 | 158 | rows, err := db.Query("SHOW DATABASES") 159 | checkErr(err) 160 | 161 | var result []string 162 | 163 | for rows.Next() { 164 | var databaseName string 165 | 166 | err = rows.Scan(&databaseName) 167 | checkErr(err) 168 | 169 | result = append(result, databaseName) 170 | } 171 | 172 | printMessage(strconv.Itoa(len(result))+" databases retrived : "+hostname, verbosity, Info) 173 | 174 | return result 175 | } 176 | 177 | // NewOptions returns a new Options instance. 178 | func NewOptions(hostname string, bind string, username string, password string, databases string, excludeddatabases string, databasetreshold int, tablethreshold int, batchsize int, forcesplit bool, additionals string, verbosity int, mysqldumppath string, outputDirectory string, defaultsProvidedByUser bool, dailyrotation int, weeklyrotation int, monthlyrotation int) *Options { 179 | 180 | databases = strings.Replace(databases, " ", "", -1) 181 | databases = strings.Replace(databases, " , ", ",", -1) 182 | databases = strings.Replace(databases, ", ", ",", -1) 183 | databases = strings.Replace(databases, " ,", ",", -1) 184 | dbs := strings.Split(databases, ",") 185 | dbs = removeDuplicates(dbs) 186 | 187 | excludeddbs := []string{} 188 | 189 | if databases == "--all-databases" { 190 | 191 | excludeddatabases = excludeddatabases + ",information_schema,performance_schema" 192 | 193 | dbslist := GetDatabaseList(hostname, bind, username, password, verbosity) 194 | databases = strings.Join(dbslist, ",") 195 | 196 | excludeddatabases = strings.Replace(excludeddatabases, " ", "", -1) 197 | excludeddatabases = strings.Replace(excludeddatabases, " , ", ",", -1) 198 | excludeddatabases = strings.Replace(excludeddatabases, ", ", ",", -1) 199 | excludeddatabases = strings.Replace(excludeddatabases, " ,", ",", -1) 200 | excludeddbs := strings.Split(excludeddatabases, ",") 201 | excludeddbs = removeDuplicates(excludeddbs) 202 | 203 | // Databases to not be in the backup 204 | dbs = difference(dbslist, excludeddbs) 205 | } 206 | 207 | return &Options{ 208 | HostName: hostname, 209 | Bind: bind, 210 | UserName: username, 211 | Password: password, 212 | Databases: dbs, 213 | ExcludedDatabases: excludeddbs, 214 | DatabaseRowCountTreshold: databasetreshold, 215 | TableRowCountTreshold: tablethreshold, 216 | BatchSize: batchsize, 217 | ForceSplit: forcesplit, 218 | AdditionalMySQLDumpArgs: additionals, 219 | Verbosity: verbosity, 220 | MySQLDumpPath: mysqldumppath, 221 | OutputDirectory: outputDirectory, 222 | DefaultsProvidedByUser: defaultsProvidedByUser, 223 | ExecutionStartDate: timeNow, 224 | DailyRotation: dailyrotation, 225 | WeeklyRotation: weeklyrotation, 226 | MonthlyRotation: monthlyrotation, 227 | } 228 | } 229 | 230 | func removeDuplicates(elements []string) []string { 231 | // Use map to record duplicates as we find them. 232 | encountered := map[string]bool{} 233 | result := []string{} 234 | 235 | for v := range elements { 236 | if encountered[elements[v]] == true { 237 | // Do not add duplicate. 238 | } else { 239 | // Record this element as an encountered element. 240 | encountered[elements[v]] = true 241 | // Append to result slice. 242 | result = append(result, elements[v]) 243 | } 244 | } 245 | // Return the new slice. 246 | return result 247 | } 248 | 249 | // difference returns the elements in a that aren't in b 250 | func difference(a, b []string) []string { 251 | mb := map[string]bool{} 252 | for _, x := range b { 253 | mb[x] = true 254 | } 255 | ab := []string{} 256 | for _, x := range a { 257 | if _, ok := mb[x]; !ok { 258 | ab = append(ab, x) 259 | } 260 | } 261 | return ab 262 | } 263 | 264 | func generateTableBackup(options Options, db string, table Table) { 265 | printMessage("Generating table backup. Database : "+db+"\t\tTableName : "+table.TableName+"\t\tRowCount : "+strconv.Itoa(table.RowCount), options.Verbosity, Info) 266 | 267 | index := 1 268 | for counter := 0; counter <= table.RowCount; counter += options.BatchSize { 269 | 270 | var args []string 271 | args = append(args, fmt.Sprintf("-h%s", options.HostName)) 272 | args = append(args, fmt.Sprintf("-u%s", options.UserName)) 273 | args = append(args, fmt.Sprintf("-p%s", options.Password)) 274 | 275 | args = append(args, "--no-create-db") 276 | args = append(args, "--skip-triggers") 277 | args = append(args, "--no-create-info") 278 | 279 | if options.AdditionalMySQLDumpArgs != "" { 280 | args = append(args, strings.Split(options.AdditionalMySQLDumpArgs, " ")...) 281 | } 282 | 283 | timestamp := strings.Replace(strings.Replace(options.ExecutionStartDate.Format("2006-01-02"), "-", "", -1), ":", "", -1) 284 | filename := path.Join(options.OutputDirectory, "daily", timeNow.Format("2006-01-02"), db+"-"+options.ExecutionStartDate.Format("2006-01-02"), fmt.Sprintf("%s_%s%d_%s.sql", db, table.TableName, index, timestamp)) 285 | _ = os.Mkdir(path.Dir(filename), os.ModePerm) 286 | 287 | args = append(args, fmt.Sprintf("-r%s", filename)) 288 | 289 | args = append(args, fmt.Sprintf("--where=1=1 LIMIT %d, %d", counter, options.BatchSize)) 290 | 291 | args = append(args, db) 292 | args = append(args, table.TableName) 293 | 294 | cmd := exec.Command(options.MySQLDumpPath, args...) 295 | cmdOut, _ := cmd.StdoutPipe() 296 | cmdErr, _ := cmd.StderrPipe() 297 | 298 | printMessage("mysqldump is being executed with parameters : "+strings.Join(cmd.Args, " "), options.Verbosity, Info) 299 | cmd.Start() 300 | 301 | output, _ := ioutil.ReadAll(cmdOut) 302 | err, _ := ioutil.ReadAll(cmdErr) 303 | cmd.Wait() 304 | 305 | printMessage("mysqldump output is : "+string(output), options.Verbosity, Info) 306 | 307 | if string(err) != "" { 308 | printMessage("mysqldump error is: "+string(err), options.Verbosity, Error) 309 | os.Exit(4) 310 | } 311 | 312 | // Compressing 313 | printMessage("Compressing table file : "+filename, options.Verbosity, Info) 314 | 315 | // set up the output file 316 | file, errcreate := os.Create(filename + ".tar.gz") 317 | 318 | if errcreate != nil { 319 | printMessage("error to create a compressed file: "+filename, options.Verbosity, Error) 320 | os.Exit(4) 321 | } 322 | 323 | defer file.Close() 324 | // set up the gzip writer 325 | gw := gzip.NewWriter(file) 326 | defer gw.Close() 327 | tw := tar.NewWriter(gw) 328 | defer tw.Close() 329 | 330 | if errcompress := Compress(tw, filename); errcompress != nil { 331 | printMessage("error to compress file: "+filename, options.Verbosity, Error) 332 | os.Exit(4) 333 | } 334 | 335 | index++ 336 | } 337 | 338 | printMessage("Table backup successfull. Database : "+db+"\t\tTableName : "+table.TableName, options.Verbosity, Info) 339 | } 340 | 341 | func generateSchemaBackup(options Options, db string) { 342 | printMessage("Generating schema backup : "+db, options.Verbosity, Info) 343 | 344 | var args []string 345 | args = append(args, fmt.Sprintf("-h%s", options.HostName)) 346 | args = append(args, fmt.Sprintf("-u%s", options.UserName)) 347 | args = append(args, fmt.Sprintf("-p%s", options.Password)) 348 | 349 | args = append(args, "--no-data") 350 | 351 | if options.AdditionalMySQLDumpArgs != "" { 352 | args = append(args, strings.Split(options.AdditionalMySQLDumpArgs, " ")...) 353 | } 354 | 355 | timestamp := strings.Replace(strings.Replace(options.ExecutionStartDate.Format("2006-01-02"), "-", "", -1), ":", "", -1) 356 | filename := path.Join(options.OutputDirectory, "daily", timeNow.Format("2006-01-02"), db+"-"+options.ExecutionStartDate.Format("2006-01-02"), fmt.Sprintf("%s_%s_%s.sql", db, "SCHEMA", timestamp)) 357 | _ = os.Mkdir(path.Dir(filename), os.ModePerm) 358 | 359 | args = append(args, fmt.Sprintf("-r%s", filename)) 360 | 361 | args = append(args, db) 362 | 363 | printMessage("mysqldump is being executed with parameters : "+strings.Join(args, " "), options.Verbosity, Info) 364 | 365 | cmd := exec.Command(options.MySQLDumpPath, args...) 366 | cmdOut, _ := cmd.StdoutPipe() 367 | cmdErr, _ := cmd.StderrPipe() 368 | 369 | cmd.Start() 370 | 371 | output, _ := ioutil.ReadAll(cmdOut) 372 | err, _ := ioutil.ReadAll(cmdErr) 373 | cmd.Wait() 374 | 375 | printMessage("mysqldump output is : "+string(output), options.Verbosity, Info) 376 | 377 | if string(err) != "" { 378 | printMessage("mysqldump error is: "+string(err), options.Verbosity, Error) 379 | os.Exit(4) 380 | } 381 | 382 | // Compressing 383 | printMessage("Compressing table file : "+filename, options.Verbosity, Info) 384 | 385 | // set up the output file 386 | file, errcreate := os.Create(filename + ".tar.gz") 387 | 388 | if errcreate != nil { 389 | printMessage("error to create a compressed file: "+filename, options.Verbosity, Error) 390 | os.Exit(4) 391 | } 392 | 393 | defer file.Close() 394 | // set up the gzip writer 395 | gw := gzip.NewWriter(file) 396 | defer gw.Close() 397 | tw := tar.NewWriter(gw) 398 | defer tw.Close() 399 | 400 | if errcompress := Compress(tw, filename); errcompress != nil { 401 | printMessage("error to compress file: "+filename, options.Verbosity, Error) 402 | os.Exit(4) 403 | } 404 | 405 | printMessage("Schema backup successfull : "+db, options.Verbosity, Info) 406 | } 407 | 408 | func generateSingleFileDataBackup(options Options, db string) { 409 | printMessage("Generating single file data backup : "+db, options.Verbosity, Info) 410 | 411 | var args []string 412 | args = append(args, fmt.Sprintf("-h%s", options.HostName)) 413 | args = append(args, fmt.Sprintf("-u%s", options.UserName)) 414 | args = append(args, fmt.Sprintf("-p%s", options.Password)) 415 | 416 | args = append(args, "--no-create-db") 417 | args = append(args, "--skip-triggers") 418 | args = append(args, "--no-create-info") 419 | 420 | if options.AdditionalMySQLDumpArgs != "" { 421 | args = append(args, strings.Split(options.AdditionalMySQLDumpArgs, " ")...) 422 | } 423 | 424 | timestamp := strings.Replace(strings.Replace(options.ExecutionStartDate.Format("2006-01-02"), "-", "", -1), ":", "", -1) 425 | filename := path.Join(options.OutputDirectory, "daily", timeNow.Format("2006-01-02"), db+"-"+options.ExecutionStartDate.Format("2006-01-02"), fmt.Sprintf("%s_%s_%s.sql", db, "DATA", timestamp)) 426 | _ = os.Mkdir(path.Dir(filename), os.ModePerm) 427 | 428 | args = append(args, fmt.Sprintf("-r%s", filename)) 429 | 430 | args = append(args, db) 431 | 432 | printMessage("mysqldump is being executed with parameters : "+strings.Join(args, " "), options.Verbosity, Info) 433 | 434 | cmd := exec.Command(options.MySQLDumpPath, args...) 435 | cmdOut, _ := cmd.StdoutPipe() 436 | cmdErr, _ := cmd.StderrPipe() 437 | 438 | cmd.Start() 439 | 440 | output, _ := ioutil.ReadAll(cmdOut) 441 | err, _ := ioutil.ReadAll(cmdErr) 442 | cmd.Wait() 443 | 444 | printMessage("mysqldump output is : "+string(output), options.Verbosity, Info) 445 | 446 | if string(err) != "" { 447 | printMessage("mysqldump error is: "+string(err), options.Verbosity, Error) 448 | os.Exit(4) 449 | } 450 | 451 | // Compressing 452 | printMessage("Compressing table file : "+filename, options.Verbosity, Info) 453 | 454 | // set up the output file 455 | file, errcreate := os.Create(filename + ".tar.gz") 456 | 457 | if errcreate != nil { 458 | printMessage("error to create a compressed file: "+filename, options.Verbosity, Error) 459 | os.Exit(4) 460 | } 461 | 462 | defer file.Close() 463 | // set up the gzip writer 464 | gw := gzip.NewWriter(file) 465 | defer gw.Close() 466 | tw := tar.NewWriter(gw) 467 | defer tw.Close() 468 | 469 | if errcompress := Compress(tw, filename); errcompress != nil { 470 | printMessage("error to compress file: "+filename, options.Verbosity, Error) 471 | os.Exit(4) 472 | } 473 | 474 | printMessage("Single file data backup successfull : "+db, options.Verbosity, Info) 475 | } 476 | 477 | func generateSingleFileBackup(options Options, db string) { 478 | printMessage("Generating single file backup : "+db, options.Verbosity, Info) 479 | 480 | var args []string 481 | args = append(args, fmt.Sprintf("-h%s", options.HostName)) 482 | args = append(args, fmt.Sprintf("-u%s", options.UserName)) 483 | args = append(args, fmt.Sprintf("-p%s", options.Password)) 484 | 485 | if options.AdditionalMySQLDumpArgs != "" { 486 | args = append(args, strings.Split(options.AdditionalMySQLDumpArgs, " ")...) 487 | } 488 | 489 | timestamp := strings.Replace(strings.Replace(options.ExecutionStartDate.Format("2006-01-02"), "-", "", -1), ":", "", -1) 490 | filename := path.Join(options.OutputDirectory, "daily", timeNow.Format("2006-01-02"), db+"-"+options.ExecutionStartDate.Format("2006-01-02"), fmt.Sprintf("%s_%s_%s.sql", db, "ALL", timestamp)) 491 | _ = os.Mkdir(path.Dir(filename), os.ModePerm) 492 | 493 | args = append(args, fmt.Sprintf("-r%s", filename)) 494 | 495 | args = append(args, db) 496 | 497 | printMessage("mysqldump is being executed with parameters : "+strings.Join(args, " "), options.Verbosity, Info) 498 | 499 | cmd := exec.Command(options.MySQLDumpPath, args...) 500 | cmdOut, _ := cmd.StdoutPipe() 501 | cmdErr, _ := cmd.StderrPipe() 502 | 503 | cmd.Start() 504 | 505 | output, _ := ioutil.ReadAll(cmdOut) 506 | err, _ := ioutil.ReadAll(cmdErr) 507 | cmd.Wait() 508 | 509 | printMessage("mysqldump output is : "+string(output), options.Verbosity, Info) 510 | 511 | if string(err) != "" { 512 | printMessage("mysqldump error is: "+string(err), options.Verbosity, Error) 513 | os.Exit(4) 514 | } 515 | 516 | // Compressing 517 | printMessage("Compressing table file : "+filename, options.Verbosity, Info) 518 | 519 | // set up the output file 520 | file, errcreate := os.Create(filename + ".tar.gz") 521 | 522 | if errcreate != nil { 523 | printMessage("error to create a compressed file: "+filename, options.Verbosity, Error) 524 | os.Exit(4) 525 | } 526 | 527 | defer file.Close() 528 | // set up the gzip writer 529 | gw := gzip.NewWriter(file) 530 | defer gw.Close() 531 | tw := tar.NewWriter(gw) 532 | defer tw.Close() 533 | 534 | if errcompress := Compress(tw, filename); errcompress != nil { 535 | printMessage("error to compress file: "+filename, options.Verbosity, Error) 536 | os.Exit(4) 537 | } 538 | 539 | printMessage("Single file backup successfull : "+db, options.Verbosity, Info) 540 | } 541 | 542 | func getTotalRowCount(tables []Table) int { 543 | result := 0 544 | for _, table := range tables { 545 | result += table.RowCount 546 | } 547 | 548 | return result 549 | } 550 | 551 | // Compress compresses files into tar.gz file 552 | func Compress(tw *tar.Writer, path string) error { 553 | file, err := os.Open(path) 554 | if err != nil { 555 | return err 556 | } 557 | defer file.Close() 558 | if stat, err := file.Stat(); err == nil { 559 | // now lets create the header as needed for this file within the tarball 560 | header := new(tar.Header) 561 | header.Name = path 562 | header.Size = stat.Size() 563 | header.Mode = int64(stat.Mode()) 564 | header.ModTime = stat.ModTime() 565 | // write the header to the tarball archive 566 | if err := tw.WriteHeader(header); err != nil { 567 | return err 568 | } 569 | // copy the file data to the tarball 570 | if _, err := io.Copy(tw, file); err != nil { 571 | return err 572 | } 573 | 574 | // Removing the original file after zipping it 575 | err = os.Remove(path) 576 | 577 | if err != nil { 578 | fmt.Println(err) 579 | return err 580 | } 581 | } 582 | return nil 583 | } 584 | 585 | // ListDirs give a Array of folders in a given path 586 | func ListDirs(rootpath string) []string { 587 | 588 | list := make([]string, 0, 10) 589 | 590 | err := filepath.Walk(rootpath, func(path string, info os.FileInfo, err error) error { 591 | if info.IsDir() { 592 | list = append(list, path) 593 | } 594 | 595 | return nil 596 | }) 597 | if err != nil { 598 | fmt.Printf("walk error [%v]\n", err) 599 | } 600 | return list 601 | } 602 | 603 | // BackupRotation execute a rotation of file, daily,weekly and monthly 604 | func BackupRotation(options Options) { 605 | //month 606 | if options.MonthlyRotation > 0 { 607 | monthly := ListDirs(options.OutputDirectory + "/monthly") 608 | if len(monthly) == 1 { 609 | CopyDir(options.OutputDirectory+"/daily/"+timeNow.Format("2006-01-02"), options.OutputDirectory+"/monthly/"+timeNow.Format("2006-01-02")) 610 | } else { 611 | newestFile := 0 612 | 613 | for _, p := range monthly { 614 | if path.Base(p) != "monthly" { 615 | file, err := os.Stat(path.Dir(p)) 616 | if err != nil { 617 | fmt.Println(err) 618 | } 619 | diff := timeNow.Sub(file.ModTime()) 620 | days := int(diff.Hours() / 24) 621 | if (len(monthly) - 1) < options.MonthlyRotation { 622 | if newestFile < days { 623 | newestFile = days 624 | } 625 | } else { 626 | // removing old backups 627 | if days > options.MonthlyRotation*30 { 628 | err = os.Remove(path.Dir(p)) 629 | if err != nil { 630 | fmt.Println(err) 631 | } 632 | } 633 | } 634 | } 635 | } 636 | if newestFile >= 30 { 637 | CopyDir(options.OutputDirectory+"/daily/"+timeNow.Format("2006-01-02"), options.OutputDirectory+"/monthly/"+timeNow.Format("2006-01-02")) 638 | } 639 | } 640 | } 641 | 642 | //weekly 643 | if options.MonthlyRotation > 0 { 644 | weekly := ListDirs(options.OutputDirectory + "/weekly") 645 | if len(weekly) == 1 { 646 | CopyDir(options.OutputDirectory+"/daily/"+timeNow.Format("2006-01-02"), options.OutputDirectory+"/weekly/"+timeNow.Format("2006-01-02")) 647 | } else { 648 | newestFile := 0 649 | 650 | for _, p := range weekly { 651 | if path.Base(p) != "weekly" { 652 | file, err := os.Stat(path.Dir(p)) 653 | if err != nil { 654 | fmt.Println(err) 655 | } 656 | diff := timeNow.Sub(file.ModTime()) 657 | days := int(diff.Hours() / 24) 658 | if (len(weekly) - 1) < options.WeeklyRotation { 659 | if newestFile < days { 660 | newestFile = days 661 | } 662 | } else { 663 | // removing old backups 664 | if days > options.WeeklyRotation*7 { 665 | err = os.Remove(path.Dir(p)) 666 | if err != nil { 667 | fmt.Println(err) 668 | } 669 | } 670 | } 671 | } 672 | } 673 | if newestFile >= 7 { 674 | CopyDir(options.OutputDirectory+"/daily/"+timeNow.Format("2006-01-02"), options.OutputDirectory+"/weekly/"+timeNow.Format("2006-01-02")) 675 | } 676 | } 677 | } 678 | 679 | //daily 680 | if options.DailyRotation > 0 { 681 | daily := ListDirs(options.OutputDirectory + "/daily") 682 | newestFile := 0 683 | for _, p := range daily { 684 | if path.Base(p) != "daily" { 685 | file, err := os.Stat(path.Dir(p)) 686 | if err != nil { 687 | fmt.Println(err) 688 | } 689 | diff := timeNow.Sub(file.ModTime()) 690 | days := int(diff.Hours() / 24) 691 | 692 | if (len(daily) - 1) < options.DailyRotation { 693 | if newestFile < days { 694 | newestFile = days 695 | } 696 | } else { 697 | // removing old backups 698 | if days > options.DailyRotation { 699 | err = os.Remove(path.Dir(p)) 700 | if err != nil { 701 | fmt.Println(err) 702 | } 703 | } 704 | } 705 | 706 | } 707 | } 708 | } 709 | 710 | } 711 | 712 | // CopyFile copies the contents of the file named src to the file named 713 | // by dst. The file will be created if it does not already exist. If the 714 | // destination file exists, all it's contents will be replaced by the contents 715 | // of the source file. The file mode will be copied from the source and 716 | // the copied data is synced/flushed to stable storage. 717 | func CopyFile(src, dst string) (err error) { 718 | in, err := os.Open(src) 719 | if err != nil { 720 | return 721 | } 722 | defer in.Close() 723 | 724 | out, err := os.Create(dst) 725 | if err != nil { 726 | return 727 | } 728 | defer func() { 729 | if e := out.Close(); e != nil { 730 | err = e 731 | } 732 | }() 733 | 734 | _, err = io.Copy(out, in) 735 | if err != nil { 736 | return 737 | } 738 | 739 | err = out.Sync() 740 | if err != nil { 741 | return 742 | } 743 | 744 | si, err := os.Stat(src) 745 | if err != nil { 746 | return 747 | } 748 | err = os.Chmod(dst, si.Mode()) 749 | if err != nil { 750 | return 751 | } 752 | 753 | return 754 | } 755 | 756 | // CopyDir recursively copies a directory tree, attempting to preserve permissions. 757 | // Source directory must exist, destination directory must *not* exist. 758 | // Symlinks are ignored and skipped. 759 | func CopyDir(src string, dst string) (err error) { 760 | src = filepath.Clean(src) 761 | dst = filepath.Clean(dst) 762 | 763 | si, err := os.Stat(src) 764 | if err != nil { 765 | return err 766 | } 767 | if !si.IsDir() { 768 | return fmt.Errorf("source is not a directory") 769 | } 770 | 771 | _, err = os.Stat(dst) 772 | if err != nil && !os.IsNotExist(err) { 773 | return 774 | } 775 | if err == nil { 776 | return fmt.Errorf("destination already exists") 777 | } 778 | 779 | err = os.MkdirAll(dst, si.Mode()) 780 | if err != nil { 781 | return 782 | } 783 | 784 | entries, err := ioutil.ReadDir(src) 785 | if err != nil { 786 | return 787 | } 788 | 789 | for _, entry := range entries { 790 | srcPath := filepath.Join(src, entry.Name()) 791 | dstPath := filepath.Join(dst, entry.Name()) 792 | 793 | if entry.IsDir() { 794 | err = CopyDir(srcPath, dstPath) 795 | if err != nil { 796 | return 797 | } 798 | } else { 799 | // Skip symlinks. 800 | if entry.Mode()&os.ModeSymlink != 0 { 801 | continue 802 | } 803 | 804 | err = CopyFile(srcPath, dstPath) 805 | if err != nil { 806 | return 807 | } 808 | } 809 | } 810 | 811 | return 812 | } 813 | 814 | // WriteToFile create a file and writes a specified msg to it 815 | func WriteToFile(filePath string, msg string) { 816 | file, err := os.Create(filePath) 817 | if err != nil { 818 | log.Fatal("Cannot create file", err) 819 | } 820 | defer file.Close() 821 | 822 | fmt.Fprintf(file, msg) 823 | } 824 | 825 | // GetOptions creates Options type from Commandline arguments 826 | func GetOptions() *Options { 827 | 828 | var hostname string 829 | flag.StringVar(&hostname, "hostname", "localhost", "Hostname of the mysql server to connect to") 830 | 831 | var bind string 832 | flag.StringVar(&bind, "bind", "3306", "Port of the mysql server to connect to") 833 | 834 | var username string 835 | flag.StringVar(&username, "username", "root", "username of the mysql server to connect to") 836 | 837 | var password string 838 | flag.StringVar(&password, "password", "1234", "password of the mysql server to connect to") 839 | 840 | var databases string 841 | flag.StringVar(&databases, "databases", "--all-databases", "List of databases as comma seperated values to dump. OBS: If not specified, --all-databases is the default") 842 | 843 | var excludeddatabases string 844 | flag.StringVar(&excludeddatabases, "excluded-databases", "", "List of databases excluded to be excluded. OBS: Only valid if -databases is not specified") 845 | 846 | var dbthreshold int 847 | flag.IntVar(&dbthreshold, "dbthreshold", 10000000, "Do not split mysqldumps, if total rowcount of tables in database is less than dbthreshold value for whole database") 848 | 849 | var tablethreshold int 850 | flag.IntVar(&tablethreshold, "tablethreshold", 5000000, "Do not split mysqldumps, if rowcount of table is less than dbthreshold value for table") 851 | 852 | var batchsize int 853 | flag.IntVar(&batchsize, "batchsize", 1000000, "Split mysqldumps in order to get each file contains batchsize number of records") 854 | 855 | var forcesplit bool 856 | flag.BoolVar(&forcesplit, "forcesplit", false, "Split schema and data dumps even if total rowcount of tables in database is less than dbthreshold value. if false one dump file will be created") 857 | 858 | var additionals string 859 | flag.StringVar(&additionals, "additionals", "", "Additional parameters that will be appended to mysqldump command") 860 | 861 | var verbosity int 862 | flag.IntVar(&verbosity, "verbosity", 2, "0 = only errors, 1 = important things, 2 = all") 863 | 864 | var mysqldumppath string 865 | flag.StringVar(&mysqldumppath, "mysqldump-path", "/usr/bin/mysqldump", "Absolute path for mysqldump executable.") 866 | 867 | var outputdir string 868 | flag.StringVar(&outputdir, "output-dir", "", "Default is the value of os.Getwd(). The backup files will be placed to output-dir /{DATABASE_NAME}/{DATABASE_NAME}_{TABLENAME|SCHEMA|DATA|ALL}_{TIMESTAMP}.sql") 869 | 870 | var dailyrotation int 871 | flag.IntVar(&dailyrotation, "daily-rotation", 5, "Number of days of retention") 872 | 873 | var weeklyrotation int 874 | flag.IntVar(&weeklyrotation, "weekly-rotation", 2, "Number of weeks of retention") 875 | 876 | var monthlyrotation int 877 | flag.IntVar(&monthlyrotation, "monthly-rotation", 1, "Number of months of retention") 878 | 879 | var test bool 880 | flag.BoolVar(&test, "test", false, "test") 881 | 882 | flag.Parse() 883 | 884 | if outputdir == "" { 885 | dir, err := os.Getwd() 886 | if err != nil { 887 | printMessage(err.Error(), verbosity, Error) 888 | } 889 | 890 | outputdir = dir 891 | } 892 | 893 | defaultsProvidedByUser := true 894 | 895 | if _, err := os.Stat(mysqldumppath); os.IsNotExist(err) { 896 | printMessage("mysqldump binary can not be found, please specify correct value for mysqldump-path parameter", verbosity, Error) 897 | os.Exit(1) 898 | } 899 | 900 | os.MkdirAll(outputdir+"/daily/"+timeNow.Format("2006-01-02"), os.ModePerm) 901 | os.MkdirAll(outputdir+"/weekly", os.ModePerm) 902 | os.MkdirAll(outputdir+"/monthly", os.ModePerm) 903 | 904 | opts := NewOptions(hostname, bind, username, password, databases, excludeddatabases, dbthreshold, tablethreshold, batchsize, forcesplit, additionals, verbosity, mysqldumppath, outputdir, defaultsProvidedByUser, dailyrotation, weeklyrotation, monthlyrotation) 905 | stropts, _ := json.MarshalIndent(opts, "", "\t") 906 | printMessage("Running with parameters", verbosity, Info) 907 | printMessage(string(stropts), verbosity, Info) 908 | printMessage("Running on operating system : "+runtime.GOOS, verbosity, Info) 909 | 910 | if test { 911 | cmd := exec.Command(opts.MySQLDumpPath, 912 | `-h127.0.0.1`, 913 | `-uroot`, 914 | `-pXXXX`, 915 | `--no-create-db`, 916 | `--skip-triggers`, 917 | `--no-create-info`, 918 | `--single-transaction`, 919 | `--skip-extended-insert`, 920 | `--quick`, 921 | `--skip-add-locks`, 922 | `--default-character-set=utf8`, 923 | `--compress`, 924 | `mysql`, 925 | `--where="1=1 LIMIT 1000000, 1000000"`, 926 | `user`, 927 | `host`) 928 | 929 | cmdOut, _ := cmd.StdoutPipe() 930 | cmdErr, _ := cmd.StderrPipe() 931 | 932 | cmd.Start() 933 | 934 | output, _ := ioutil.ReadAll(cmdOut) 935 | err, _ := ioutil.ReadAll(cmdErr) 936 | 937 | cmd.Wait() 938 | 939 | printMessage("mysqldump output is : "+string(output), opts.Verbosity, Info) 940 | 941 | if string(err) != "" { 942 | printMessage("mysqldump error is: "+string(err), opts.Verbosity, Error) 943 | os.Exit(4) 944 | } 945 | 946 | os.Exit(4) 947 | } 948 | 949 | return opts 950 | } 951 | 952 | func printMessage(message string, verbosity int, messageType int) { 953 | colors := map[int]color.Attribute{Info: color.FgGreen, Warning: color.FgHiYellow, Error: color.FgHiRed} 954 | 955 | if verbosity == 2 { 956 | color.Set(colors[messageType]) 957 | fmt.Println(message) 958 | color.Unset() 959 | } else if verbosity == 1 && messageType > 1 { 960 | color.Set(colors[messageType]) 961 | fmt.Println(message) 962 | color.Unset() 963 | } else if verbosity == 0 && messageType > 2 { 964 | color.Set(colors[messageType]) 965 | fmt.Println(message) 966 | color.Unset() 967 | } 968 | } 969 | 970 | func checkErr(err error) { 971 | if err != nil { 972 | color.Set(color.FgHiRed) 973 | panic(err) 974 | color.Unset() 975 | } 976 | } 977 | --------------------------------------------------------------------------------