This repository has been archived by the owner on Oct 23, 2024. It is now read-only.
forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
111 lines (99 loc) · 2.44 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package lxd
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"path"
"strings"
)
// Client can talk to a lxd daemon.
type Client struct {
config Config
Remote *RemoteConfig
http http.Client
baseURL string
}
// NewClient returns a new lxd client.
func NewClient(config *Config, raw string) (*Client, string, error) {
c := Client{
config: *config,
http: http.Client{
// Added on Go 1.3. Wait until it's more popular.
//Timeout: 10 * time.Second,
},
}
result := strings.SplitN(raw, ":", 2)
var remote string
var container string
if len(result) == 1 {
remote = config.DefaultRemote
container = result[0]
} else {
remote = result[0]
container = result[1]
}
// TODO: Here, we don't support configurable local remotes, we only
// support the default local lxd at /var/lib/lxd/unix.socket.
if remote == "" {
c.baseURL = "http://unix.socket"
c.http.Transport = &unixTransport
} else if r, ok := config.Remotes[remote]; ok {
c.baseURL = "http://" + r.Addr
c.Remote = &r
} else {
return nil, "", fmt.Errorf("unknown remote name: %q", config.DefaultRemote)
}
if err := c.Ping(); err != nil {
return nil, "", err
}
return &c, container, nil
}
func (c *Client) getstr(base string, args map[string]string) (string, error) {
vs := url.Values{}
for k, v := range args {
vs.Set(k, v)
}
data, err := c.get(base + "?" + vs.Encode())
if err != nil {
return "", err
}
return string(data), nil
}
func (c *Client) get(elem ...string) ([]byte, error) {
resp, err := c.http.Get(c.url(elem...))
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func (c *Client) url(elem ...string) string {
return c.baseURL + path.Join(elem...)
}
var unixTransport = http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
if addr != "unix.socket:80" {
return nil, fmt.Errorf("non-unix-socket addresses not supported yet")
}
raddr, err := net.ResolveUnixAddr("unix", VarPath("unix.socket"))
if err != nil {
return nil, fmt.Errorf("cannot resolve unix socket address: %v", err)
}
return net.DialUnix("unix", nil, raddr)
},
}
// Ping pings the daemon to see if it is up listening and working.
func (c *Client) Ping() error {
Debugf("pinging the daemon")
data, err := c.getstr("/ping", nil)
if err != nil {
return err
}
if data != Version {
return fmt.Errorf("version mismatch: mine: %q, daemon: %q", Version, data)
}
Debugf("pong received")
return nil
}