2021-04-18 15:41:13 -04:00
|
|
|
// Copyright (c) 2015-2021 MinIO, Inc.
|
2018-03-15 16:03:41 -04:00
|
|
|
//
|
2021-04-18 15:41:13 -04:00
|
|
|
// This file is part of MinIO Object Storage stack
|
2018-03-15 16:03:41 -04:00
|
|
|
//
|
2021-04-18 15:41:13 -04:00
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Affero General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
2018-03-15 16:03:41 -04:00
|
|
|
//
|
2021-04-18 15:41:13 -04:00
|
|
|
// This program is distributed in the hope that it will be useful
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Affero General Public License for more details.
|
2018-03-15 16:03:41 -04:00
|
|
|
//
|
2021-04-18 15:41:13 -04:00
|
|
|
// You should have received a copy of the GNU Affero General Public License
|
|
|
|
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
2018-03-15 16:03:41 -04:00
|
|
|
|
|
|
|
package target
|
|
|
|
|
|
|
|
import (
|
2019-10-11 20:46:03 -04:00
|
|
|
"context"
|
2018-03-15 16:03:41 -04:00
|
|
|
"database/sql"
|
|
|
|
"encoding/json"
|
2019-07-24 13:18:29 -04:00
|
|
|
"errors"
|
2018-03-15 16:03:41 -04:00
|
|
|
"fmt"
|
|
|
|
"net/url"
|
2019-07-24 13:18:29 -04:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2018-07-18 14:22:29 -04:00
|
|
|
"strconv"
|
2018-03-15 16:03:41 -04:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2018-10-23 14:44:46 -04:00
|
|
|
_ "github.com/lib/pq" // Register postgres driver
|
|
|
|
|
2021-06-01 17:59:40 -04:00
|
|
|
"github.com/minio/minio/internal/event"
|
2022-07-27 12:44:59 -04:00
|
|
|
"github.com/minio/minio/internal/logger"
|
2021-06-14 17:54:37 -04:00
|
|
|
xnet "github.com/minio/pkg/net"
|
2018-03-15 16:03:41 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
psqlTableExists = `SELECT 1 FROM %s;`
|
|
|
|
psqlCreateNamespaceTable = `CREATE TABLE %s (key VARCHAR PRIMARY KEY, value JSONB);`
|
|
|
|
psqlCreateAccessTable = `CREATE TABLE %s (event_time TIMESTAMP WITH TIME ZONE NOT NULL, event_data JSONB);`
|
|
|
|
|
|
|
|
psqlUpdateRow = `INSERT INTO %s (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;`
|
|
|
|
psqlDeleteRow = `DELETE FROM %s WHERE key = $1;`
|
|
|
|
psqlInsertRow = `INSERT INTO %s (event_time, event_data) VALUES ($1, $2);`
|
|
|
|
)
|
|
|
|
|
2019-10-23 01:59:13 -04:00
|
|
|
// Postgres constants
|
|
|
|
const (
|
2020-09-25 01:20:30 -04:00
|
|
|
PostgresFormat = "format"
|
|
|
|
PostgresConnectionString = "connection_string"
|
|
|
|
PostgresTable = "table"
|
|
|
|
PostgresHost = "host"
|
|
|
|
PostgresPort = "port"
|
|
|
|
PostgresUsername = "username"
|
|
|
|
PostgresPassword = "password"
|
|
|
|
PostgresDatabase = "database"
|
|
|
|
PostgresQueueDir = "queue_dir"
|
|
|
|
PostgresQueueLimit = "queue_limit"
|
|
|
|
PostgresMaxOpenConnections = "max_open_connections"
|
|
|
|
|
|
|
|
EnvPostgresEnable = "MINIO_NOTIFY_POSTGRES_ENABLE"
|
|
|
|
EnvPostgresFormat = "MINIO_NOTIFY_POSTGRES_FORMAT"
|
|
|
|
EnvPostgresConnectionString = "MINIO_NOTIFY_POSTGRES_CONNECTION_STRING"
|
|
|
|
EnvPostgresTable = "MINIO_NOTIFY_POSTGRES_TABLE"
|
|
|
|
EnvPostgresHost = "MINIO_NOTIFY_POSTGRES_HOST"
|
|
|
|
EnvPostgresPort = "MINIO_NOTIFY_POSTGRES_PORT"
|
|
|
|
EnvPostgresUsername = "MINIO_NOTIFY_POSTGRES_USERNAME"
|
|
|
|
EnvPostgresPassword = "MINIO_NOTIFY_POSTGRES_PASSWORD"
|
|
|
|
EnvPostgresDatabase = "MINIO_NOTIFY_POSTGRES_DATABASE"
|
|
|
|
EnvPostgresQueueDir = "MINIO_NOTIFY_POSTGRES_QUEUE_DIR"
|
|
|
|
EnvPostgresQueueLimit = "MINIO_NOTIFY_POSTGRES_QUEUE_LIMIT"
|
|
|
|
EnvPostgresMaxOpenConnections = "MINIO_NOTIFY_POSTGRES_MAX_OPEN_CONNECTIONS"
|
2019-10-23 01:59:13 -04:00
|
|
|
)
|
|
|
|
|
2018-03-15 16:03:41 -04:00
|
|
|
// PostgreSQLArgs - PostgreSQL target arguments.
|
|
|
|
type PostgreSQLArgs struct {
|
2020-09-25 01:20:30 -04:00
|
|
|
Enable bool `json:"enable"`
|
|
|
|
Format string `json:"format"`
|
|
|
|
ConnectionString string `json:"connectionString"`
|
|
|
|
Table string `json:"table"`
|
|
|
|
Host xnet.Host `json:"host"` // default: localhost
|
|
|
|
Port string `json:"port"` // default: 5432
|
|
|
|
Username string `json:"username"` // default: user running minio
|
|
|
|
Password string `json:"password"` // default: no password
|
|
|
|
Database string `json:"database"` // default: same as user
|
|
|
|
QueueDir string `json:"queueDir"`
|
|
|
|
QueueLimit uint64 `json:"queueLimit"`
|
|
|
|
MaxOpenConnections int `json:"maxOpenConnections"`
|
2018-03-15 16:03:41 -04:00
|
|
|
}
|
|
|
|
|
2018-07-18 14:22:29 -04:00
|
|
|
// Validate PostgreSQLArgs fields
|
|
|
|
func (p PostgreSQLArgs) Validate() error {
|
|
|
|
if !p.Enable {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if p.Table == "" {
|
|
|
|
return fmt.Errorf("empty table name")
|
|
|
|
}
|
|
|
|
if p.Format != "" {
|
|
|
|
f := strings.ToLower(p.Format)
|
|
|
|
if f != event.NamespaceFormat && f != event.AccessFormat {
|
|
|
|
return fmt.Errorf("unrecognized format value")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.ConnectionString != "" {
|
2018-09-06 11:04:52 -04:00
|
|
|
// No pq API doesn't help to validate connection string
|
|
|
|
// prior connection, so no validation for now.
|
2018-07-18 14:22:29 -04:00
|
|
|
} else {
|
|
|
|
// Some fields need to be specified when ConnectionString is unspecified
|
|
|
|
if p.Port == "" {
|
|
|
|
return fmt.Errorf("unspecified port")
|
|
|
|
}
|
|
|
|
if _, err := strconv.Atoi(p.Port); err != nil {
|
|
|
|
return fmt.Errorf("invalid port")
|
|
|
|
}
|
|
|
|
if p.Database == "" {
|
|
|
|
return fmt.Errorf("database unspecified")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-24 13:18:29 -04:00
|
|
|
if p.QueueDir != "" {
|
|
|
|
if !filepath.IsAbs(p.QueueDir) {
|
|
|
|
return errors.New("queueDir path should be absolute")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-25 01:20:30 -04:00
|
|
|
if p.MaxOpenConnections < 0 {
|
|
|
|
return errors.New("maxOpenConnections cannot be less than zero")
|
|
|
|
}
|
|
|
|
|
2018-07-18 14:22:29 -04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-03-15 16:03:41 -04:00
|
|
|
// PostgreSQLTarget - PostgreSQL target.
|
|
|
|
type PostgreSQLTarget struct {
|
2022-09-27 20:23:28 -04:00
|
|
|
lazyInit lazyInit
|
|
|
|
|
2018-03-15 16:03:41 -04:00
|
|
|
id event.TargetID
|
|
|
|
args PostgreSQLArgs
|
|
|
|
updateStmt *sql.Stmt
|
|
|
|
deleteStmt *sql.Stmt
|
|
|
|
insertStmt *sql.Stmt
|
|
|
|
db *sql.DB
|
2019-07-24 13:18:29 -04:00
|
|
|
store Store
|
|
|
|
firstPing bool
|
2020-04-14 14:19:25 -04:00
|
|
|
connString string
|
2022-07-27 12:44:59 -04:00
|
|
|
loggerOnce logger.LogOnce
|
2022-09-27 20:23:28 -04:00
|
|
|
quitCh chan struct{}
|
2018-03-15 16:03:41 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// ID - returns target ID.
|
|
|
|
func (target *PostgreSQLTarget) ID() event.TargetID {
|
|
|
|
return target.id
|
|
|
|
}
|
|
|
|
|
2022-11-08 19:36:47 -05:00
|
|
|
// Store returns any underlying store if set.
|
|
|
|
func (target *PostgreSQLTarget) Store() event.TargetStore {
|
|
|
|
return target.store
|
|
|
|
}
|
|
|
|
|
2019-12-11 17:27:03 -05:00
|
|
|
// IsActive - Return true if target is up and active
|
|
|
|
func (target *PostgreSQLTarget) IsActive() (bool, error) {
|
2022-09-27 20:23:28 -04:00
|
|
|
if err := target.init(); err != nil {
|
|
|
|
return false, err
|
2020-04-14 14:19:25 -04:00
|
|
|
}
|
2022-09-27 20:23:28 -04:00
|
|
|
return target.isActive()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (target *PostgreSQLTarget) isActive() (bool, error) {
|
2019-12-11 17:27:03 -05:00
|
|
|
if err := target.db.Ping(); err != nil {
|
|
|
|
if IsConnErr(err) {
|
|
|
|
return false, errNotConnected
|
|
|
|
}
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
2019-07-24 13:18:29 -04:00
|
|
|
// Save - saves the events to the store if questore is configured, which will be replayed when the PostgreSQL connection is active.
|
2019-04-10 08:46:01 -04:00
|
|
|
func (target *PostgreSQLTarget) Save(eventData event.Event) error {
|
2022-09-27 20:23:28 -04:00
|
|
|
if err := target.init(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-24 13:18:29 -04:00
|
|
|
if target.store != nil {
|
|
|
|
return target.store.Put(eventData)
|
|
|
|
}
|
2022-09-27 20:23:28 -04:00
|
|
|
_, err := target.isActive()
|
2019-12-11 17:27:03 -05:00
|
|
|
if err != nil {
|
2019-07-24 13:18:29 -04:00
|
|
|
return err
|
|
|
|
}
|
2019-04-10 08:46:01 -04:00
|
|
|
return target.send(eventData)
|
|
|
|
}
|
|
|
|
|
2019-07-24 13:18:29 -04:00
|
|
|
// IsConnErr - To detect a connection error.
|
|
|
|
func IsConnErr(err error) bool {
|
|
|
|
return IsConnRefusedErr(err) || err.Error() == "sql: database is closed" || err.Error() == "sql: statement is closed" || err.Error() == "invalid connection"
|
|
|
|
}
|
|
|
|
|
|
|
|
// send - sends an event to the PostgreSQL.
|
2019-04-10 08:46:01 -04:00
|
|
|
func (target *PostgreSQLTarget) send(eventData event.Event) error {
|
2018-03-15 16:03:41 -04:00
|
|
|
if target.args.Format == event.NamespaceFormat {
|
|
|
|
objectName, err := url.QueryUnescape(eventData.S3.Object.Key)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
key := eventData.S3.Bucket.Name + "/" + objectName
|
|
|
|
|
|
|
|
if eventData.EventName == event.ObjectRemovedDelete {
|
|
|
|
_, err = target.deleteStmt.Exec(key)
|
|
|
|
} else {
|
|
|
|
var data []byte
|
|
|
|
if data, err = json.Marshal(struct{ Records []event.Event }{[]event.Event{eventData}}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = target.updateStmt.Exec(key, data)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if target.args.Format == event.AccessFormat {
|
|
|
|
eventTime, err := time.Parse(event.AMZTimeFormat, eventData.EventTime)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
data, err := json.Marshal(struct{ Records []event.Event }{[]event.Event{eventData}})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-24 13:18:29 -04:00
|
|
|
if _, err = target.insertStmt.Exec(eventTime, data); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-03-15 16:03:41 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-07-24 13:18:29 -04:00
|
|
|
// Send - reads an event from store and sends it to PostgreSQL.
|
2019-04-10 08:46:01 -04:00
|
|
|
func (target *PostgreSQLTarget) Send(eventKey string) error {
|
2022-09-27 20:23:28 -04:00
|
|
|
if err := target.init(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err := target.isActive()
|
2019-12-11 17:27:03 -05:00
|
|
|
if err != nil {
|
2019-07-24 13:18:29 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !target.firstPing {
|
|
|
|
if err := target.executeStmts(); err != nil {
|
|
|
|
if IsConnErr(err) {
|
|
|
|
return errNotConnected
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
eventData, eErr := target.store.Get(eventKey)
|
|
|
|
if eErr != nil {
|
|
|
|
// The last event key in a successful batch will be sent in the channel atmost once by the replayEvents()
|
|
|
|
// Such events will not exist and wouldve been already been sent successfully.
|
|
|
|
if os.IsNotExist(eErr) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return eErr
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := target.send(eventData); err != nil {
|
|
|
|
if IsConnErr(err) {
|
|
|
|
return errNotConnected
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete the event from store.
|
|
|
|
return target.store.Del(eventKey)
|
2019-04-10 08:46:01 -04:00
|
|
|
}
|
|
|
|
|
2018-03-15 16:03:41 -04:00
|
|
|
// Close - closes underneath connections to PostgreSQL database.
|
|
|
|
func (target *PostgreSQLTarget) Close() error {
|
2022-09-27 20:23:28 -04:00
|
|
|
close(target.quitCh)
|
2018-03-15 16:03:41 -04:00
|
|
|
if target.updateStmt != nil {
|
|
|
|
// FIXME: log returned error. ignore time being.
|
|
|
|
_ = target.updateStmt.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
if target.deleteStmt != nil {
|
|
|
|
// FIXME: log returned error. ignore time being.
|
|
|
|
_ = target.deleteStmt.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
if target.insertStmt != nil {
|
|
|
|
// FIXME: log returned error. ignore time being.
|
|
|
|
_ = target.insertStmt.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
return target.db.Close()
|
|
|
|
}
|
|
|
|
|
2019-07-24 13:18:29 -04:00
|
|
|
// Executes the table creation statements.
|
|
|
|
func (target *PostgreSQLTarget) executeStmts() error {
|
|
|
|
_, err := target.db.Exec(fmt.Sprintf(psqlTableExists, target.args.Table))
|
|
|
|
if err != nil {
|
|
|
|
createStmt := psqlCreateNamespaceTable
|
|
|
|
if target.args.Format == event.AccessFormat {
|
|
|
|
createStmt = psqlCreateAccessTable
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, dbErr := target.db.Exec(fmt.Sprintf(createStmt, target.args.Table)); dbErr != nil {
|
|
|
|
return dbErr
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
switch target.args.Format {
|
|
|
|
case event.NamespaceFormat:
|
|
|
|
// insert or update statement
|
|
|
|
if target.updateStmt, err = target.db.Prepare(fmt.Sprintf(psqlUpdateRow, target.args.Table)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// delete statement
|
|
|
|
if target.deleteStmt, err = target.db.Prepare(fmt.Sprintf(psqlDeleteRow, target.args.Table)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
case event.AccessFormat:
|
|
|
|
// insert statement
|
|
|
|
if target.insertStmt, err = target.db.Prepare(fmt.Sprintf(psqlInsertRow, target.args.Table)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-09-27 20:23:28 -04:00
|
|
|
func (target *PostgreSQLTarget) init() error {
|
|
|
|
return target.lazyInit.Do(target.initPostgreSQL)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (target *PostgreSQLTarget) initPostgreSQL() error {
|
|
|
|
args := target.args
|
|
|
|
|
|
|
|
db, err := sql.Open("postgres", target.connString)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
target.db = db
|
|
|
|
|
|
|
|
if args.MaxOpenConnections > 0 {
|
|
|
|
// Set the maximum connections limit
|
|
|
|
target.db.SetMaxOpenConns(args.MaxOpenConnections)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = target.db.Ping()
|
|
|
|
if err != nil {
|
|
|
|
if !(IsConnRefusedErr(err) || IsConnResetErr(err)) {
|
|
|
|
target.loggerOnce(context.Background(), err, target.ID().String())
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if err = target.executeStmts(); err != nil {
|
|
|
|
target.loggerOnce(context.Background(), err, target.ID().String())
|
|
|
|
} else {
|
|
|
|
target.firstPing = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
target.db.Close()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
yes, err := target.isActive()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !yes {
|
|
|
|
return errNotConnected
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-03-15 16:03:41 -04:00
|
|
|
// NewPostgreSQLTarget - creates new PostgreSQL target.
|
2022-09-27 20:23:28 -04:00
|
|
|
func NewPostgreSQLTarget(id string, args PostgreSQLArgs, loggerOnce logger.LogOnce) (*PostgreSQLTarget, error) {
|
2018-03-15 16:03:41 -04:00
|
|
|
params := []string{args.ConnectionString}
|
2020-08-03 12:16:00 -04:00
|
|
|
if args.ConnectionString == "" {
|
|
|
|
params = []string{}
|
|
|
|
if !args.Host.IsEmpty() {
|
|
|
|
params = append(params, "host="+args.Host.String())
|
|
|
|
}
|
|
|
|
if args.Port != "" {
|
|
|
|
params = append(params, "port="+args.Port)
|
|
|
|
}
|
|
|
|
if args.Username != "" {
|
|
|
|
params = append(params, "username="+args.Username)
|
|
|
|
}
|
|
|
|
if args.Password != "" {
|
|
|
|
params = append(params, "password="+args.Password)
|
|
|
|
}
|
|
|
|
if args.Database != "" {
|
|
|
|
params = append(params, "dbname="+args.Database)
|
|
|
|
}
|
2018-03-15 16:03:41 -04:00
|
|
|
}
|
|
|
|
connStr := strings.Join(params, " ")
|
|
|
|
|
2019-07-24 13:18:29 -04:00
|
|
|
var store Store
|
|
|
|
if args.QueueDir != "" {
|
|
|
|
queueDir := filepath.Join(args.QueueDir, storePrefix+"-postgresql-"+id)
|
|
|
|
store = NewQueueStore(queueDir, args.QueueLimit)
|
2022-09-27 20:23:28 -04:00
|
|
|
if err := store.Open(); err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to initialize the queue store of PostgreSQL `%s`: %w", id, err)
|
2018-03-15 16:03:41 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-07 11:01:24 -05:00
|
|
|
target := &PostgreSQLTarget{
|
2022-09-27 20:23:28 -04:00
|
|
|
id: event.TargetID{ID: id, Name: "postgresql"},
|
|
|
|
args: args,
|
|
|
|
firstPing: false,
|
|
|
|
store: store,
|
|
|
|
connString: connStr,
|
|
|
|
loggerOnce: loggerOnce,
|
|
|
|
quitCh: make(chan struct{}),
|
2022-11-07 11:01:24 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if target.store != nil {
|
|
|
|
streamEventsFromStore(target.store, target, target.quitCh, target.loggerOnce)
|
|
|
|
}
|
|
|
|
|
|
|
|
return target, nil
|
2018-03-15 16:03:41 -04:00
|
|
|
}
|