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 {
62 // deliberately limit the pool size to 5 to avoid "problems" if any queries hang.
63 dbh.SetMaxOpenConns(5) // hard-coded value!
68 // connect to MySQL using various component parts needed to make the dsn
69 func connect_by_components( components map[string]string ) *sql.DB {
72 lib.Logger.Println("connect_by_components() connecting to database")
74 new_dsn := mysql_defaults_file.BuildDSN(components, "performance_schema")
75 dbh, err = sql.Open(sql_driver, new_dsn)
79 if err = dbh.Ping(); err != nil {
86 // make chan for termbox events and run a poller to send events to the channel
87 // - return the channel
88 func new_tb_chan() chan termbox.Event {
89 termboxChan := make(chan termbox.Event)
92 termboxChan <- termbox.PollEvent()
99 fmt.Println(lib.MyName() + " - " + lib.Copyright())
101 fmt.Println("Top-like program to show MySQL activity by using information collected")
102 fmt.Println("from performance_schema.")
104 fmt.Println("Usage: " + lib.MyName() + " <options>")
106 fmt.Println("Options:")
107 fmt.Println("--defaults-file=/path/to/defaults.file Connect to MySQL using given defaults-file" )
108 fmt.Println("--help Show this help message")
109 fmt.Println("--version Show the version")
110 fmt.Println("--host=<hostname> MySQL host to connect to")
111 fmt.Println("--port=<port> MySQL port to connect to")
112 fmt.Println("--socket=<path> MySQL path of the socket to connect to")
113 fmt.Println("--user=<user> User to connect with")
114 fmt.Println("--password=<password> Password to use when connecting")
117 // pstop requires MySQL 5.6+ or MariaDB 10.0+. Check the version
118 // rather than giving an error message if the requires P_S tables can't
120 func validate_mysql_version(dbh *sql.DB) error {
121 var tables = [...]string{
122 "performance_schema.events_waits_summary_global_by_event_name",
123 "performance_schema.file_summary_by_instance",
124 "performance_schema.table_io_waits_summary_by_table",
125 "performance_schema.table_lock_waits_summary_by_table",
128 lib.Logger.Println("validate_mysql_version()")
130 lib.Logger.Println("- Getting MySQL version")
131 err, mysql_version := lib.SelectGlobalVariableByVariableName(dbh, "VERSION")
135 lib.Logger.Println("- mysql_version: '" + mysql_version + "'")
137 if !re_valid_version.MatchString(mysql_version) {
138 err := errors.New(lib.MyName() + " does not work with MySQL version " + mysql_version)
141 lib.Logger.Println("OK: MySQL version is valid, continuing")
143 lib.Logger.Println("Checking access to required tables:")
144 for i := range tables {
145 if err := lib.CheckTableAccess(dbh, tables[i]); err == nil {
146 lib.Logger.Println("OK: " + tables[i] + " found")
151 lib.Logger.Println("OK: all table checks passed")
157 var defaults_file string = ""
161 if *cpuprofile != "" {
162 f, err := os.Create(*cpuprofile)
166 pprof.StartCPUProfile(f)
167 defer pprof.StopCPUProfile()
171 lib.Logger.EnableLogging(true)
174 fmt.Println(lib.MyName() + " version " + version.Version())
182 lib.Logger.Println("Starting " + lib.MyName())
186 if *flag_host != "" || *flag_socket != "" {
187 lib.Logger.Println("--host= or --socket= defined")
188 var components = make(map[string]string)
189 if *flag_host != "" && *flag_socket != "" {
190 fmt.Println(lib.MyName() + ": Do not specify --host and --socket together" )
193 if *flag_host != "" {
194 components["host"] = *flag_host
197 if *flag_socket == "" {
198 components["port"] = fmt.Sprintf("%d", *flag_port)
200 fmt.Println(lib.MyName() + ": Do not specify --socket and --port together" )
204 if *flag_socket != "" {
205 components["socket"] = *flag_socket
207 if *flag_user != "" {
208 components["user"] = *flag_user
210 if *flag_password != "" {
211 components["password"] = *flag_password
213 dbh = connect_by_components( components )
215 if flag_defaults_file != nil && *flag_defaults_file != "" {
216 lib.Logger.Println("--defaults-file defined")
217 defaults_file = *flag_defaults_file
219 lib.Logger.Println("connecting by implicit defaults file")
221 dbh = connect_by_defaults_file( defaults_file )
224 if err := validate_mysql_version(dbh); err != nil {
228 var state state.State
229 var wi wait_info.WaitInfo
230 wi.SetWaitInterval(time.Second)
232 sigChan := make(chan os.Signal, 1)
233 done := make(chan struct{})
235 termboxChan := new_tb_chan()
237 signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
240 for !state.Finished() {
243 fmt.Println("exiting")
245 case sig := <-sigChan:
246 fmt.Println("Caught a signal", sig)
248 case <-wi.WaitNextPeriod():
252 case event := <-termboxChan:
253 // switch on event type
255 case termbox.EventKey: // actions depend on key
257 case termbox.KeyCtrlZ, termbox.KeyCtrlC, termbox.KeyEsc:
259 case termbox.KeyArrowLeft: // left arrow change to previous display mode
260 state.DisplayPrevious()
262 case termbox.KeyTab, termbox.KeyArrowRight: // tab or right arrow - change to next display mode
267 case '-': // decrease the interval if > 1
268 if wi.WaitInterval() > time.Second {
269 wi.SetWaitInterval(wi.WaitInterval() - time.Second)
271 case '+': // increase interval by creating a new ticker
272 wi.SetWaitInterval(wi.WaitInterval() + time.Second)
273 case 'h', '?': // help
274 state.SetHelp(!state.Help())
277 case 't': // toggle between absolute/relative statistics
278 state.SetWantRelativeStats(!state.WantRelativeStats())
280 case 'z': // reset the statistics to now by taking a query of current values
281 state.ResetDBStatistics()
284 case termbox.EventResize: // set sizes
285 state.ScreenSetSize(event.Width, event.Height)
287 case termbox.EventError: // quit
288 log.Fatalf("Quitting because of termbox error: \n%s\n", event.Err)
293 lib.Logger.Println("Terminating " + lib.MyName())