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.events_waits_summary_global_by_event_name",
120 "performance_schema.file_summary_by_instance",
121 "performance_schema.table_io_waits_summary_by_table",
122 "performance_schema.table_lock_waits_summary_by_table",
125 lib.Logger.Println("validate_mysql_version()")
127 lib.Logger.Println("- Getting MySQL version")
128 err, mysql_version := lib.SelectGlobalVariableByVariableName(dbh, "VERSION")
132 lib.Logger.Println("- mysql_version: '" + mysql_version + "'")
134 if !re_valid_version.MatchString(mysql_version) {
135 err := errors.New(lib.MyName() + " does not work with MySQL version " + mysql_version)
138 lib.Logger.Println("OK: MySQL version is valid, continuing")
140 lib.Logger.Println("Checking access to required tables:")
141 for i := range tables {
142 if err := lib.CheckTableAccess(dbh, tables[i]); err == nil {
143 lib.Logger.Println("OK: " + tables[i] + " found")
148 lib.Logger.Println("OK: all table checks passed")
154 var defaults_file string = ""
158 if *cpuprofile != "" {
159 f, err := os.Create(*cpuprofile)
163 pprof.StartCPUProfile(f)
164 defer pprof.StopCPUProfile()
168 lib.Logger.EnableLogging(true)
171 fmt.Println(lib.MyName() + " version " + version.Version())
179 lib.Logger.Println("Starting " + lib.MyName())
183 if *flag_host != "" || *flag_socket != "" {
184 lib.Logger.Println("--host= or --socket= defined")
185 var components = make(map[string]string)
186 if *flag_host != "" && *flag_socket != "" {
187 fmt.Println(lib.MyName() + ": Do not specify --host and --socket together" )
190 if *flag_host != "" {
191 components["host"] = *flag_host
194 if *flag_socket == "" {
195 components["port"] = fmt.Sprintf("%d", *flag_port)
197 fmt.Println(lib.MyName() + ": Do not specify --socket and --port together" )
201 if *flag_socket != "" {
202 components["socket"] = *flag_socket
204 if *flag_user != "" {
205 components["user"] = *flag_user
207 if *flag_password != "" {
208 components["password"] = *flag_password
210 dbh = connect_by_components( components )
212 if flag_defaults_file != nil && *flag_defaults_file != "" {
213 lib.Logger.Println("--defaults-file defined")
214 defaults_file = *flag_defaults_file
216 lib.Logger.Println("connecting by implicit defaults file")
218 dbh = connect_by_defaults_file( defaults_file )
221 if err := validate_mysql_version(dbh); err != nil {
225 var state state.State
226 var wi wait_info.WaitInfo
227 wi.SetWaitInterval(time.Second)
229 sigChan := make(chan os.Signal, 1)
230 done := make(chan struct{})
232 termboxChan := new_tb_chan()
234 signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
237 for !state.Finished() {
240 fmt.Println("exiting")
242 case sig := <-sigChan:
243 fmt.Println("Caught a signal", sig)
245 case <-wi.WaitNextPeriod():
249 case event := <-termboxChan:
250 // switch on event type
252 case termbox.EventKey: // actions depend on key
254 case termbox.KeyCtrlZ, termbox.KeyCtrlC, termbox.KeyEsc:
256 case termbox.KeyArrowLeft: // left arrow change to previous display mode
257 state.DisplayPrevious()
259 case termbox.KeyTab, termbox.KeyArrowRight: // tab or right arrow - change to next display mode
264 case '-': // decrease the interval if > 1
265 if wi.WaitInterval() > time.Second {
266 wi.SetWaitInterval(wi.WaitInterval() - time.Second)
268 case '+': // increase interval by creating a new ticker
269 wi.SetWaitInterval(wi.WaitInterval() + time.Second)
270 case 'h', '?': // help
271 state.SetHelp(!state.Help())
274 case 't': // toggle between absolute/relative statistics
275 state.SetWantRelativeStats(!state.WantRelativeStats())
277 case 'z': // reset the statistics to now by taking a query of current values
278 state.ResetDBStatistics()
281 case termbox.EventResize: // set sizes
282 state.ScreenSetSize(event.Width, event.Height)
284 case termbox.EventError: // quit
285 log.Fatalf("Quitting because of termbox error: \n%s\n", event.Err)
290 lib.Logger.Println("Terminating " + lib.MyName())