Skip to content

Commit

Permalink
Merge pull request #101 from Carrotman42/master
Browse files Browse the repository at this point in the history
Add -verbose flag to allow users to turn off verbose output
  • Loading branch information
Carrotman42 authored Jun 16, 2017
2 parents 3aecf32 + 8bc0720 commit ba702eb
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 56 deletions.
22 changes: 14 additions & 8 deletions cmd/cloud_sql_proxy/cloud_sql_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"sync"
"time"

"github.com/GoogleCloudPlatform/cloudsql-proxy/logging"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/certs"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/fuse"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/proxy"
Expand All @@ -48,6 +49,7 @@ import (

var (
version = flag.Bool("version", false, "Print the version of the proxy and exit")
verbose = flag.Bool("verbose", true, "If false, verbose output such as information about when connections are created/closed without error are suppressed")
quiet = flag.Bool("quiet", false, "Disable log messages")

checkRegion = flag.Bool("check_region", false, `If specified, the 'region' portion of the connection string is required for
Expand Down Expand Up @@ -220,7 +222,7 @@ func authenticatedClient(ctx context.Context) (*http.Client, error) {
if err != nil {
return nil, fmt.Errorf("invalid json file %q: %v", f, err)
}
log.Printf("using credential file for authentication; email=%s", cfg.Email)
logging.Infof("using credential file for authentication; email=%s", cfg.Email)
return cfg.Client(ctx), nil
} else if tok := *token; tok != "" {
src := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: tok})
Expand Down Expand Up @@ -265,7 +267,7 @@ func listInstances(ctx context.Context, cl *http.Client, projects []string) ([]s
return nil
})
if err != nil {
log.Printf("Error listing instances in %v: %v", proj, err)
logging.Errorf("Error listing instances in %v: %v", proj, err)
}
wg.Done()
}()
Expand Down Expand Up @@ -294,7 +296,7 @@ func gcloudProject() []string {
// gcloud not installed; ignore the error
return nil
}
log.Printf("Error detecting gcloud project: %v", err)
logging.Errorf("Error detecting gcloud project: %v", err)
return nil
}

Expand All @@ -305,12 +307,12 @@ func gcloudProject() []string {
}

if err := json.Unmarshal(buf.Bytes(), &data); err != nil {
log.Printf("Failed to unmarshal bytes from gcloud: %v", err)
log.Printf(" gcloud returned:\n%s", buf)
logging.Errorf("Failed to unmarshal bytes from gcloud: %v", err)
logging.Errorf(" gcloud returned:\n%s", buf)
return nil
}

log.Printf("Using gcloud's active project: %v", data.Core.Project)
logging.Infof("Using gcloud's active project: %v", data.Core.Project)
return []string{data.Core.Project}
}

Expand Down Expand Up @@ -339,6 +341,10 @@ func main() {
return
}

if !*verbose {
logging.Verbosef = func(string, ...interface{}) {}
}

if *quiet {
log.Println("Cloud SQL Proxy logging has been disabled by the -quiet flag. All messages (including errors) will be suppressed.")
log.SetFlags(0)
Expand Down Expand Up @@ -398,7 +404,7 @@ func main() {
return nil
})
if err != nil {
log.Print(err)
logging.Errorf("Error on receiving new instances from metadata: %v", err)
}
time.Sleep(5 * time.Second)
}
Expand All @@ -412,7 +418,7 @@ func main() {
connSrc = c
}

log.Print("Ready for new connections")
logging.Infof("Ready for new connections")

(&proxy.Client{
Port: port,
Expand Down
22 changes: 11 additions & 11 deletions cmd/cloud_sql_proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@ import (
"bytes"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"

"github.com/GoogleCloudPlatform/cloudsql-proxy/logging"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/fuse"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/proxy"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/util"
Expand Down Expand Up @@ -64,7 +64,7 @@ func watchInstancesLoop(dir string, dst chan<- proxy.Conn, updates <-chan string
for instances := range updates {
list, err := parseInstanceConfigs(dir, strings.Split(instances, ","), cl)
if err != nil {
log.Print(err)
logging.Errorf("%v", err)
}

stillOpen := make(map[string]net.Listener)
Expand All @@ -85,7 +85,7 @@ func watchInstancesLoop(dir string, dst chan<- proxy.Conn, updates <-chan string

l, err := listenInstance(dst, cfg)
if err != nil {
log.Printf("Couldn't open socket for %q: %v", instance, err)
logging.Errorf("Couldn't open socket for %q: %v", instance, err)
continue
}
stillOpen[instance] = l
Expand All @@ -95,7 +95,7 @@ func watchInstancesLoop(dir string, dst chan<- proxy.Conn, updates <-chan string
// update. Clean up those instances' sockets by closing them; note that
// this does not affect any existing connections instance.
for instance, listener := range dynamicInstances {
log.Printf("Closing socket for instance %v", instance)
logging.Infof("Closing socket for instance %v", instance)
listener.Close()
}

Expand All @@ -104,19 +104,19 @@ func watchInstancesLoop(dir string, dst chan<- proxy.Conn, updates <-chan string

for _, v := range static {
if err := v.Close(); err != nil {
log.Printf("Error closing %q: %v", v.Addr(), err)
logging.Errorf("Error closing %q: %v", v.Addr(), err)
}
}
for _, v := range dynamicInstances {
if err := v.Close(); err != nil {
log.Printf("Error closing %q: %v", v.Addr(), err)
logging.Errorf("Error closing %q: %v", v.Addr(), err)
}
}
}

func remove(path string) {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
log.Printf("Remove(%q) error: %v", path, err)
logging.Infof("Remove(%q) error: %v", path, err)
}
}

Expand All @@ -133,24 +133,24 @@ func listenInstance(dst chan<- proxy.Conn, cfg instanceConfig) (net.Listener, er
}
if unix {
if err := os.Chmod(cfg.Address, 0777|os.ModeSocket); err != nil {
log.Printf("couldn't update permissions for socket file %q: %v; other users may not be unable to connect", cfg.Address, err)
logging.Errorf("couldn't update permissions for socket file %q: %v; other users may not be unable to connect", cfg.Address, err)
}
}

go func() {
for {
c, err := l.Accept()
if err != nil {
log.Printf("Error in accept for %q on %v: %v", cfg, cfg.Address, err)
logging.Errorf("Error in accept for %q on %v: %v", cfg, cfg.Address, err)
l.Close()
return
}
log.Printf("New connection for %q", cfg.Instance)
logging.Verbosef("New connection for %q", cfg.Instance)
dst <- proxy.Conn{cfg.Instance, c}
}
}()

log.Printf("Listening on %s for %s", cfg.Address, cfg.Instance)
logging.Infof("Listening on %s for %s", cfg.Address, cfg.Instance)
return l, nil
}

Expand Down
31 changes: 31 additions & 0 deletions logging/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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 logging contains helpers to support log messages. If you are using
// the Cloud SQL Proxy as a Go library, you can override these variables to
// control where log messages end up.
package logging

import "log"

// Verbosef is called to write verbose logs, such as when a new connection is
// established correctly.
var Verbosef = log.Printf

// Infof is called to write informational logs, such as when startup has
// completed.
var Infof = log.Printf

// Errorf is called to write an error log, such as when a new connection fails.
var Errorf = log.Printf
8 changes: 4 additions & 4 deletions proxy/certs/certs.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ import (
"encoding/pem"
"errors"
"fmt"
"log"
"math"
mrand "math/rand"
"net/http"
"time"

"github.com/GoogleCloudPlatform/cloudsql-proxy/logging"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/util"
"google.golang.org/api/googleapi"
sqladmin "google.golang.org/api/sqladmin/v1beta4"
Expand Down Expand Up @@ -96,7 +96,7 @@ func backoffAPIRetry(desc, instance string, do func() error) error {
// sleep = baseBackoff * backoffMult^(retries + randomFactor)
exp := float64(i+1) + mrand.Float64()
sleep := time.Duration(baseBackoff * math.Pow(backoffMult, exp))
log.Printf("Error in %s %s: %v; retrying in %v", desc, instance, err, sleep)
logging.Errorf("Error in %s %s: %v; retrying in %v", desc, instance, err, sleep)
time.Sleep(sleep)
}
return err
Expand Down Expand Up @@ -172,8 +172,8 @@ func (s *RemoteCertSource) Remote(instance string) (cert *x509.Certificate, addr
if s.checkRegion {
return nil, "", "", err
}
log.Print(err)
log.Print("WARNING: specifying the correct region in an instance string will become required in a future version!")
logging.Errorf("%v", err)
logging.Errorf("WARNING: specifying the correct region in an instance string will become required in a future version!")
}
if len(data.IpAddresses) == 0 || data.IpAddresses[0].IpAddress == "" {
return nil, "", "", fmt.Errorf("no IP address found for %v", instance)
Expand Down
34 changes: 17 additions & 17 deletions proxy/fuse/fuse.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ import (
"errors"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"sync"

"bazil.org/fuse"
"bazil.org/fuse/fs"
"github.com/GoogleCloudPlatform/cloudsql-proxy/logging"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/proxy"
"golang.org/x/net/context"
)
Expand All @@ -71,12 +71,12 @@ func NewConnSrc(mountdir, tmpdir string, connset *proxy.ConnSet) (<-chan proxy.C
if err := fuse.Unmount(mountdir); err != nil {
// The error is too verbose to be useful to print out
}
log.Printf("Mounting %v...", mountdir)
logging.Verbosef("Mounting %v...", mountdir)
c, err := fuse.Mount(mountdir, fuse.AllowOther())
if err != nil {
return nil, nil, fmt.Errorf("cannot mount %q: %v", mountdir, err)
}
log.Printf("Mounted %v", mountdir)
logging.Infof("Mounted %v", mountdir)

if connset == nil {
// Make a dummy one.
Expand All @@ -95,23 +95,23 @@ func NewConnSrc(mountdir, tmpdir string, connset *proxy.ConnSet) (<-chan proxy.C
server := fs.New(c, &fs.Config{
Debug: func(msg interface{}) {
if false {
log.Print(msg)
logging.Verbosef("%s", msg)
}
},
})

go func() {
if err := server.Serve(root); err != nil {
log.Printf("serve %q exited due to error: %v", mountdir, err)
logging.Errorf("serve %q exited due to error: %v", mountdir, err)
}
// The server exited but we don't know whether this is because of a
// graceful reason (via root.Close) or via an external force unmounting.
// Closing the root will ensure the 'dst' chan is closed correctly to
// signify that no new connections are possible.
if err := root.Close(); err != nil {
log.Printf("root.Close() error: %v", err)
logging.Errorf("root.Close() error: %v", err)
}
log.Printf("FUSE exited")
logging.Infof("FUSE exited")
}()

return conns, root, nil
Expand Down Expand Up @@ -168,17 +168,17 @@ func (r *fsRoot) newConn(instance string, c net.Conn) {
if ch := r.dst; ch != nil {
ch <- proxy.Conn{instance, c}
} else {
log.Printf("Ignored new conn request to %q: system has been closed", instance)
logging.Errorf("Ignored new conn request to %q: system has been closed", instance)
}
r.RUnlock()
}

func (r *fsRoot) Forget() {
log.Printf("Forget called on %q", r.linkDir)
logging.Verbosef("Forget called on %q", r.linkDir)
}

func (r *fsRoot) Destroy() {
log.Printf("Destroy called on %q", r.linkDir)
logging.Verbosef("Destroy called on %q", r.linkDir)
}

func (r *fsRoot) Close() error {
Expand All @@ -193,7 +193,7 @@ func (r *fsRoot) Close() error {
}
r.Unlock()

log.Printf("unmount %q", r.linkDir)
logging.Infof("unmount %q", r.linkDir)
if err := fuse.Unmount(r.linkDir); err != nil {
return err
}
Expand All @@ -210,7 +210,7 @@ func (r *fsRoot) Close() error {
if errs.Len() == 0 {
return nil
}
log.Printf("Close %q: %v", r.linkDir, errs.String())
logging.Errorf("Close %q: %v", r.linkDir, errs.String())
return errors.New(errs.String())
}

Expand Down Expand Up @@ -247,11 +247,11 @@ func (r *fsRoot) Lookup(_ context.Context, req *fuse.LookupRequest, resp *fuse.L
os.Remove(path) // Best effort; the following will fail if this does.
sock, err := net.Listen("unix", path)
if err != nil {
log.Printf("couldn't listen at %q: %v", path, err)
logging.Errorf("couldn't listen at %q: %v", path, err)
return nil, fuse.EEXIST
}
if err := os.Chmod(path, 0777|os.ModeSocket); err != nil {
log.Printf("couldn't update permissions for socket file %q: %v; other users may be unable to connect", path, err)
logging.Errorf("couldn't update permissions for socket file %q: %v; other users may be unable to connect", path, err)
}

go r.listenerLifecycle(sock, instance, path)
Expand All @@ -272,7 +272,7 @@ func (r *fsRoot) removeListener(instance, path string) {
if ok && string(v) == path {
delete(r.links, instance)
} else {
log.Printf("Removing a listener for %q at %q which was already replaced", instance, path)
logging.Errorf("Removing a listener for %q at %q which was already replaced", instance, path)
}
r.sockLock.Unlock()
}
Expand All @@ -283,15 +283,15 @@ func (r *fsRoot) listenerLifecycle(l net.Listener, instance, path string) {
for {
c, err := l.Accept()
if err != nil {
log.Printf("error in Accept for %q: %v", instance, err)
logging.Errorf("error in Accept for %q: %v", instance, err)
break
}
r.newConn(instance, c)
}
r.removeListener(instance, path)
l.Close()
if err := os.Remove(path); err != nil {
log.Printf("couldn't remove %q: %v", path, err)
logging.Errorf("couldn't remove %q: %v", path, err)
}
}

Expand Down
Loading

0 comments on commit ba702eb

Please sign in to comment.