Intro
In this tutorial, we will guide you through the process of creating a simple, low-memory, and efficient service using Go. This service monitors your MySQL server and automatically restarts it if it goes down. We’ll also cover how to deploy this service on a VPS, run it in the background, and ensure it starts automatically with your system.
Prerequisites
Before we start, make sure you have the following:
- A VPS running Ubuntu or any Linux distribution. If you don’t have one, you can get a VPS from DigitalOcean, AWS, or Azure.
- Go installed on your local development environment (preferably using WSL if you are on Windows). You can download Go from the official website.
- Basic understanding of the Linux command line and Go programming.
Step 1: Setting Up the Project
First, let’s set up a new Go project with a go.mod
file:
- Open your terminal and create a new directory for your project:
mkdir mysql_monitor cd mysql_monitor
- Initialize the Go module:
go mod init mysql_monitor
- Install the necessary dependencies, such as the Gomail package for sending email notifications:
go get gopkg.in/mail.v2
Step 2: Writing the Go Code
Here’s the Go code that monitors MySQL, attempts to restart it if it’s down, and sends email notifications about its status:
package main
import (
"fmt"
"log"
"os/exec"
"time"
"gopkg.in/mail.v2"
)
// CheckMySQLStatus checks if MySQL is running
func CheckMySQLStatus() bool {
cmd := exec.Command("systemctl", "is-active", "--quiet", "mysql")
err := cmd.Run()
return err == nil
}
// RestartMySQL restarts the MySQL service
func RestartMySQL() {
log.Println("MySQL is down! Attempting to restart...")
cmd := exec.Command("systemctl", "restart", "mysql")
sendMail("MySQL is down! Attempting to restart...", "MySQL is down! Attempting to restart...")
err := cmd.Run()
if err != nil {
log.Printf("Failed to restart MySQL: %v
", err)
sendMail(fmt.Sprintf("Failed to restart MySQL: %v", err), "MySQL Restart Failure")
} else {
log.Println("MySQL restarted successfully.")
sendMail("MySQL restarted successfully.", "MySQL Restart Success")
}
}
func main() {
for {
if !CheckMySQLStatus() {
RestartMySQL()
}
time.Sleep(1 * time.Minute) // Check every minute
}
}
func sendMail(body string, subject string) {
m := mail.NewMessage()
m.SetHeader("From", "rambod.gh@outlook.com")
m.SetHeader("To", "rambod.dev@gmail.com")
m.SetHeader("Subject", subject)
m.SetBody("text/plain", body)
d := mail.NewDialer("smtp-mail.outlook.com", 587, "rambod.gh@outlook.com", "password")
if err := d.DialAndSend(m); err != nil {
log.Printf("Failed to send email: %v
", err)
}
}
Explanation of the Code
- CheckMySQLStatus: This function checks whether the MySQL service is running using the
systemctl is-active
command. - RestartMySQL: If MySQL is down, this function attempts to restart it and sends an email notification about the status.
- sendMail: This function sends an email using the Gomail package, notifying you of any important events.
Step 3: Building the Binary
Once the code is written, build the Go binary:
go build -o mysql_monitor
This command will create an executable named mysql_monitor
in your project directory.
Step 4: Transferring the Binary to Your VPS
Use scp
to transfer the binary to your VPS. If you don’t have a VPS, you can get one from DigitalOcean, AWS, or Azure.
scp mysql_monitor username@your-vps-ip:/path/to/destination
Step 5: Setting Up a Non-Root User (Optional but Recommended)
For security reasons, it’s best to run services as a non-root user:
- Create a new user:
sudo adduser yourusername
- Grant sudo privileges to the new user:
sudo usermod -aG sudo yourusername
- Switch to the new user:
su - yourusername
Step 6: Running the Service in the Background
Once logged in as your new user, make the binary executable:
chmod +x /path/to/destination/mysql_monitor
You can run it in the background using nohup
:
nohup ./mysql_monitor &
Step 7: Creating a systemd Service
For better management, create a systemd service to run your application automatically on startup:
- Create a service file:
sudo nano /etc/systemd/system/mysql_monitor.service
- Add the following content:
[Unit]
Description=MySQL Monitor Service
After=network.target
[Service]
ExecStart=/path/to/destination/mysql_monitor
Restart=always
User=yourusername
[Install]
WantedBy=multi-user.target
- Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable mysql_monitor.service
sudo systemctl start mysql_monitor.service
- Check the status of the service:
sudo systemctl status mysql_monitor.service
Step 8: Monitoring Logs
You can monitor the service logs with:
sudo journalctl -u mysql_monitor.service
Conclusion
By following this tutorial, you’ve created a simple, low-memory, and efficient Go service that monitors and automatically restarts MySQL if it goes down. This service will also notify you via email of any issues with your MySQL server, ensuring that you’re always aware of its status.
This setup is ideal for small-scale deployments where resource usage is a concern. Go’s lightweight nature makes it a perfect choice for such tasks. Whether you’re using a VPS from DigitalOcean, AWS, or Azure, this tutorial helps you ensure your MySQL server stays up and running.
External Links:
- Official Go Programming Language Documentation
- DigitalOcean Guide on VPS
- MySQL Official Documentation
- Systemd Service Management
Tags
- Go Programming
- MySQL
- Linux Server
- VPS
- systemd
- DevOps
- Low-Memory Usage
- Server Monitoring
No comment yet, add your voice below!