// New opens connection to postgres database and starts collector for metrics func New(m *metrics.MetricContext, user, config string) (*PostgresStat, error) { s := new(PostgresStat) s.dsn = map[string]string{ "dbname": "postgres", "user": user, "sslmode": "disable", "host": "localhost", } var err error s.Modes = make(map[string]*ModeMetrics) s.DBs = make(map[string]*DBMetrics) s.db, err = tools.New(s.dsn) s.dbLock = &sync.Mutex{} s.modeLock = &sync.Mutex{} s.m = m s.PGDATA = "/data/pgsql" if err != nil { s.db.Log(err) return nil, err } s.Metrics = PostgresStatMetricsNew(m) return s, nil }
//get size of tables and databases and binlogs func (s *PostgresStat) getSizes() { //get binlog sizes out, err := exec.Command("ls", "-l", "/data/pgsql/pg_xlog/").Output() if err != nil { s.db.Log(err) s.wg.Done() return } blob := string(out) count := 0 total := float64(0) for _, line := range strings.Split(blob, "\n") { cols := strings.Split(line, " ") if len(cols) < 5 { continue } count++ tmp, _ := strconv.ParseFloat(cols[4], 64) total += tmp } s.Metrics.BinlogFiles.Set(float64(count)) s.Metrics.DBSizeBinlogs.Set(float64(total)) //get database sizes //method similar here to the mysql one res, err := s.db.QueryMapFirstColumnToRow(dbSizeQuery) if err != nil { s.db.Log(err) s.wg.Done() return } for key, value := range res { //key being the name of the db, value its size in bytes dbname := strings.TrimSpace(string(key)) size, err := strconv.ParseInt(string(value[0]), 10, 64) if err != nil { s.db.Log(err) } if size > 0 { s.checkDB(dbname) s.dbLock.Lock() s.DBs[dbname].SizeBytes.Set(float64(size)) s.dbLock.Unlock() } } //get table sizes for dbname := range res { newDsn := make(map[string]string) for k, v := range s.dsn { newDsn[k] = v } newDsn["dbname"] = dbname newDB, err := tools.New(newDsn) if err != nil { s.db.Log("Cannot connect to database: " + dbname) continue } cmd := fmt.Sprintf(tblSizeQuery, dbname) res, err := newDB.QueryMapFirstColumnToRow(cmd) if err != nil { s.db.Log(err) } for relation, sizes := range res { size, _ := strconv.ParseInt(sizes[0], 10, 64) if size > 0 { s.checkTable(dbname, relation) s.dbLock.Lock() s.DBs[dbname].Tables[relation].SizeBytes.Set(float64(size)) s.dbLock.Unlock() } } newDB.Close() } s.wg.Done() return }