Skip to content

Instantly share code, notes, and snippets.

@s-hironobu
Created December 1, 2015 13:15
Show Gist options
  • Select an option

  • Save s-hironobu/8dc0e355c20ebf8d7708 to your computer and use it in GitHub Desktop.

Select an option

Save s-hironobu/8dc0e355c20ebf8d7708 to your computer and use it in GitHub Desktop.
This program extracts all parameters in the specified PostgreSQL's configuration file which are located under the specified base directory.
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
)
func getConfParams(basedir, file string, params map[string]string) error {
confFile := basedir + "/" + file
fp, err := os.Open(confFile)
if err != nil {
return err
}
defer fp.Close()
rep_inc, _ := regexp.Compile("^include\\s+")
rep_incdir, _ := regexp.Compile("^include_dir\\s+")
scanner := bufio.NewScanner(fp)
for scanner.Scan() {
s := scanner.Text()
if rep_inc.MatchString(s) {
s = regexp.MustCompile("include").ReplaceAllString(s, "")
s = strings.Trim(strings.TrimRight(strings.TrimSpace(s), "\n"), "'")
if err = getConfParams(basedir, s, params); err != nil {
return err
}
} else if rep_incdir.MatchString(s) {
s = regexp.MustCompile("include_dir").ReplaceAllString(s, "")
s = strings.Trim(strings.TrimRight(strings.TrimSpace(s), "\n"), "'")
files, _ := ioutil.ReadDir(basedir + "/" + s)
for _, f := range files {
if err = getConfParams(basedir+"/"+s, f.Name(), params); err != nil {
return err
}
}
} else {
pf1 := "^\\s*[#]*\\s*[\\w\\/\\-]+\\s*=\\s*\\'[\\w\\/\\.\\,\\-\\%\\s*\\$\\:\\!\\+\"]*\\'"
pf2 := "^\\s*[#]*\\s*[\\w\\/\\-]+\\s*=\\s*[\\w\\/\\.\\,\\-]+"
pformats := []string{pf1, pf2}
for _, v := range pformats {
if match, _ := regexp.MatchString(v, s); match == true {
// Delete ^#
if match, _ = regexp.MatchString("^\\s*#", s); match == true {
s = strings.TrimLeft(s, "#")
}
line := strings.Split(s, "#") // Delete comment
pv := strings.Split(line[0], "=") // Get param and value
pv[0] = strings.TrimSpace(pv[0])
pv[1] = strings.TrimSpace(pv[1])
params[pv[0]] = pv[1]
}
}
}
}
if err := scanner.Err(); err != nil {
return err
}
exceptions := []string{"TB", "GB", "MB", "name", "d"} // These are examples described in the default postgresql.conf.
for _, v := range exceptions {
if _, ex := params[v]; ex == true {
delete(params, v)
}
}
return nil
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Syntax Error!\n")
fmt.Printf("Usage: %s baseDir\n\n", os.Args[0])
fmt.Printf("\tbaseDir: PostgreSQL's base directory, e.g. \"/usr/local/pgsql/data\"\n")
return
}
params := map[string]string{}
if err := getConfParams(os.Args[1], "postgresql.conf", params); err == nil {
for k, v := range params {
fmt.Printf("%s = %s\n", k, v)
}
} else {
fmt.Printf("Error: %v\n", err)
}
if strings.ToLower(strings.Trim(params["hot_standby"], "'")) == "on" {
fmt.Printf("hot_standby = on\n")
} else {
fmt.Printf("hot_standby = off OR not defined\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment