2024-07-23 14:48:37 +08:00
package client
import (
"compress/gzip"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path"
"strings"
"time"
2025-11-24 16:07:14 +08:00
"github.com/1Panel-dev/1Panel/agent/app/dto"
2024-07-23 14:48:37 +08:00
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global"
2026-04-28 11:17:30 +08:00
"github.com/1Panel-dev/1Panel/agent/utils/cmd"
2026-01-08 15:27:00 +08:00
"github.com/1Panel-dev/1Panel/agent/utils/common"
2024-07-23 14:48:37 +08:00
"github.com/1Panel-dev/1Panel/agent/utils/files"
)
type Local struct {
Type string
PrefixCommand [] string
Database string
Password string
ContainerName string
2026-10-26 13:59:49 +08:00
// sqlContext belongs to a request-scoped copy, never the reusable client.
sqlContext context . Context
2024-07-23 14:48:37 +08:00
}
func NewLocal ( command [] string , dbType , containerName , password , database string ) * Local {
return & Local { Type : dbType , PrefixCommand : command , ContainerName : containerName , Password : password , Database : database }
}
func ( r * Local ) Create ( info CreateInfo ) error {
2026-07-16 14:24:38 +08:00
if err := r . CreateDatabase ( info ); err != nil {
return err
}
if len ( info . Username ) == 0 {
return nil
}
if err := r . CreateUser ( info , true ); err != nil {
_ = r . ExecSQL ( fmt . Sprintf ( "drop database if exists `%s`" , info . Name ), info . Timeout )
return err
}
return nil
}
2026-10-26 13:59:49 +08:00
// CreateWithContext shares one deadline across all creation and rollback SQL.
// Copying the client keeps concurrent or subsequent ordinary calls independent.
func ( r * Local ) CreateWithContext ( ctx context . Context , info CreateInfo ) error {
if ctx == nil {
return errors . New ( "mysql creation context is required" )
}
scoped := * r
scoped . PrefixCommand = append ([] string ( nil ), r . PrefixCommand ... )
scoped . sqlContext = ctx
return scoped . Create ( info )
}
func ( r * Local ) commandContext ( timeout uint ) ( context . Context , context . CancelFunc ) {
parent := r . sqlContext
if parent == nil {
parent = context . Background ()
}
return context . WithTimeout ( parent , time . Duration ( timeout ) * time . Second )
}
2026-07-16 14:24:38 +08:00
func ( r * Local ) CreateDatabase ( info CreateInfo ) error {
2025-11-24 16:07:14 +08:00
createSql := fmt . Sprintf ( "create database `%s` default character set %s collate %s" , info . Name , info . Format , info . Collation )
2025-11-25 15:02:37 +08:00
if len ( info . Collation ) == 0 {
createSql = fmt . Sprintf ( "create database `%s` default character set %s" , info . Name , info . Format )
}
2024-07-23 14:48:37 +08:00
if err := r . ExecSQL ( createSql , info . Timeout ); err != nil {
if strings . Contains ( strings . ToLower ( err . Error ()), "error 1007" ) {
2025-01-24 11:00:07 +08:00
return buserr . New ( "ErrDatabaseIsExist" )
2024-07-23 14:48:37 +08:00
}
return err
}
return nil
}
func ( r * Local ) CreateUser ( info CreateInfo , withDeleteDB bool ) error {
2026-07-16 14:24:38 +08:00
for _ , user := range userIdentities ( info . Username , info . Permission ) {
if err := r . ExecSQL ( createUserSQL ( user , info . Password ), info . Timeout ); err != nil {
if isUserExistsErr ( err ) {
2025-01-24 11:00:07 +08:00
return buserr . New ( "ErrUserIsExist" )
2024-07-23 14:48:37 +08:00
}
if withDeleteDB {
_ = r . Delete ( DeleteInfo {
Name : info . Name ,
Version : info . Version ,
Username : info . Username ,
Permission : info . Permission ,
ForceDelete : true ,
Timeout : 300 })
}
return err
}
2026-07-16 14:24:38 +08:00
if err := r . ExecSQL ( createUserGrantSQL ( info , user ), info . Timeout ); err != nil {
2024-07-23 14:48:37 +08:00
if withDeleteDB {
_ = r . Delete ( DeleteInfo {
Name : info . Name ,
Version : info . Version ,
Username : info . Username ,
Permission : info . Permission ,
ForceDelete : true ,
Timeout : 300 })
}
return err
}
}
return nil
}
2026-07-16 14:24:38 +08:00
func ( r * Local ) CreateUserOnly ( info UserInfo , password string , timeout uint ) error {
if err := r . ExecSQL ( createUserSQL ( userIdentity ( info . Username , info . Host ), password ), timeout ); err != nil {
if isUserExistsErr ( err ) {
return buserr . New ( "ErrUserIsExist" )
2024-07-23 14:48:37 +08:00
}
2026-07-16 14:24:38 +08:00
return err
2024-07-23 14:48:37 +08:00
}
2026-07-16 14:24:38 +08:00
return nil
}
2024-07-23 14:48:37 +08:00
2026-07-16 14:24:38 +08:00
func ( r * Local ) GrantUser ( info GrantInfo , timeout uint ) error {
return r . ExecSQL ( grantUserSQL ( info ), timeout )
}
func ( r * Local ) RevokeGrant ( info GrantInfo , timeout uint ) error {
if err := r . ExecSQL ( revokeGrantSQL ( info ), timeout ); err != nil {
return err
}
_ = r . ExecSQL ( revokeGrantOptionSQL ( info ), timeout )
return nil
}
func ( r * Local ) DeleteUser ( info UserInfo , version string , timeout uint ) error {
return r . ExecSQL ( dropUserSQL ( info , version ), timeout )
}
func ( r * Local ) UpdateUser ( info UserUpdateInfo , timeout uint ) error {
if info . Host == info . NewHost {
return nil
}
return r . ExecSQL ( renameUserSQL ( info ), timeout )
}
func ( r * Local ) DeleteDatabase ( info DeleteInfo ) error {
if len ( info . Name ) == 0 {
return nil
}
if err := r . ExecSQL ( dropDatabaseSQL ( info . Name ), info . Timeout ); err != nil && ! info . ForceDelete {
return fmt . Errorf ( "drop database failed, err: %v" , err )
}
return nil
}
func ( r * Local ) ListUsers ( timeout uint ) ([] UserInfo , error ) {
lines , err := r . ExecSQLForRows ( "select user,host from mysql.user order by user,host;" , timeout )
if err != nil {
return nil , err
}
users := make ([] UserInfo , 0 )
for _ , line := range lines {
parts := strings . Fields ( line )
if len ( parts ) != 2 || strings . EqualFold ( parts [ 0 ], "user" ) {
continue
}
users = append ( users , UserInfo { Username : parts [ 0 ], Host : parts [ 1 ]})
}
return users , nil
}
func ( r * Local ) ListGrants ( timeout uint ) ([] GrantInfo , error ) {
lines , err := r . ExecSQLForRows ( "select db,user,host from mysql.db where db not in ('information_schema','mysql','performance_schema','sys','__recycle_bin__','recycle_bin') order by db,user,host;" , timeout )
if err != nil {
return nil , err
}
grants := make ([] GrantInfo , 0 )
for _ , line := range lines {
parts := strings . Fields ( line )
if len ( parts ) != 3 || strings . EqualFold ( parts [ 0 ], "db" ) {
continue
}
if parts [ 1 ] == "root" {
continue
}
grants = append ( grants , GrantInfo { Database : parts [ 0 ], Username : parts [ 1 ], Host : parts [ 2 ]})
}
return grants , nil
}
func ( r * Local ) Delete ( info DeleteInfo ) error {
for _ , user := range userIdentities ( info . Username , info . Permission ) {
2024-07-23 14:48:37 +08:00
if strings . HasPrefix ( info . Version , "5.6" ) {
if err := r . ExecSQL ( fmt . Sprintf ( "drop user %s" , user ), info . Timeout ); err != nil && ! info . ForceDelete {
2025-09-02 13:43:44 +08:00
return fmt . Errorf ( "drop user failed, err: %v" , err )
2024-07-23 14:48:37 +08:00
}
} else {
if err := r . ExecSQL ( fmt . Sprintf ( "drop user if exists %s" , user ), info . Timeout ); err != nil && ! info . ForceDelete {
2025-09-02 13:43:44 +08:00
return fmt . Errorf ( "drop user failed, err: %v" , err )
2024-07-23 14:48:37 +08:00
}
}
}
if len ( info . Name ) != 0 {
2026-07-16 14:24:38 +08:00
if err := r . ExecSQL ( dropDatabaseSQL ( info . Name ), info . Timeout ); err != nil && ! info . ForceDelete {
2025-09-02 13:43:44 +08:00
return fmt . Errorf ( "drop database failed, err: %v" , err )
2024-07-23 14:48:37 +08:00
}
}
if ! info . ForceDelete {
global . LOG . Info ( "execute delete database sql successful, now start to drop uploads and records" )
}
return nil
}
func ( r * Local ) ChangePassword ( info PasswordChangeInfo ) error {
if info . Username != "root" {
2026-07-16 14:24:38 +08:00
for _ , user := range userIdentities ( info . Username , info . Permission ) {
if err := r . ExecSQL ( changeUserPasswordSQL ( user , info . Password , info . Version ), info . Timeout ); err != nil {
2024-07-23 14:48:37 +08:00
return err
}
}
return nil
}
hosts , err := r . ExecSQLForRows ( "select host from mysql.user where user='root';" , info . Timeout )
if err != nil {
return err
}
for _ , host := range hosts {
if host == "%" || host == "localhost" {
passwordRootChangeCMD := fmt . Sprintf ( "set password for 'root'@'%s' = password('%s')" , host , info . Password )
if ! strings . HasPrefix ( info . Version , "5.7" ) && ! strings . HasPrefix ( info . Version , "5.6" ) {
passwordRootChangeCMD = fmt . Sprintf ( "alter user 'root'@'%s' identified by '%s';" , host , info . Password )
}
if err := r . ExecSQL ( passwordRootChangeCMD , info . Timeout ); err != nil {
return err
}
}
}
return nil
}
func ( r * Local ) ChangeAccess ( info AccessChangeInfo ) error {
if info . Username == "root" {
info . OldPermission = "%"
info . Name = "*"
info . Password = r . Password
}
if info . Permission != info . OldPermission {
if err := r . Delete ( DeleteInfo {
Version : info . Version ,
Username : info . Username ,
Permission : info . OldPermission ,
ForceDelete : true ,
Timeout : 300 }); err != nil {
return err
}
if info . Username == "root" {
return nil
}
}
if err := r . CreateUser ( CreateInfo {
Name : info . Name ,
Version : info . Version ,
Username : info . Username ,
Password : info . Password ,
Permission : info . Permission ,
Timeout : info . Timeout ,
}, false ); err != nil {
return err
}
if err := r . ExecSQL ( "flush privileges" , 300 ); err != nil {
return err
}
return nil
}
func ( r * Local ) Backup ( info BackupInfo ) error {
fileOp := files . NewFileOp ()
if ! fileOp . Stat ( info . TargetDir ) {
if err := os . MkdirAll ( info . TargetDir , os . ModePerm ); err != nil {
return fmt . Errorf ( "mkdir %s failed, err: %v" , info . TargetDir , err )
}
}
dumpCmd := "mysqldump"
if r . Type == constant . AppMariaDB {
dumpCmd = "mariadb-dump"
}
2026-01-06 16:41:55 +08:00
global . LOG . Infof ( "start to %s | gzip > %s.gzip, args: %v" , dumpCmd , info . TargetDir + "/" + info . FileName , info . Args )
2025-08-05 14:30:34 +08:00
2026-01-08 15:27:00 +08:00
info . Args = append ( info . Args , "--routines" )
itemArgs := common . RemoveRepeatStr ( info . Args )
args := [] string { "exec" , r . ContainerName , dumpCmd , "-uroot" , "-p" + r . Password , "--default-character-set=" + info . Format }
for _ , arg := range itemArgs {
2026-01-06 16:41:55 +08:00
if len ( arg ) == 0 {
continue
}
args = append ( args , arg )
}
args = append ( args , info . Name )
2026-05-26 09:33:41 +08:00
cmdMgr := cmd . NewCommandMgr ()
if _ , err := cmdMgr . RunPipeToFile ( path . Join ( info . TargetDir , info . FileName ),
2026-04-28 11:17:30 +08:00
cmd . PipeCommand { Name : "docker" , Args : args },
cmd . PipeCommand { Name : "gzip" , Args : [] string { "-cf" }},
); err != nil {
return fmt . Errorf ( "handle backup database failed, err: %v" , err )
2024-07-23 14:48:37 +08:00
}
return nil
}
func ( r * Local ) Recover ( info RecoverInfo ) error {
fi , _ := os . Open ( info . SourceFile )
2026-02-27 22:43:50 +08:00
defer func () { _ = fi . Close () }()
2025-07-28 18:01:05 +08:00
mysqlCli := r . Type
if mysqlCli == "mysql-cluster" {
mysqlCli = "mysql"
}
2025-09-15 16:27:11 +08:00
cmd := exec . Command ( "docker" , "exec" , "-i" , r . ContainerName , mysqlCli , "-uroot" , "-p" + r . Password , "--default-character-set=" + info . Format , info . Name )
2024-07-23 14:48:37 +08:00
if strings . HasSuffix ( info . SourceFile , ".gz" ) {
gzipFile , err := os . Open ( info . SourceFile )
if err != nil {
return err
}
2026-02-27 22:43:50 +08:00
defer func () { _ = gzipFile . Close () }()
2024-07-23 14:48:37 +08:00
gzipReader , err := gzip . NewReader ( gzipFile )
if err != nil {
return err
}
2026-02-27 22:43:50 +08:00
defer func () { _ = gzipReader . Close () }()
2024-07-23 14:48:37 +08:00
cmd . Stdin = gzipReader
} else {
cmd . Stdin = fi
}
stdout , err := cmd . CombinedOutput ()
stdStr := strings . ReplaceAll ( string ( stdout ), "mysql: [Warning] Using a password on the command line interface can be insecure.\n" , "" )
2025-07-28 18:01:05 +08:00
if err != nil || strings . HasPrefix ( stdStr , "ERROR " ) {
2024-07-23 14:48:37 +08:00
return errors . New ( stdStr )
}
return nil
}
func ( r * Local ) SyncDB ( version string ) ([] SyncDBInfo , error ) {
var datas [] SyncDBInfo
2025-11-25 15:02:37 +08:00
lines , err := r . ExecSQLForRows ( "SELECT SCHEMA_NAME, DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA" , 300 )
2024-07-23 14:48:37 +08:00
if err != nil {
return datas , err
}
for _ , line := range lines {
parts := strings . Fields ( line )
2025-11-25 15:02:37 +08:00
if len ( parts ) != 3 {
2024-07-23 14:48:37 +08:00
continue
}
if parts [ 0 ] == "SCHEMA_NAME" || parts [ 0 ] == "information_schema" || parts [ 0 ] == "mysql" || parts [ 0 ] == "performance_schema" || parts [ 0 ] == "sys" || parts [ 0 ] == "__recycle_bin__" || parts [ 0 ] == "recycle_bin" {
continue
}
dataItem := SyncDBInfo {
Name : parts [ 0 ],
From : "local" ,
MysqlName : r . Database ,
Format : parts [ 1 ],
2025-11-25 15:02:37 +08:00
Collation : parts [ 2 ],
2024-07-23 14:48:37 +08:00
}
userLines , err := r . ExecSQLForRows ( fmt . Sprintf ( "select user,host from mysql.db where db = '%s'" , parts [ 0 ]), 300 )
if err != nil {
global . LOG . Debugf ( "sync user of db %s failed, err: %v" , parts [ 0 ], err )
dataItem . Permission = "%"
datas = append ( datas , dataItem )
continue
}
var permissionItem [] string
isLocal := true
i := 0
for _ , userline := range userLines {
userparts := strings . Fields ( userline )
if len ( userparts ) != 2 {
continue
}
if userparts [ 0 ] == "root" {
continue
}
if i == 0 {
dataItem . Username = userparts [ 0 ]
}
dataItem . Username = userparts [ 0 ]
if dataItem . Username == userparts [ 0 ] && userparts [ 1 ] == "%" {
isLocal = false
dataItem . Permission = "%"
} else if dataItem . Username == userparts [ 0 ] && userparts [ 1 ] != "localhost" {
isLocal = false
permissionItem = append ( permissionItem , userparts [ 1 ])
}
}
if len ( dataItem . Username ) == 0 {
dataItem . Permission = "%"
} else {
if isLocal {
dataItem . Permission = "localhost"
}
if len ( dataItem . Permission ) == 0 {
dataItem . Permission = strings . Join ( permissionItem , "," )
}
}
datas = append ( datas , dataItem )
}
return datas , nil
}
func ( r * Local ) Close () {}
func ( r * Local ) ExecSQL ( command string , timeout uint ) error {
2026-10-26 13:59:49 +08:00
itemCommand := append ([] string ( nil ), r . PrefixCommand ... )
2024-07-23 14:48:37 +08:00
itemCommand = append ( itemCommand , command )
2026-10-26 13:59:49 +08:00
ctx , cancel := r . commandContext ( timeout )
2024-07-23 14:48:37 +08:00
defer cancel ()
cmd := exec . CommandContext ( ctx , "docker" , itemCommand ... )
stdout , err := cmd . CombinedOutput ()
if errors . Is ( ctx . Err (), context . DeadlineExceeded ) {
2025-01-24 11:00:07 +08:00
return buserr . New ( "ErrExecTimeOut" )
2024-07-23 14:48:37 +08:00
}
2026-10-26 13:59:49 +08:00
if ctx . Err () != nil {
return ctx . Err ()
}
2024-07-23 14:48:37 +08:00
stdStr := strings . ReplaceAll ( string ( stdout ), "mysql: [Warning] Using a password on the command line interface can be insecure.\n" , "" )
if err != nil || strings . HasPrefix ( string ( stdStr ), "ERROR " ) {
return errors . New ( stdStr )
}
return nil
}
func ( r * Local ) ExecSQLForRows ( command string , timeout uint ) ([] string , error ) {
2026-10-26 13:59:49 +08:00
itemCommand := append ([] string ( nil ), r . PrefixCommand ... )
2024-07-23 14:48:37 +08:00
itemCommand = append ( itemCommand , command )
2026-10-26 13:59:49 +08:00
ctx , cancel := r . commandContext ( timeout )
2024-07-23 14:48:37 +08:00
defer cancel ()
cmd := exec . CommandContext ( ctx , "docker" , itemCommand ... )
stdout , err := cmd . CombinedOutput ()
if errors . Is ( ctx . Err (), context . DeadlineExceeded ) {
2025-01-24 11:00:07 +08:00
return nil , buserr . New ( "ErrExecTimeOut" )
2024-07-23 14:48:37 +08:00
}
2026-10-26 13:59:49 +08:00
if ctx . Err () != nil {
return nil , ctx . Err ()
}
2024-07-23 14:48:37 +08:00
stdStr := strings . ReplaceAll ( string ( stdout ), "mysql: [Warning] Using a password on the command line interface can be insecure.\n" , "" )
if err != nil || strings . HasPrefix ( string ( stdStr ), "ERROR " ) {
return nil , errors . New ( stdStr )
}
return strings . Split ( stdStr , "\n" ), nil
}
2025-11-24 16:07:14 +08:00
func ( r * Local ) LoadFormatCollation ( timeout uint ) ([] dto . MysqlFormatCollationOption , error ) {
std , err := r . ExecSQLForRows ( "SELECT CHARACTER_SET_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLLATIONS ORDER BY CHARACTER_SET_NAME, COLLATION_NAME;" , timeout )
if err != nil {
return nil , err
}
formatMap := make ( map [ string ][] string )
for _ , item := range std {
if strings . ToLower ( item ) == "character_set_name\tcollation_name" {
continue
}
parts := strings . Split ( item , "\t" )
if len ( parts ) != 2 {
continue
}
2025-11-26 17:21:21 +08:00
if parts [ 0 ] == "NULL" {
continue
}
2025-11-24 16:07:14 +08:00
if _ , ok := formatMap [ parts [ 0 ]]; ! ok {
formatMap [ parts [ 0 ]] = [] string { parts [ 1 ]}
} else {
formatMap [ parts [ 0 ]] = append ( formatMap [ parts [ 0 ]], parts [ 1 ])
}
}
options := [] dto . MysqlFormatCollationOption {}
for key , val := range formatMap {
options = append ( options , dto . MysqlFormatCollationOption {
Format : key ,
Collations : val ,
})
}
return options , nil
}