Skip to content

Commit

Permalink
Add CLI data features using shell command on MariaDB
Browse files Browse the repository at this point in the history
Signed-off-by: ashraful <[email protected]>
  • Loading branch information
AshrafulHaqueToni committed Nov 14, 2023
1 parent dfd5e3b commit ed2c054
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 60 deletions.
146 changes: 89 additions & 57 deletions pkg/data/mariadb.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,15 @@ package data
import (
"bytes"
"context"
"errors"
"fmt"
"k8s.io/apimachinery/pkg/labels"
"log"
"os"
"os/exec"
"strconv"
"strings"

api "kubedb.dev/apimachinery/apis/kubedb/v1alpha2"
cs "kubedb.dev/apimachinery/client/clientset/versioned"
"kubedb.dev/cli/pkg/lib"

_ "github.com/go-sql-driver/mysql"
"github.com/spf13/cobra"
shell "gomodules.xyz/go-sh"
Expand All @@ -38,7 +37,8 @@ import (
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"kmodules.xyz/client-go/tools/portforward"
api "kubedb.dev/apimachinery/apis/kubedb/v1alpha2"
cs "kubedb.dev/apimachinery/client/clientset/versioned"
)

func InsertMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
Expand All @@ -54,7 +54,7 @@ func InsertMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
},
Short: "Connect to a mariadb object",
Long: `Use this cmd to exec into a mariadb object's primary pod.`,
Example: `kubectl dba insert mariadb -n demo sample-mariadb --rows 1000`,
Example: `kubectl dba data insert mariadb -n demo sample-mariadb --rows 1000`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
log.Fatal("Enter mariadb object's name as an argument")
Expand All @@ -75,14 +75,11 @@ func InsertMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
log.Fatal("Inserted rows must be greater than 0")
}

tunnel, err := lib.TunnelToDBService(opts.config, dbName, namespace, api.MySQLDatabasePort)
if err != nil {
log.Fatal("couldn't create tunnel, error: ", err)
if rows > 100000 {
log.Fatal("Inserted rows must be less than or equal 100000")
}

defer tunnel.Close()

err = opts.insertDataExecCmd(tunnel, rows)
err = opts.insertDataExecCmd(rows)
if err != nil {
log.Fatal(err)
}
Expand All @@ -94,9 +91,10 @@ func InsertMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
return mdInsertCmd
}

func (opts *mariadbOpts) insertDataExecCmd(tunnel *portforward.Tunnel, rows int) error {
func (opts *mariadbOpts) insertDataExecCmd(rows int) error {
command := `
USE mysql;
CREATE DATABASE IF NOT EXISTS MySQL;
USE MySQL;
CREATE TABLE IF NOT EXISTS kubedb_table (id VARCHAR(255) PRIMARY KEY);
DROP PROCEDURE IF EXISTS insert_data;
DELIMITER //
Expand All @@ -121,12 +119,12 @@ func (opts *mariadbOpts) insertDataExecCmd(tunnel *portforward.Tunnel, rows int)
CALL insert_data(` + fmt.Sprintf("%v", rows) + `);
`

_, err := opts.executeCommand(tunnel.Local, command)
_, err := opts.executeCommand(command)
if err != nil {
return err
}

fmt.Printf("\nSuccess! %d keys inserted in MariaDB database %s/%s.\n", rows, opts.db.Namespace, opts.db.Name)
fmt.Printf("\nSuccess! %d keys inserted in MySQL database %s/%s.\n", rows, opts.db.Namespace, opts.db.Name)
return nil
}

Expand All @@ -143,7 +141,7 @@ func VerifyMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
},
Short: "Verify rows in a MariaDB database",
Long: `Use this cmd to verify data in a mariadb object`,
Example: `kubectl dba verify mariadb -n demo sample-mariadb --rows 1000`,
Example: `kubectl dba data verify mariadb -n demo sample-mariadb --rows 1000`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
log.Fatal("Enter mariadb object's name as an argument.")
Expand All @@ -160,13 +158,7 @@ func VerifyMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
log.Fatalln(err)
}

tunnel, err := lib.TunnelToDBService(opts.config, dbName, namespace, api.MySQLDatabasePort)
if err != nil {
log.Fatal("couldn't create tunnel, error: ", err)
}
defer tunnel.Close()

err = opts.verifyDataExecCmd(tunnel, rows)
err = opts.verifyDataExecCmd(rows)
if err != nil {
log.Fatal(err)
}
Expand All @@ -178,30 +170,33 @@ func VerifyMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
return mdVerifyCmd
}

func (opts *mariadbOpts) verifyDataExecCmd(tunnel *portforward.Tunnel, rows int) error {
func (opts *mariadbOpts) verifyDataExecCmd(rows int) error {
if rows <= 0 {
return fmt.Errorf("rows need to be greater than 0")
}

command := `
USE mysql;
CREATE DATABASE IF NOT EXISTS MySQL;
USE MySQL;
CREATE TABLE IF NOT EXISTS kubedb_table (id VARCHAR(255) PRIMARY KEY);
SELECT COUNT(*) FROM kubedb_table;
`
out, err := opts.executeCommand(tunnel.Local, command)
o, err := opts.executeCommand(command)
if err != nil {
return err
}

out := string(o)
output := strings.Split(out, "\n")

totalKeys, err := strconv.Atoi(strings.TrimPrefix(output[1], " "))
totalKeys, err := strconv.Atoi(strings.TrimSpace(output[1]))
if err != nil {
return err
}
if totalKeys >= rows {
fmt.Printf("\nSuccess! MariaDB database %s/%s contains: %d keys\n", opts.db.Namespace, opts.db.Name, totalKeys)
fmt.Printf("\nSuccess! MySQL database %s/%s contains: %d keys\n", opts.db.Namespace, opts.db.Name, totalKeys)
} else {
fmt.Printf("\nError! Expected keys: %d . MariaDB database %s/%s contains: %d keys\n", rows, opts.db.Namespace, opts.db.Name, totalKeys)
fmt.Printf("\nError! Expected keys: %d . MySQL database %s/%s contains: %d keys\n", rows, opts.db.Namespace, opts.db.Name, totalKeys)
}
return nil
}
Expand All @@ -216,7 +211,7 @@ func DropMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
},
Short: "Verify rows in a MariaDB database",
Long: `Use this cmd to verify data in a mariadb object`,
Example: `kubectl dba drop mariadb -n demo sample-mariadb`,
Example: `kubectl dba data drop mariadb -n demo sample-mariadb`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
log.Fatal("Enter mariadb object's name as an argument.")
Expand All @@ -233,13 +228,7 @@ func DropMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
log.Fatalln(err)
}

tunnel, err := lib.TunnelToDBService(opts.config, dbName, namespace, api.MySQLDatabasePort)
if err != nil {
log.Fatal("couldn't create tunnel, error: ", err)
}
defer tunnel.Close()

err = opts.dropDataExecCmd(tunnel)
err = opts.dropDataExecCmd()
if err != nil {
log.Fatal(err)
}
Expand All @@ -249,16 +238,16 @@ func DropMariaDBDataCMD(f cmdutil.Factory) *cobra.Command {
return mdDropCmd
}

func (opts *mariadbOpts) dropDataExecCmd(tunnel *portforward.Tunnel) error {
func (opts *mariadbOpts) dropDataExecCmd() error {
command := `
USE mysql;
USE MySQL;
DROP TABLE IF EXISTS kubedb_table;
`
_, err := opts.executeCommand(tunnel.Local, command)
_, err := opts.executeCommand(command)
if err != nil {
return err
}
fmt.Printf("\nSuccess: All the CLI inserted rows DELETED from MariaDB database %s/%s.\n", opts.db.Namespace, opts.db.Name)
fmt.Printf("\nSuccess: All the CLI inserted rows DELETED from MySQL database %s/%s.\n", opts.db.Namespace, opts.db.Name)

return nil
}
Expand Down Expand Up @@ -390,30 +379,73 @@ func (opts *mariadbOpts) getDockerShellCommand(localPort int, dockerFlags, maria
return sh.Command("docker", finalCommand...).SetStdin(os.Stdin), nil
}

func (opts *mariadbOpts) executeCommand(localPort int, command string) (string, error) {
mariadbExtraFlags := []interface{}{
"-e", command,
func (opts *mariadbOpts) getShellCommand(command string) (string, error) {
db := opts.db
cmd := ""
user, password, err := opts.GetMariaDBAuthCredentials(db)
if err != nil {
return "", err
}
containerName := "mariadb"
label := opts.db.OffshootLabels()

shSession, err := opts.getDockerShellCommand(localPort, nil, mariadbExtraFlags)
if err != nil {
if *opts.db.Spec.Replicas > 1 {
label["kubedb.com/role"] = "primary"
}

pods, err := opts.client.CoreV1().Pods(db.Namespace).List(context.TODO(), metav1.ListOptions{
LabelSelector: labels.Set.String(label),
})
if err != nil || len(pods.Items) == 0 {
return "", err
}
if db.Spec.TLS != nil {
cmd = fmt.Sprintf("kubectl exec -n %s %s -c %s -- mysql -u%s -p'%s' --host=%s --port=%s --ssl-ca='%v' --ssl-cert='%v' --ssl-key='%v' %s -e \"%s\"", db.Namespace, pods.Items[0].Name, containerName, user, password, "127.0.0.1", "3306", myCaFile, myCertFile, myKeyFile, api.ResourceSingularMySQL, command)
} else {
cmd = fmt.Sprintf("kubectl exec -n %s %s -c %s -- mysql -u%s -p'%s' %s -e \"%s\"", db.Namespace, pods.Items[0].Name, containerName, user, password, api.ResourceSingularMySQL, command)
}

out, err := shSession.Output()
return cmd, err
}

func (opts *mariadbOpts) GetMariaDBAuthCredentials(db *api.MariaDB) (string, string, error) {
if db.Spec.AuthSecret == nil {
return "", "", errors.New("no database secret")
}
secret, err := opts.client.CoreV1().Secrets(db.Namespace).Get(context.TODO(), db.Spec.AuthSecret.Name, metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("failed to execute file, error: %s, output: %s\n", err, out)
return "", "", err
}
return string(secret.Data[corev1.BasicAuthUsernameKey]), string(secret.Data[corev1.BasicAuthPasswordKey]), nil
}

output := ""
if string(out) != "" {
output = ", output:\n\n" + string(out)
func (opts *mariadbOpts) executeCommand(command string) ([]byte, error) {
cmd, err := opts.getShellCommand(command)
if err != nil {
return nil, err
}

errOutput := opts.errWriter.String()
if errOutput != "" {
return "", fmt.Errorf("failed to execute command, stderr: %s%s", errOutput, output)
output, err := opts.runCMD(cmd)
if err != nil {
return nil, err
}
return output, nil
}

return string(out), nil
func (opts *mariadbOpts) runCMD(cmd string) ([]byte, error) {
sh := exec.Command("/bin/sh", "-c", cmd)
stdout := bytes.NewBuffer(nil)
stderr := bytes.NewBuffer(nil)
sh.Stdout = stdout
sh.Stderr = stderr
err := sh.Run()
out := stdout.Bytes()
errOut := stderr.Bytes()
errOutput := string(errOut)
if errOutput != "" && !strings.Contains(errOutput, "NOTICE") && !strings.Contains(errOutput, "Warning") {
return nil, fmt.Errorf("failed to execute command, stderr: %s", errOutput)
}
if err != nil {
return nil, err
}
return out, nil
}
6 changes: 3 additions & 3 deletions pkg/data/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func InsertMySQLDataCMD(f cmdutil.Factory) *cobra.Command {
},
Short: "Connect to a mysql object",
Long: `Use this cmd to exec into a mysql object's primary pod.`,
Example: `kubectl dba insert mysql -n demo sample-mysql --rows 1000`,
Example: `kubectl dba data insert mysql -n demo sample-mysql --rows 1000`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
log.Fatal("Enter mysql object's name as an argument")
Expand Down Expand Up @@ -146,7 +146,7 @@ func VerifyMySQLDataCMD(f cmdutil.Factory) *cobra.Command {
},
Short: "Verify rows in a MySQL database",
Long: `Use this cmd to verify data in a mysql object`,
Example: `kubectl dba verify mysql -n demo sample-mysql --rows 1000`,
Example: `kubectl dba data verify mysql -n demo sample-mysql --rows 1000`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
log.Fatal("Enter mysql object's name as an argument.")
Expand Down Expand Up @@ -216,7 +216,7 @@ func DropMySQLDataCMD(f cmdutil.Factory) *cobra.Command {
},
Short: "Verify rows in a MySQL database",
Long: `Use this cmd to verify data in a mysql object`,
Example: `kubectl dba drop mysql -n demo sample-mysql`,
Example: `kubectl dba data drop mysql -n demo sample-mysql`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
log.Fatal("Enter mysql object's name as an argument.")
Expand Down

0 comments on commit ed2c054

Please sign in to comment.