Git Product home page Git Product logo

cloud-sql-go-connector's Introduction

cloud-sql-go-connector

Warning: This project is in Public Preview, and may contain breaking changes before it becomes Generally Available.

CI Go Reference

The Cloud SQL Go Connector is a Cloud SQL connector designed for use with the Go language. Using a Cloud SQL connector provides the following benefits:

  • IAM Authorization: uses IAM permissions to control who/what can connect to your Cloud SQL instances
  • Improved Security: uses robust, updated TLS 1.3 encryption and identity verification between the client connector and the server-side proxy, independent of the database protocol.
  • Convenience: removes the requirement to use and distribute SSL certificates, as well as manage firewalls or source/destination IP addresses.
  • (optionally) IAM DB Authenticiation: provides support for Cloud SQL’s automatic IAM DB AuthN feature.

Installation

You can install this repo with go get:

go get cloud.google.com/go/cloudsqlconn

Usage

This package provides several functions for authorizing and encrypting connections. These functions can be used with your database driver to connect to your Cloud SQL instance.

The instance connection name for your Cloud SQL instance is always in the format "project:region:instance".

APIs and Services

This package requires the following to successfully make Cloud SQL Connections:

  • IAM principal (user, service account, etc.) with the Cloud SQL Client role or equivalent. This IAM principal will be used for credentials.
  • The Cloud SQL Admin API to be enabled within your Google Cloud Project. By default, the API will be called in the project associated with the IAM principal.

Credentials

This repo uses the Application Default Credentials (ADC) strategy for resolving credentials. Please see the golang.org/x/oauth2/google documentation for more information in how these credentials are sourced.

To explicitly set a specific source for the Credentials to use, see Using Options below.

Postgres

To use the dialer with pgx, use pgxpool by configuring a Config.DialFunc like so:

// Configure the driver to connect to the database
dsn := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", pgUser, pgPass, pgDB)
config, err := pgxpool.ParseConfig(dsn)
if err != nil {
    log.Fatalf("failed to parse pgx config: %v", err)
}

// Create a new dialer with any options
d, err := cloudsqlconn.NewDialer(ctx)
if err != nil {
    log.Fatalf("failed to initialize dialer: %v", err)
}
defer d.Close()

// Tell the driver to use the Cloud SQL Go Connector to create connections
config.ConnConfig.DialFunc = func(ctx context.Context, _ string, instance string) (net.Conn, error) {
    return d.Dial(ctx, "project:region:instance")
}

// Interact with the dirver directly as you normally would
conn, err := pgxpool.ConnectConfig(context.Background(), config)
if err != nil {
    log.Fatalf("failed to connect: %v", connErr)
}
defer conn.Close()

MySQL

The Go MySQL driver does not provide a stand-alone interface for interacting with a database and instead uses database/sql. See the section below on how to use the database/sql package with a Cloud SQL MySQL instance.

SQL Server

Go-mssql does not provide a stand-alone interface for interacting with a database and instead uses database/sql. See the section below on how to use the database/sql package with a Cloud SQL SQL Server instance.

Using Options

If you need to customize something about the Dialer, you can initialize directly with NewDialer:

myDialer, err := cloudsqlconn.NewDialer(
    ctx,
    cloudsqlconn.WithCredentialsFile("key.json"),
)
if err != nil {
    log.Fatalf("unable to initialize dialer: %s", err)
}

conn, err := myDialer.Dial(ctx, "project:region:instance")

For a full list of customizable behavior, see Option.

Using DialOptions

If you want to customize things about how the connection is created, use Option:

conn, err := myDialer.Dial(
    ctx,
    "project:region:instance",
    cloudsqlconn.WithPrivateIP(),
)

You can also use the WithDefaultDialOptions Option to specify DialOptions to be used by default:

myDialer, err := cloudsqlconn.NewDialer(
    ctx,
    cloudsqlconn.WithDefaultDialOptions(
        cloudsqlconn.WithPrivateIP(),
    ),
)

Using the dialer with database/sql

Using the dialer directly will expose more configuration options. However, it is possible to use the dialer with the database/sql package.

Postgres

To use database/sql, use pgxv4.RegisterDriver with any necessary Dialer configuration. Note: the connection string must use the keyword/value format with host set to the instance connection name.

package foo

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/postgres/pgxv4"
)

func Connect() {
    cleanup, err := pgxv4.RegisterDriver("cloudsql-postgres", cloudsqlconn.WithIAMAuthN())
    if err != nil {
        // ... handle error
    }
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-postgres",
        "host=project:region:instance user=myuser password=mypass dbname=mydb sslmode=disable",
	)
    // ... etc
}

MySQL

To use database/sql, use mysql.RegisterDriver with any necessary Dialer configuration.

package foo

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/mysql/mysql"
)

func Connect() {
    cleanup, err := mysql.RegisterDriver("cloudsql-mysql", cloudsqlconn.WithCredentialsFile("key.json"))
    if err != nil {
        // ... handle error
    }
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-mysql",
        "myuser:mypass@cloudsql-mysql(my-project:us-central1:my-instance)/mydb",
	)
    // ... etc
}

SQL Server

To use database/sql, use sqlserver.RegisterDriver with any necessary Dialer configuration.

package foo

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/sqlserver"
)

func Connect() {
    cleanup, err := sqlserver.RegisterDriver("cloudsql-sqlserver", cloudsqlconn.WithCredentialsFile("key.json"))
    if err != nil {
        // ... handle error
    }
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-sqlserver",
        "sqlserver://user:password@localhost?database=mydb&cloudsql=my-proj:us-central1:my-inst",
    )
    // ... etc
}

Enabling Metrics and Tracing

This library includes support for metrics and tracing using OpenCensus. To enable metrics or tracing, you need to configure an exporter. OpenCensus supports many backends for exporters.

For example, to use Cloud Monitoring and Cloud Trace, you would configure an exporter like so:

package main

import (
    "contrib.go.opencensus.io/exporter/stackdriver"
    "go.opencensus.io/trace"
)

func main() {
    sd, err := stackdriver.NewExporter(stackdriver.Options{
        ProjectID: "mycoolproject",
    })
    if err != nil {
        // handle error
    }
    defer sd.Flush()
    trace.RegisterExporter(sd)

    sd.StartMetricsExporter()
    defer sd.StopMetricsExporter()

    // Use cloudsqlconn as usual.
    // ...
}

Support policy

Major version lifecycle

This project uses semantic versioning, and uses the following lifecycle regarding support for a major version:

Active - Active versions get all new features and security fixes (that wouldn’t otherwise introduce a breaking change). New major versions are guaranteed to be "active" for a minimum of 1 year.

Deprecated - Deprecated versions continue to receive security and critical bug fixes, but do not receive new features. Deprecated versions will be supported for 1 year.

Unsupported - Any major version that has been deprecated for >=1 year is considered unsupported.

Supported Go Versions

We test and support at minimum, the latest three Go versions. Changes in supported Go versions will be considered a minor change, and will be listed in the realease notes.

Release cadence

This project aims for a release on at least a monthly basis. If no new features or fixes have been added, a new PATCH version with the latest dependencies is released.

cloud-sql-go-connector's People

Contributors

enocom avatar github-actions[bot] avatar jackwotherspoon avatar kurtisvg avatar renovate-bot avatar stepan-romankov avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.