DEV Community

Cover image for Creating a mysqldump Tool with Go
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Creating a mysqldump Tool with Go

This article was originally published on bmf-tech.com.

Overview

Since I was manually backing up the database for this blog like a caveman, I decided to create a tool in Go that can back up the database from remote to local with a single command.

Packages

  • "net"
    • Provides interfaces for network I/O, TCP/IP, UDP, domain name resolution, Unix domain sockets, etc.
  • "time"
    • Provides functions for time calculations and display.
  • "io/ioutil"
    • Provides I/O utilities for file operations.
  • "golang.org/x/crypto/ssh"
    • Provides implementations for SSH clients and servers.
  • "github.com/BurntSushi/toml"
    • TOML parser
    • It seems to be designed similarly to Go's standard library parsers for JSON and XML.
    • Burnt Sushi

Implementation

I implemented it roughly to a working state. Since I'm not familiar with Go, it feels a bit clumsy...
Also, I haven't written tests yet.

package main

import (
    "net"
    "time"
    "io/ioutil"
    "golang.org/x/crypto/ssh"
    "github.com/BurntSushi/toml"
)

type Config struct {
    SSH SSH
    Mysql Mysql
}

type SSH struct {
    IP string
    Port string
    User string
    IdentityFile string
}

type Mysql struct {
    MysqlConf string
    Database string
    DumpDir string
    DumpFilePrefix string
}

func dump() {
    var config Config
    if _, err := toml.DecodeFile("config.toml", &config); err != nil {
        panic(err)
    }

    buf, err := ioutil.ReadFile(config.SSH.IdentityFile)
    if err != nil {
        panic(err)
    }

    key, err := ssh.ParsePrivateKey(buf)
    if err != nil {
        panic(err)
    }

    conn, err := ssh.Dial("tcp", config.SSH.IP+":"+config.SSH.Port, &ssh.ClientConfig{
        User: config.SSH.User,
        Auth: []ssh.AuthMethod{
            ssh.PublicKeys(key),
        },
        HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
            return nil
        },
    })
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    session, err := conn.NewSession()
    if err != nil {
        panic(err)
    }
    defer session.Close()

    byte, err := session.Output("sudo mysqldump --defaults-file="+config.Mysql.MysqlConf+" "+config.Mysql.Database+" --quick --single-transaction")
    if err != nil {
        panic(err)
    }

    ioutil.WriteFile(config.Mysql.DumpDir+config.Mysql.DumpFilePrefix+time.Now().Format("2006-01-02")+".sql", byte, 0644)
}

func main() {
    dump()
}
Enter fullscreen mode Exit fullscreen mode

GitHub

Left it here.

Thoughts

For now, I will look at various implementations in Go and accumulate knowledge...

References

Top comments (0)