1 // pstop - Top like progream which collects information from MySQL's
2 // performance_schema database.
18 _ "github.com/go-sql-driver/mysql"
19 "github.com/nsf/termbox-go"
21 "github.com/sjmudd/mysql_defaults_file"
22 "github.com/sjmudd/pstop/lib"
23 "github.com/sjmudd/pstop/state"
24 "github.com/sjmudd/pstop/version"
25 "github.com/sjmudd/pstop/wait_info"
30 db = "performance_schema"
34 flag_debug = flag.Bool("debug", false, "Enabling debug logging")
35 flag_defaults_file = flag.String("defaults-file", "", "Provide a defaults-file to use to connect to MySQL")
36 flag_help = flag.Bool("help", false, "Provide some help for "+lib.MyName())
37 flag_host = flag.String("host", "", "Provide the hostname of the MySQL to connect to")
38 flag_port = flag.Int("port", 0 , "Provide the port number of the MySQL to connect to (default: 3306)") /* deliberately 0 here, defaults to 3306 elsewhere */
39 flag_socket = flag.String("socket", "", "Provide the path to the local MySQL server to connect to")
40 flag_password = flag.String("password", "", "Provide the password when connecting to the MySQL server")
41 flag_user = flag.String("user", "", "Provide the username to connect with to MySQL (default: $USER)")
42 flag_version = flag.Bool("version", false, "Show the version of "+lib.MyName())
43 cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
45 re_valid_version = regexp.MustCompile(`^(5\.[67]\.|10\.[01])`)
48 // Connect to the database with the given defaults-file, or ~/.my.cnf if not provided.
49 func connect_by_defaults_file( defaults_file string ) *sql.DB {
52 lib.Logger.Println("connect_by_defaults_file() connecting to database")
54 dbh, err = mysql_defaults_file.OpenUsingDefaultsFile(sql_driver, defaults_file, "performance_schema")
58 if err = dbh.Ping(); err != nil {
65 // connect to MySQL using various component parts needed to make the dsn
66 func connect_by_components( components map[string]string ) *sql.DB {
69 lib.Logger.Println("connect_by_components() connecting to database")
71 new_dsn := mysql_defaults_file.BuildDSN(components, "performance_schema")
72 dbh, err = sql.Open(sql_driver, new_dsn)
76 if err = dbh.Ping(); err != nil {
83 // make chan for termbox events and run a poller to send events to the channel
84 // - return the channel
85 func new_tb_chan() chan termbox.Event {
86 termboxChan := make(chan termbox.Event)
89 termboxChan <- termbox.PollEvent()
96 fmt.Println(lib.MyName() + " - " + lib.Copyright())
98 fmt.Println("Top-like program to show MySQL activity by using information collected")
99 fmt.Println("from performance_schema.")
101 fmt.Println("Usage: " + lib.MyName() + " <options>")
103 fmt.Println("Options:")
104 fmt.Println("--defaults-file=/path/to/defaults.file Connect to MySQL using given defaults-file" )
105 fmt.Println("--help Show this help message")
106 fmt.Println("--version Show the version")
107 fmt.Println("--host=<hostname> MySQL host to connect to")
108 fmt.Println("--port=<port> MySQL port to connect to")
109 fmt.Println("--socket=<path> MySQL path of the socket to connect to")
110 fmt.Println("--user=<user> User to connect with")
111 fmt.Println("--password=<password> Password to use when connecting")
114 // pstop requires MySQL 5.6+ or MariaDB 10.0+. Check the version
115 // rather than giving an error message if the requires P_S tables can't
117 func validate_mysql_version(dbh *sql.DB) error {
118 var tables = [...]string{
119 "performance_schema.file_summary_by_instance",
120 "performance_schema.table_io_waits_summary_by_table",
121 "performance_schema.table_lock_waits_summary_by_table",
124 lib.Logger.Println("validate_mysql_version()")
126 lib.Logger.Println("- Getting MySQL version")
127 err, mysql_version := lib.SelectGlobalVariableByVariableName(dbh, "VERSION")
131 lib.Logger.Println("- mysql_version: '" + mysql_version + "'")
133 if !re_valid_version.MatchString(mysql_version) {
134 err := errors.New(lib.MyName() + " does not work with MySQL version " + mysql_version)
137 lib.Logger.Println("OK: MySQL version is valid, continuing")
139 lib.Logger.Println("Checking access to required tables:")
140 for i := range tables {
141 if err := lib.CheckTableAccess(dbh, tables[i]); err == nil {
142 lib.Logger.Println("OK: " + tables[i] + " found")
147 lib.Logger.Println("OK: all table checks passed")
153 var defaults_file string = ""
157 if *cpuprofile != "" {
158 f, err := os.Create(*cpuprofile)
162 pprof.StartCPUProfile(f)
163 defer pprof.StopCPUProfile()
167 lib.Logger.EnableLogging(true)
170 fmt.Println(lib.MyName() + " version " + version.Version())
178 lib.Logger.Println("Starting " + lib.MyName())
182 if *flag_host != "" || *flag_socket != "" {
183 lib.Logger.Println("--host= or --socket= defined")
184 var components = make(map[string]string)
185 if *flag_host != "" && *flag_socket != "" {
186 fmt.Println(lib.MyName() + ": Do not specify --host and --socket together" )
189 if *flag_host != "" {
190 components["host"] = *flag_host
193 if *flag_socket == "" {
194 components["port"] = fmt.Sprintf("%d", *flag_port)
196 fmt.Println(lib.MyName() + ": Do not specify --socket and --port together" )
200 if *flag_socket != "" {
201 components["socket"] = *flag_socket
203 if *flag_user != "" {
204 components["user"] = *flag_user
206 if *flag_password != "" {
207 components["password"] = *flag_password
209 dbh = connect_by_components( components )
211 if flag_defaults_file != nil && *flag_defaults_file != "" {
212 lib.Logger.Println("--defaults-file defined")
213 defaults_file = *flag_defaults_file
215 lib.Logger.Println("connecting by implicit defaults file")
217 dbh = connect_by_defaults_file( defaults_file )
220 if err := validate_mysql_version(dbh); err != nil {
224 var state state.State
225 var wi wait_info.WaitInfo
226 wi.SetWaitInterval(time.Second)
228 sigChan := make(chan os.Signal, 1)
229 done := make(chan struct{})
231 termboxChan := new_tb_chan()
233 signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
236 for !state.Finished() {
239 fmt.Println("exiting")
241 case sig := <-sigChan:
242 fmt.Println("Caught a signal", sig)
244 case <-wi.WaitNextPeriod():
248 case event := <-termboxChan:
249 // switch on event type
251 case termbox.EventKey: // actions depend on key
253 case termbox.KeyCtrlZ, termbox.KeyCtrlC, termbox.KeyEsc:
255 case termbox.KeyArrowLeft: // left arrow change to previous display mode
256 state.DisplayPrevious()
258 case termbox.KeyTab, termbox.KeyArrowRight: // tab or right arrow - change to next display mode
263 case '-': // decrease the interval if > 1
264 if wi.WaitInterval() > time.Second {
265 wi.SetWaitInterval(wi.WaitInterval() - time.Second)
267 case '+': // increase interval by creating a new ticker
268 wi.SetWaitInterval(wi.WaitInterval() + time.Second)
269 case 'h', '?': // help
270 state.SetHelp(!state.Help())
273 case 't': // toggle between absolute/relative statistics
274 state.SetWantRelativeStats(!state.WantRelativeStats())
276 case 'z': // reset the statistics to now by taking a query of current values
277 state.ResetDBStatistics()
280 case termbox.EventResize: // set sizes
281 state.ScreenSetSize(event.Width, event.Height)
283 case termbox.EventError: // quit
284 log.Fatalf("Quitting because of termbox error: \n%s\n", event.Err)
289 lib.Logger.Println("Terminating " + lib.MyName())