~fwereade/juju-core/unit-remove-depart-scopes

« back to all changes in this revision

Viewing changes to provider/local/environprovider.go

  • Committer: William Reade
  • Date: 2013-11-07 17:30:38 UTC
  • mfrom: (2032.1.6 juju-core)
  • Revision ID: fwereade@gmail.com-20131107173038-d0a72q96dujotc0z
merge parent

Show diffs side-by-side

added added

removed removed

Lines of Context:
5
5
 
6
6
import (
7
7
        "fmt"
 
8
        "net"
 
9
        "syscall"
8
10
 
9
11
        "launchpad.net/loggo"
10
12
 
53
55
 
54
56
// Prepare implements environs.EnvironProvider.Prepare.
55
57
func (p environProvider) Prepare(cfg *config.Config) (environs.Environ, error) {
56
 
        // TODO prepare environment
 
58
        err := checkLocalPort(cfg.StatePort(), "state port")
 
59
        if err != nil {
 
60
                return nil, err
 
61
        }
 
62
        err = checkLocalPort(cfg.APIPort(), "API port")
 
63
        if err != nil {
 
64
                return nil, err
 
65
        }
57
66
        return p.Open(cfg)
58
67
}
59
68
 
 
69
// checkLocalPort checks that the passed port is not used so far.
 
70
func checkLocalPort(port int, description string) error {
 
71
        logger.Infof("checking %s", description)
 
72
        // Try to connect the port on localhost.
 
73
        address := fmt.Sprintf("localhost:%d", port)
 
74
        // TODO(mue) Add a timeout?
 
75
        conn, err := net.Dial("tcp", address)
 
76
        if err != nil {
 
77
                if nerr, ok := err.(*net.OpError); ok {
 
78
                        if nerr.Err == syscall.ECONNREFUSED {
 
79
                                // No connection, so everything is fine.
 
80
                                return nil
 
81
                        }
 
82
                }
 
83
                return err
 
84
        }
 
85
        // Connected, so port is in use.
 
86
        err = conn.Close()
 
87
        if err != nil {
 
88
                return err
 
89
        }
 
90
        return fmt.Errorf("cannot use %d as %s, already in use", port, description)
 
91
}
 
92
 
60
93
// Validate implements environs.EnvironProvider.Validate.
61
94
func (provider environProvider) Validate(cfg, old *config.Config) (valid *config.Config, err error) {
62
95
        // Check for valid changes for the base config values.