2016-01-19 20:16:45 +00:00
|
|
|
// Copyright 2015 clair authors
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
// Package pgsql implements database.Datastore with PostgreSQL.
|
2015-12-28 20:03:29 +00:00
|
|
|
package pgsql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
2016-02-02 18:40:41 +00:00
|
|
|
"os"
|
2015-12-28 20:03:29 +00:00
|
|
|
"path"
|
|
|
|
"runtime"
|
|
|
|
"strings"
|
2016-01-24 03:02:34 +00:00
|
|
|
"time"
|
2015-12-28 20:03:29 +00:00
|
|
|
|
|
|
|
"bitbucket.org/liamstask/goose/lib/goose"
|
|
|
|
"github.com/coreos/clair/config"
|
|
|
|
"github.com/coreos/clair/database"
|
2016-01-24 03:02:34 +00:00
|
|
|
"github.com/coreos/clair/utils"
|
2016-01-08 16:17:32 +00:00
|
|
|
cerrors "github.com/coreos/clair/utils/errors"
|
2015-12-28 20:03:29 +00:00
|
|
|
"github.com/coreos/pkg/capnslog"
|
|
|
|
"github.com/hashicorp/golang-lru"
|
|
|
|
"github.com/lib/pq"
|
|
|
|
"github.com/pborman/uuid"
|
2016-01-22 20:59:46 +00:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2015-12-28 20:03:29 +00:00
|
|
|
)
|
|
|
|
|
2016-01-22 20:59:46 +00:00
|
|
|
var (
|
|
|
|
log = capnslog.NewPackageLogger("github.com/coreos/clair", "pgsql")
|
|
|
|
|
|
|
|
promErrorsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
|
|
|
|
Name: "clair_pgsql_errors_total",
|
2016-01-24 03:02:34 +00:00
|
|
|
Help: "Number of errors that PostgreSQL requests generated.",
|
2016-01-22 20:59:46 +00:00
|
|
|
}, []string{"request"})
|
|
|
|
|
|
|
|
promCacheHitsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
|
|
|
|
Name: "clair_pgsql_cache_hits_total",
|
2016-01-24 03:02:34 +00:00
|
|
|
Help: "Number of cache hits that the PostgreSQL backend did.",
|
2016-01-22 20:59:46 +00:00
|
|
|
}, []string{"object"})
|
|
|
|
|
|
|
|
promCacheQueriesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
|
|
|
|
Name: "clair_pgsql_cache_queries_total",
|
2016-01-24 03:02:34 +00:00
|
|
|
Help: "Number of cache queries that the PostgreSQL backend did.",
|
2016-01-22 20:59:46 +00:00
|
|
|
}, []string{"object"})
|
2016-01-24 03:02:34 +00:00
|
|
|
|
|
|
|
promQueryDurationMilliseconds = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
|
|
|
Name: "clair_pgsql_query_duration_milliseconds",
|
|
|
|
Help: "Time it takes to execute the database query.",
|
|
|
|
}, []string{"query", "subquery"})
|
|
|
|
|
|
|
|
promConcurrentLockVAFV = prometheus.NewGauge(prometheus.GaugeOpts{
|
|
|
|
Name: "clair_pgsql_concurrent_lock_vafv_total",
|
|
|
|
Help: "Number of transactions trying to hold the exclusive Vulnerability_Affects_FeatureVersion lock.",
|
|
|
|
})
|
2016-01-22 20:59:46 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2016-01-24 03:02:34 +00:00
|
|
|
prometheus.MustRegister(promErrorsTotal)
|
2016-01-22 20:59:46 +00:00
|
|
|
prometheus.MustRegister(promCacheHitsTotal)
|
|
|
|
prometheus.MustRegister(promCacheQueriesTotal)
|
2016-01-24 03:02:34 +00:00
|
|
|
prometheus.MustRegister(promQueryDurationMilliseconds)
|
|
|
|
prometheus.MustRegister(promConcurrentLockVAFV)
|
2016-01-22 20:59:46 +00:00
|
|
|
}
|
2015-12-28 20:03:29 +00:00
|
|
|
|
2016-02-02 18:29:59 +00:00
|
|
|
type Queryer interface {
|
|
|
|
Query(query string, args ...interface{}) (*sql.Rows, error)
|
|
|
|
QueryRow(query string, args ...interface{}) *sql.Row
|
|
|
|
}
|
|
|
|
|
2015-12-28 20:03:29 +00:00
|
|
|
type pgSQL struct {
|
|
|
|
*sql.DB
|
|
|
|
cache *lru.ARCCache
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pgSQL *pgSQL) Close() {
|
|
|
|
pgSQL.DB.Close()
|
|
|
|
}
|
|
|
|
|
2016-01-22 20:57:57 +00:00
|
|
|
func (pgSQL *pgSQL) Ping() bool {
|
2016-02-04 21:13:11 +00:00
|
|
|
return pgSQL.DB.Ping() == nil
|
2016-01-22 20:57:57 +00:00
|
|
|
}
|
|
|
|
|
2015-12-28 20:03:29 +00:00
|
|
|
// Open creates a Datastore backed by a PostgreSQL database.
|
|
|
|
//
|
|
|
|
// It will run immediately every necessary migration on the database.
|
|
|
|
func Open(config *config.DatabaseConfig) (database.Datastore, error) {
|
|
|
|
// Run migrations.
|
2016-01-08 16:17:32 +00:00
|
|
|
if err := migrate(config.Source); err != nil {
|
|
|
|
log.Error(err)
|
|
|
|
return nil, database.ErrCantOpen
|
2015-12-28 20:03:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Open database.
|
|
|
|
db, err := sql.Open("postgres", config.Source)
|
|
|
|
if err != nil {
|
2016-01-08 16:17:32 +00:00
|
|
|
log.Error(err)
|
|
|
|
return nil, database.ErrCantOpen
|
2015-12-28 20:03:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Initialize cache.
|
|
|
|
// TODO(Quentin-M): Benchmark with a simple LRU Cache.
|
|
|
|
var cache *lru.ARCCache
|
|
|
|
if config.CacheSize > 0 {
|
|
|
|
cache, _ = lru.NewARC(config.CacheSize)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &pgSQL{DB: db, cache: cache}, nil
|
|
|
|
}
|
|
|
|
|
2016-01-08 16:17:32 +00:00
|
|
|
// migrate runs all available migrations on a pgSQL database.
|
|
|
|
func migrate(dataSource string) error {
|
2015-12-28 20:03:29 +00:00
|
|
|
log.Info("running database migrations")
|
|
|
|
|
|
|
|
_, filename, _, _ := runtime.Caller(1)
|
|
|
|
migrationDir := path.Join(path.Dir(filename), "/migrations/")
|
|
|
|
conf := &goose.DBConf{
|
|
|
|
MigrationsDir: migrationDir,
|
|
|
|
Driver: goose.DBDriver{
|
|
|
|
Name: "postgres",
|
|
|
|
OpenStr: dataSource,
|
|
|
|
Import: "github.com/lib/pq",
|
|
|
|
Dialect: &goose.PostgresDialect{},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
// Determine the most recent revision available from the migrations folder.
|
|
|
|
target, err := goose.GetMostRecentDBVersion(conf.MigrationsDir)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run migrations
|
|
|
|
err = goose.RunMigrations(conf, conf.MigrationsDir, target)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Info("database migration ran successfully")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-01-08 16:17:32 +00:00
|
|
|
// createDatabase creates a new database.
|
2015-12-28 20:03:29 +00:00
|
|
|
// The dataSource parameter should not contain a dbname.
|
2016-01-08 16:17:32 +00:00
|
|
|
func createDatabase(dataSource, databaseName string) error {
|
2015-12-28 20:03:29 +00:00
|
|
|
// Open database.
|
|
|
|
db, err := sql.Open("postgres", dataSource)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not open database (CreateDatabase): %v", err)
|
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
|
|
|
|
// Create database.
|
2016-01-20 00:17:08 +00:00
|
|
|
_, err = db.Exec("CREATE DATABASE " + databaseName)
|
2015-12-28 20:03:29 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not create database: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-01-08 16:17:32 +00:00
|
|
|
// dropDatabase drops an existing database.
|
2015-12-28 20:03:29 +00:00
|
|
|
// The dataSource parameter should not contain a dbname.
|
2016-01-08 16:17:32 +00:00
|
|
|
func dropDatabase(dataSource, databaseName string) error {
|
2015-12-28 20:03:29 +00:00
|
|
|
// Open database.
|
|
|
|
db, err := sql.Open("postgres", dataSource)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not open database (DropDatabase): %v", err)
|
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
|
2016-02-02 18:40:41 +00:00
|
|
|
// Kill any opened connection.
|
|
|
|
if _, err := db.Exec(`
|
|
|
|
SELECT pg_terminate_backend(pg_stat_activity.pid)
|
|
|
|
FROM pg_stat_activity
|
|
|
|
WHERE pg_stat_activity.datname = $1
|
|
|
|
AND pid <> pg_backend_pid()`, databaseName); err != nil {
|
|
|
|
return fmt.Errorf("could not drop database: %v", err)
|
|
|
|
}
|
|
|
|
|
2015-12-28 20:03:29 +00:00
|
|
|
// Drop database.
|
2016-02-02 18:40:41 +00:00
|
|
|
if _, err = db.Exec("DROP DATABASE " + databaseName); err != nil {
|
2016-01-12 15:40:46 +00:00
|
|
|
return fmt.Errorf("could not drop database: %v", err)
|
2015-12-28 20:03:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// pgSQLTest wraps pgSQL for testing purposes.
|
|
|
|
// Its Close() method drops the database.
|
|
|
|
type pgSQLTest struct {
|
|
|
|
*pgSQL
|
2016-02-02 18:40:41 +00:00
|
|
|
dataSourceDefaultDatabase string
|
|
|
|
dbName string
|
2015-12-28 20:03:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// OpenForTest creates a test Datastore backed by a new PostgreSQL database.
|
|
|
|
// It creates a new unique and prefixed ("test_") database.
|
|
|
|
// Using Close() will drop the database.
|
|
|
|
func OpenForTest(name string, withTestData bool) (*pgSQLTest, error) {
|
2016-02-02 18:40:41 +00:00
|
|
|
// Define the PostgreSQL connection strings.
|
|
|
|
dataSource := "host=127.0.0.1 sslmode=disable user=postgres dbname="
|
|
|
|
if dataSourceEnv := os.Getenv("CLAIR_TEST_PGSQL"); dataSourceEnv != "" {
|
|
|
|
dataSource = dataSourceEnv + " dbname="
|
|
|
|
}
|
2015-12-28 20:03:29 +00:00
|
|
|
dbName := "test_" + strings.ToLower(name) + "_" + strings.Replace(uuid.New(), "-", "_", -1)
|
2016-02-02 18:40:41 +00:00
|
|
|
dataSourceDefaultDatabase := dataSource + "postgres"
|
|
|
|
dataSourceTestDatabase := dataSource + dbName
|
2015-12-28 20:03:29 +00:00
|
|
|
|
|
|
|
// Create database.
|
2016-02-02 18:40:41 +00:00
|
|
|
if err := createDatabase(dataSourceDefaultDatabase, dbName); err != nil {
|
2016-01-08 16:17:32 +00:00
|
|
|
log.Error(err)
|
|
|
|
return nil, database.ErrCantOpen
|
2015-12-28 20:03:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Open database.
|
2016-02-02 18:40:41 +00:00
|
|
|
db, err := Open(&config.DatabaseConfig{Source: dataSourceTestDatabase, CacheSize: 0})
|
2015-12-28 20:03:29 +00:00
|
|
|
if err != nil {
|
2016-02-02 18:40:41 +00:00
|
|
|
dropDatabase(dataSourceDefaultDatabase, dbName)
|
2016-01-08 16:17:32 +00:00
|
|
|
log.Error(err)
|
|
|
|
return nil, database.ErrCantOpen
|
2015-12-28 20:03:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Load test data if specified.
|
|
|
|
if withTestData {
|
|
|
|
_, filename, _, _ := runtime.Caller(0)
|
|
|
|
d, _ := ioutil.ReadFile(path.Join(path.Dir(filename)) + "/testdata/data.sql")
|
|
|
|
_, err = db.(*pgSQL).Exec(string(d))
|
|
|
|
if err != nil {
|
2016-02-02 18:40:41 +00:00
|
|
|
dropDatabase(dataSourceDefaultDatabase, dbName)
|
2016-01-08 16:17:32 +00:00
|
|
|
log.Error(err)
|
|
|
|
return nil, database.ErrCantOpen
|
2015-12-28 20:03:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-02 18:40:41 +00:00
|
|
|
return &pgSQLTest{
|
|
|
|
pgSQL: db.(*pgSQL),
|
|
|
|
dataSourceDefaultDatabase: dataSourceDefaultDatabase,
|
|
|
|
dbName: dbName}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pgSQL *pgSQLTest) Close() {
|
|
|
|
pgSQL.DB.Close()
|
|
|
|
dropDatabase(pgSQL.dataSourceDefaultDatabase, pgSQL.dbName)
|
2015-12-28 20:03:29 +00:00
|
|
|
}
|
|
|
|
|
2016-01-08 16:17:32 +00:00
|
|
|
// handleError logs an error with an extra description and masks the error if it's an SQL one.
|
|
|
|
// This ensures we never return plain SQL errors and leak anything.
|
|
|
|
func handleError(desc string, err error) error {
|
2016-01-26 22:57:32 +00:00
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-01-22 20:59:46 +00:00
|
|
|
if err == sql.ErrNoRows {
|
2016-01-08 16:17:32 +00:00
|
|
|
return cerrors.ErrNotFound
|
|
|
|
}
|
|
|
|
|
2016-01-21 23:09:38 +00:00
|
|
|
log.Errorf("%s: %v", desc, err)
|
2016-01-22 20:59:46 +00:00
|
|
|
promErrorsTotal.WithLabelValues(desc).Inc()
|
|
|
|
|
|
|
|
if _, o := err.(*pq.Error); o || err == sql.ErrTxDone || strings.HasPrefix(err.Error(), "sql:") {
|
|
|
|
return database.ErrBackendException
|
|
|
|
}
|
|
|
|
|
2016-01-08 16:17:32 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-12-28 20:03:29 +00:00
|
|
|
// isErrUniqueViolation determines is the given error is a unique contraint violation.
|
|
|
|
func isErrUniqueViolation(err error) bool {
|
|
|
|
pqErr, ok := err.(*pq.Error)
|
|
|
|
return ok && pqErr.Code == "23505"
|
|
|
|
}
|
2016-01-24 03:02:34 +00:00
|
|
|
|
|
|
|
func observeQueryTime(query, subquery string, start time.Time) {
|
|
|
|
utils.PrometheusObserveTimeMilliseconds(promQueryDurationMilliseconds.WithLabelValues(query, subquery), start)
|
|
|
|
}
|