<commit_before>// Copyright © 2017 <NAME> <<EMAIL>>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"bufio"
	"bytes"
	"database/sql"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"

	log "github.com/Sirupsen/logrus"
	minio "github.com/minio/minio-go"
	ec "github.com/xxorde/pgglaskugel/errorcheck"
	util "github.com/xxorde/pgglaskugel/util"
	"github.com/xxorde/pgglaskugel/wal"

	"github.com/kardianos/osext"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

const (
	myName = "pgglaskugel"

	// Logo
	logo = `
     __________
    /          \
   /   ______   \
  /   /     0\   \
 /   /        \   \
 \   \        /   /
  \   \______/   /
   \  /______\  /
    \__________/
	`
)

var (
	// Version holds the current version
	Version string

	// GitHash holds the hash for the current commit
	GitHash string

	// Name of the current host
	hostname string

	// Name of the PostgreSQL cluster
	clusterName string

	// own executable path
	myExecutable string

	// Vars for configuration
	cfgFile    string
	archiveDir string
	backupDir  string
	walDir     string

	// Minimal and maximal PostgreSQL version (numeric)
	pgMinVersion           = 90500
	pgMaxVersion           = 90699
	supportedMajorVersions = [...]string{"9.5", "9.6"}

	// sub folders
	subDirBasebackup = "/basebackup/"
	subDirWal        = "/wal/"

	// commands
	cmdTar        = "tar"
	cmdBasebackup = "pg_basebackup"
	cmdZstd       = "zstd"
	cmdZstdcat    = "zstdcat"
	cmdGpg        = "gpg"

	baseBackupTools = []string{
		cmdTar,
		cmdBasebackup,
		cmdZstd,
		cmdZstdcat,
		cmdGpg,
	}

	// Default number of parallel jobs
	defaultJobs = runtime.NumCPU()

	// Store time of programm start
	startTime time.Time

	// PGP keys for encryption
	keyDir = "~/.pgglaskugel/"

	// RootCmd represents the base command when called without any subcommands
	RootCmd = &cobra.Command{
		Use:   myName,
		Short: "A tool to backup PostgreSQL databases",
		Long:  `A tool that helps you to manage your PostgreSQL backups.` + logo,
	}
)

// storeStream is an interface for functions that store a stream in an storage backend
type storeStream func(*io.Reader, string)

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	// Measure time from here
	startTime = time.Now()

	// Local error var declared here to make it easier to define the scope of other vars
	var err error

	myExecutable, err = osext.Executable()
	if err != nil {
		log.Warn(err)
	}

	hostname, err = os.Hostname()
	if err != nil {
		log.Warn(err)
	}

	cobra.OnInitialize(initConfig)
	// Set the default values for the globally used flags
	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Config file")
	RootCmd.PersistentFlags().String("cluster_name", hostname, "Name of the cluster, used in backup name")
	RootCmd.PersistentFlags().StringP("pgdata", "D", "$PGDATA", "Base directory of your PostgreSQL instance aka. pg_data")
	RootCmd.PersistentFlags().Bool("pgdata-auto", true, "Try to find pgdata if not set correctly (via SQL)")
	RootCmd.PersistentFlags().String("archivedir", "/var/lib/postgresql/backup/pgglaskugel", "Dir where the backups")
	RootCmd.PersistentFlags().Bool("debug", false, "Enable debug mode to increase verbosity")
	RootCmd.PersistentFlags().Bool("json", false, "Generate output as JSON")
	RootCmd.PersistentFlags().String("connection", "host=/var/run/postgresql user=postgres dbname=postgres", "Connection string to connect to the database")
	RootCmd.PersistentFlags().IntP("jobs", "j", defaultJobs, "The number of jobs to run parallel. default depends on cores ")
	RootCmd.PersistentFlags().String("backup_to", "file", "Backup destination (file|s3)")
	RootCmd.PersistentFlags().String("archive_to", "file", "WAL destination (file|s3)")
	RootCmd.PersistentFlags().String("s3_endpoint", "127.0.0.1:9000", "S3 endpoint")
	RootCmd.PersistentFlags().String("s3_bucket_backup", "pgglaskugel-basebackup", "Bucket name for base backups")
	RootCmd.PersistentFlags().String("s3_bucket_wal", "pgglaskugel-wal", "Bucket name for WAL files")
	RootCmd.PersistentFlags().String("s3_access_key", "<KEY>", "access_key")
	RootCmd.PersistentFlags().String("s3_secret_key", "<KEY>", "secret_key")
	RootCmd.PersistentFlags().String("s3_location", "us-east-1", "S3 datacenter location")
	RootCmd.PersistentFlags().Bool("s3_ssl", true, "If SSL (TLS) should be used for S3")
	RootCmd.PersistentFlags().Int("s3_protocol_version", -1, "Version of the S3 protocol version (2,4,-1=auto)")
	RootCmd.PersistentFlags().Bool("encrypt", false, "Enable encryption for S3 storage")
	RootCmd.PersistentFlags().String("recipient", "pgglaskugel", "The recipient for PGP encryption (key identifier)")
	RootCmd.PersistentFlags().String("path_to_tar", "/bin/tar", "Path to the tar command")
	RootCmd.PersistentFlags().String("path_to_basebackup", "/usr/bin/pg_basebackup", "Path to the basebackup command")
	RootCmd.PersistentFlags().String("path_to_zstd", "/usr/bin/zstd", "Path to the zstd command")
	RootCmd.PersistentFlags().String("path_to_zstdcat", "/usr/bin/zstdcat", "Path to the zstdcat command")
	RootCmd.PersistentFlags().String("path_to_gpg", "/usr/bin/gpg", "Path to the gpg command")
<commit_msg>Change description<commit_after>// Copyright © 2017 <NAME> <<EMAIL> <EMAIL>>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"bufio"
	"bytes"
	"database/sql"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"

	log "github.com/Sirupsen/logrus"
	minio "github.com/minio/minio-go"
	ec "github.com/xxorde/pgglaskugel/errorcheck"
	util "github.com/xxorde/pgglaskugel/util"
	"github.com/xxorde/pgglaskugel/wal"

	"github.com/kardianos/osext"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

const (
	myName = "pgglaskugel"

	// Logo
	logo = `
     __________
    /          \
   /   ______   \
  /   /     0\   \
 /   /        \   \
 \   \        /   /
  \   \______/   /
   \  /______\  /
    \__________/
	`
)

var (
	// Version holds the current version
	Version string

	// GitHash holds the hash for the current commit
	GitHash string

	// Name of the current host
	hostname string

	// Name of the PostgreSQL cluster
	clusterName string

	// own executable path
	myExecutable string

	// Vars for configuration
	cfgFile    string
	archiveDir string
	backupDir  string
	walDir     string

	// Minimal and maximal PostgreSQL version (numeric)
	pgMinVersion           = 90500
	pgMaxVersion           = 90699
	supportedMajorVersions = [...]string{"9.5", "9.6"}

	// sub folders
	subDirBasebackup = "/basebackup/"
	subDirWal        = "/wal/"

	// commands
	cmdTar        = "tar"
	cmdBasebackup = "pg_basebackup"
	cmdZstd       = "zstd"
	cmdZstdcat    = "zstdcat"
	cmdGpg        = "gpg"

	baseBackupTools = []string{
		cmdTar,
		cmdBasebackup,
		cmdZstd,
		cmdZstdcat,
		cmdGpg,
	}

	// Default number of parallel jobs
	defaultJobs = runtime.NumCPU()

	// Store time of programm start
	startTime time.Time

	// PGP keys for encryption
	keyDir = "~/.pgglaskugel/"

	// RootCmd represents the base command when called without any subcommands
	RootCmd = &cobra.Command{
		Use:   myName,
		Short: "A tool to backup PostgreSQL databases",
		Long:  `A tool that helps you to manage your PostgreSQL backups.` + logo,
	}
)

// storeStream is an interface for functions that store a stream in an storage backend
type storeStream func(*io.Reader, string)

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	// Measure time from here
	startTime = time.Now()

	// Local error var declared here to make it easier to define the scope of other vars
	var err error

	myExecutable, err = osext.Executable()
	if err != nil {
		log.Warn(err)
	}

	hostname, err = os.Hostname()
	if err != nil {
		log.Warn(err)
	}

	cobra.OnInitialize(initConfig)
	// Set the default values for the globally used flags
	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Config file")
	RootCmd.PersistentFlags().String("cluster_name", hostname, "Name of the cluster, used in backup name")
	RootCmd.PersistentFlags().StringP("pgdata", "D", "$PGDATA", "Base directory of your PostgreSQL instance aka. pg_data")
	RootCmd.PersistentFlags().Bool("pgdata-auto", true, "Try to find pgdata if not set correctly (via SQL)")
	RootCmd.PersistentFlags().String("archivedir", "/var/lib/postgresql/backup/pgglaskugel", "Dir where the backups")
	RootCmd.PersistentFlags().Bool("debug", false, "Enable debug mode to increase verbosity")
	RootCmd.PersistentFlags().Bool("json", false, "Generate output as JSON")
	RootCmd.PersistentFlags().String("connection", "host=/var/run/postgresql user=postgres dbname=postgres", "Connection string to connect to the database")
	RootCmd.PersistentFlags().IntP("jobs", "j", defaultJobs, "The number of jobs to run parallel, default depends on cores ")
	RootCmd.PersistentFlags().String("backup_to", "file", "Backup destination (file|s3)")
	RootCmd.PersistentFlags().String("archive_to", "file", "WAL destination (file|s3)")
	RootCmd.PersistentFlags().String("s3_endpoint", "127.0.0.1:9000", "S3 endpoint")
	RootCmd.PersistentFlags().String("s3_bucket_backup", "pgglaskugel-basebackup", "Bucket name for base backups")
	RootCmd.PersistentFlags().String("s3_bucket_wal", "pgglaskugel-wal", "Bucket name for WAL files")
	RootCmd.PersistentFlags().String("s3_access_key", "<KEY>", "access_key")
	RootCmd.PersistentFlags().String("s3_secret_key", "<KEY>", "secret_key")
	RootCmd.PersistentFlags().String("s3_location", "us-east-1", "S3 datacenter location")
	RootCmd.PersistentFlags().Bool("s3_ssl", true, "If SSL (TLS) should be used for S3")
	RootCmd.PersistentFlags().Int("s3_protocol_version", -1, "Version of the S3 protocol version (2,4,-1=auto)")
	RootCmd.PersistentFlags().Bool("encrypt", false, "Enable encryption for S3 storage")
	RootCmd.PersistentFlags().String("recipient", "pgglaskugel", "The recipient for PGP encryption (key identifier)")
	RootCmd.PersistentFlags().String("path_to_tar", "/bin/tar", "Path to the tar command")
	RootCmd.PersistentFlags().String("path_to_basebackup", "/usr/bin/pg_basebackup", "Path to the basebackup command")
	RootCmd.PersistentFlags().String("path_to_zstd", "/usr/bin/zstd", "Path to the zstd command")
	RootCmd.PersistentFlags().String("path_to_zstdcat", "/usr/bin/zstdcat", "Path to the zstdcat command")
	RootCmd.PersistentFlags().String("path_to_gpg", "/usr/bin/gpg", "Path to the gpg command")

{'fraction_non_alphanumeric': 0.12417947331840297, 'fraction_numerical': 0.008340412387056916, 'mean_word_length': 4.003863987635239, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '853981', 'n_tokens_mistral': 4332, 'n_tokens_neox': 4183, 'n_words': 1276}