1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
|
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bufio"
"context"
"fmt"
"io"
"log"
"os"
"os/user"
"path"
"github.com/go-git/go-billy/v5/osfs"
ui "github.com/gizak/termui/v3"
"github.com/gizak/termui/v3/widgets"
"github.com/pingcap/tiup/pkg/environment"
"github.com/pingcap/tiup/pkg/localdata"
"github.com/pingcap/tiup/pkg/repository"
gops "github.com/shirou/gopsutil/process"
"github.com/spf13/cobra"
_ "github.com/xo/usql/drivers/mysql"
"github.com/xo/usql/env"
"github.com/xo/usql/handler"
"github.com/xo/usql/rline"
)
func main() {
if err := execute(); err != nil {
os.Exit(1)
}
}
func execute() error {
rootCmd := &cobra.Command{
Use: "tiup client",
Short: "Connect a TiDB cluster in your local host",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
target := ""
if len(args) > 0 {
target = args[0]
}
env, err := environment.InitEnv(repository.Options{}, repository.MirrorOptions{})
if err != nil {
return err
}
environment.SetGlobalEnv(env)
return connect(target)
},
PostRunE: func(cmd *cobra.Command, args []string) error {
return environment.GlobalEnv().Close()
},
}
return rootCmd.Execute()
}
func connect(target string) error {
tiupHome := os.Getenv(localdata.EnvNameHome)
if tiupHome == "" {
return fmt.Errorf("env variable %s not set, are you running client out of tiup?", localdata.EnvNameHome)
}
endpoints, err := scanEndpoint(tiupHome)
if err != nil {
return fmt.Errorf("error on read files: %s", err.Error())
}
if len(endpoints) == 0 {
return fmt.Errorf("It seems no playground is running, execute `tiup playground` to start one")
}
var ep *endpoint
if target == "" {
if ep = selectEndpoint(endpoints); ep == nil {
os.Exit(0)
}
} else {
for _, end := range endpoints {
if end.component == target {
ep = end
}
}
if ep == nil {
return fmt.Errorf("specified instance %s not found, maybe it's not alive now, execute `tiup status` to see instance list", target)
}
}
u, err := user.Current()
if err != nil {
return fmt.Errorf("can't get current user: %s", err.Error())
}
l, err := rline.New(false, false, false, "", env.HistoryFile(u))
if err != nil {
return fmt.Errorf("can't open history file: %s", err.Error())
}
dataDir := os.Getenv(localdata.EnvNameInstanceDataDir)
h := handler.New(l, u, dataDir, osfs.New(dataDir), true)
if err = h.Open(context.TODO(), ep.dsn); err != nil {
return fmt.Errorf("can't open connection to %s: %s", ep.dsn, err.Error())
}
if err = h.Run(); err != io.EOF {
return err
}
return nil
}
func scanEndpoint(tiupHome string) ([]*endpoint, error) {
endpoints := []*endpoint{}
files, err := os.ReadDir(path.Join(tiupHome, localdata.DataParentDir))
if err != nil {
return nil, err
}
for _, file := range files {
if !isInstanceAlive(tiupHome, file.Name()) {
continue
}
endpoints = append(endpoints, readDsn(path.Join(tiupHome, localdata.DataParentDir, file.Name()), file.Name())...)
}
return endpoints, nil
}
func isInstanceAlive(tiupHome, instance string) bool {
s, err := environment.GlobalEnv().Profile().ReadMetaFile(instance)
if err != nil {
return false
}
exist, _ := gops.PidExists(int32(s.Pid))
return exist
}
func readDsn(dir, component string) []*endpoint {
endpoints := []*endpoint{}
file, err := os.Open(path.Join(dir, "dsn"))
if err != nil {
return endpoints
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
endpoints = append(endpoints, &endpoint{
component: component,
dsn: scanner.Text(),
})
}
return endpoints
}
func selectEndpoint(endpoints []*endpoint) *endpoint {
if err := ui.Init(); err != nil {
log.Fatalf("failed to initialize termui: %v", err)
}
defer ui.Close()
l := widgets.NewList()
l.Title = "Choose an endpoint to connect"
ml := 0
for _, ep := range endpoints {
if ml < len(ep.component) {
ml = len(ep.component)
}
}
fmtStr := fmt.Sprintf(" %%-%ds %%s", ml)
for _, ep := range endpoints {
l.Rows = append(l.Rows, fmt.Sprintf(fmtStr, ep.component, ep.dsn))
}
l.TextStyle = ui.NewStyle(ui.ColorWhite)
l.SelectedRowStyle = ui.NewStyle(ui.ColorGreen)
l.WrapText = false
size := min(len(endpoints), 16)
l.SetRect(0, 0, 80, size+2)
ui.Render(l)
uiEvents := ui.PollEvents()
for {
e := <-uiEvents
_ = os.WriteFile("/tmp/log", []byte(e.ID+"\n"), 0664)
switch e.ID {
case "q", "<C-c>":
return nil
case "j", "<Down>":
l.ScrollDown()
case "k", "<Up>":
l.ScrollUp()
case "<Enter>":
return endpoints[l.SelectedRow]
}
ui.Render(l)
}
}
|