github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/lorry/engines/wesql/get_replica_role.go (about)

     1  /*
     2  Copyright (C) 2022-2023 ApeCloud Co., Ltd
     3  
     4  This file is part of KubeBlocks project
     5  
     6  This program is free software: you can redistribute it and/or modify
     7  it under the terms of the GNU Affero General Public License as published by
     8  the Free Software Foundation, either version 3 of the License, or
     9  (at your option) any later version.
    10  
    11  This program is distributed in the hope that it will be useful
    12  but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  GNU Affero General Public License for more details.
    15  
    16  You should have received a copy of the GNU Affero General Public License
    17  along with this program.  If not, see <http://www.gnu.org/licenses/>.
    18  */
    19  
    20  package wesql
    21  
    22  import (
    23  	"context"
    24  	"fmt"
    25  
    26  	"github.com/pkg/errors"
    27  
    28  	"github.com/1aal/kubeblocks/pkg/lorry/dcs"
    29  	"github.com/1aal/kubeblocks/pkg/lorry/engines/mysql"
    30  )
    31  
    32  func (mgr *Manager) GetReplicaRole(ctx context.Context, cluter *dcs.Cluster) (string, error) {
    33  	sql := "select CURRENT_LEADER, ROLE, SERVER_ID  from information_schema.wesql_cluster_local"
    34  
    35  	rows, err := mgr.DB.QueryContext(ctx, sql)
    36  	if err != nil {
    37  		mgr.Logger.Error(err, fmt.Sprintf("error executing %s", sql))
    38  		return "", errors.Wrapf(err, "error executing %s", sql)
    39  	}
    40  
    41  	defer func() {
    42  		_ = rows.Close()
    43  		_ = rows.Err()
    44  	}()
    45  
    46  	var curLeader string
    47  	var role string
    48  	var serverID string
    49  	var isReady bool
    50  	for rows.Next() {
    51  		if err = rows.Scan(&curLeader, &role, &serverID); err != nil {
    52  			mgr.Logger.Error(err, "Role query error")
    53  			return role, err
    54  		}
    55  		isReady = true
    56  	}
    57  	if isReady {
    58  		return role, nil
    59  	}
    60  	return "", errors.Errorf("exec sql %s failed: no data returned", sql)
    61  }
    62  
    63  func (mgr *Manager) GetClusterLocalInfo(ctx context.Context) (mysql.RowMap, error) {
    64  	var result mysql.RowMap
    65  	sql := "select * from information_schema.wesql_cluster_local;"
    66  	err := mysql.QueryRowsMap(mgr.DB, sql, func(rMap mysql.RowMap) error {
    67  		result = rMap
    68  		return nil
    69  	})
    70  	if err != nil {
    71  		mgr.Logger.Error(err, fmt.Sprintf("error executing %s", sql))
    72  		return nil, err
    73  	}
    74  	return result, nil
    75  
    76  }