~themue/juju-core/021-deployer-lxc-context

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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package rpc

import (
	"errors"
	"fmt"
	"io"
	"launchpad.net/juju-core/log"
	"sync"
)

var ErrShutdown = errors.New("connection is shut down")

// A ClientCodec implements writing of RPC requests and reading of RPC
// responses for the client side of an RPC session.  The client calls
// WriteRequest to write a request to the connection and calls
// ReadResponseHeader and ReadResponseBody in pairs to read responses.
// The client calls Close when finished with the connection.
// The params argument to WriteRequest will always be of struct
// type; the result argument to ReadResponseBody will always be
// a non-nil pointer to a struct.
type ClientCodec interface {
	WriteRequest(req *Request, params interface{}) error
	ReadResponseHeader(resp *Response) error
	ReadResponseBody(result interface{}) error
	Close() error
}

// Client represents an RPC Client.  There may be multiple outstanding
// Calls associated with a single Client, and a Client may be used by
// multiple goroutines simultaneously.
type Client struct {
	sending sync.Mutex
	codec   ClientCodec
	request Request

	mutex    sync.Mutex // protects the following fields
	reqId    uint64
	pending  map[uint64]*Call
	closing  bool
	shutdown bool
}

// NewClient returns a new Client to handle requests to the set of
// services at the other end of the connection.  The given codec is used
// to encode requests and decode responses.
func NewClientWithCodec(codec ClientCodec) *Client {
	client := &Client{
		codec:   codec,
		pending: make(map[uint64]*Call),
	}
	go client.input()
	return client
}

// Call represents an active RPC.
type Call struct {
	Type     string
	Id       string
	Request  string
	Params   interface{}
	Response interface{}
	Error    error
	Done     chan *Call
}

// ServerError represents an error returned from an RPC server.
type ServerError struct {
	Message string
	Code    string
}

func (e *ServerError) Error() string {
	m := "server error: " + e.Message
	if e.Code != "" {
		m += " (" + e.Code + ")"
	}
	return m
}

func (e *ServerError) ErrorCode() string {
	return e.Code
}

func (client *Client) Close() error {
	client.mutex.Lock()
	if client.shutdown || client.closing {
		client.mutex.Unlock()
		return ErrShutdown
	}
	client.closing = true
	client.mutex.Unlock()
	return client.codec.Close()
}

func (client *Client) send(call *Call) {
	client.sending.Lock()
	defer client.sending.Unlock()

	// Register this call.
	client.mutex.Lock()
	if client.shutdown || client.closing {
		call.Error = ErrShutdown
		client.mutex.Unlock()
		call.done()
		return
	}
	client.reqId++
	reqId := client.reqId
	client.pending[reqId] = call
	client.mutex.Unlock()

	// Encode and send the request.
	client.request = Request{
		RequestId: reqId,
		Type:      call.Type,
		Id:        call.Id,
		Request:   call.Request,
	}
	params := call.Params
	if params == nil {
		params = struct{}{}
	}
	if err := client.codec.WriteRequest(&client.request, params); err != nil {
		client.mutex.Lock()
		call = client.pending[reqId]
		delete(client.pending, reqId)
		client.mutex.Unlock()
		if call != nil {
			call.Error = err
			call.done()
		}
	}
}

func (client *Client) readBody(resp interface{}) error {
	if resp == nil {
		resp = &struct{}{}
	}
	err := client.codec.ReadResponseBody(resp)
	if err != nil {
		err = fmt.Errorf("error reading body: %v", err)
	}
	return err
}

func (client *Client) input() {
	var err error
	var response Response
	for err == nil {
		response = Response{}
		err = client.codec.ReadResponseHeader(&response)
		if err != nil {
			break
		}
		reqId := response.RequestId
		client.mutex.Lock()
		call := client.pending[reqId]
		delete(client.pending, reqId)
		client.mutex.Unlock()

		switch {
		case call == nil:
			// We've got no pending call. That usually means that
			// WriteRequest partially failed, and call was already
			// removed; response is a server telling us about an
			// error reading request body. We should still attempt
			// to read error body, but there's no one to give it to.
			err = client.readBody(nil)
		case response.Error != "":
			// We've got an error response. Give this to the request;
			// any subsequent requests will get the ReadResponseBody
			// error if there is one.
			call.Error = &ServerError{
				Message: response.Error,
				Code:    response.ErrorCode,
			}
			err = client.readBody(nil)
			call.done()
		default:
			err = client.readBody(call.Response)
			call.done()
		}
	}
	// Terminate pending calls.
	client.sending.Lock()
	client.mutex.Lock()
	client.shutdown = true
	closing := client.closing
	if err == io.EOF {
		if closing {
			err = ErrShutdown
		} else {
			err = io.ErrUnexpectedEOF
		}
	}
	for _, call := range client.pending {
		call.Error = err
		call.done()
	}
	client.pending = nil
	client.mutex.Unlock()
	client.sending.Unlock()
	if err != io.EOF && !closing {
		log.Errorf("rpc: client protocol error: %v", err)
	}
}

func (call *Call) done() {
	select {
	case call.Done <- call:
		// ok
	default:
		// We don't want to block here.  It is the caller's responsibility to make
		// sure the channel has enough buffer space. See comment in Go().
		log.Warningf("rpc: discarding Call reply due to insufficient Done chan capacity")
	}
}

// Call invokes the named action on the object of the given type with
// the given id.  The returned values will be stored in response, which
// should be a pointer.  If the action fails remotely, the returned
// error will be of type ServerError.
// The params value may be nil if no parameters are provided;
// the response value may be nil to indicate that any result
// should be discarded.
func (c *Client) Call(objType, id, action string, params, response interface{}) error {
	call := <-c.Go(objType, id, action, params, response, make(chan *Call, 1)).Done
	return call.Error
}

// Go invokes the request asynchronously.  It returns the Call structure representing
// the invocation.  The done channel will signal when the call is complete by returning
// the same Call object.  If done is nil, Go will allocate a new channel.
// If non-nil, done must be buffered or Go will deliberately panic.
func (c *Client) Go(objType, id, request string, args, response interface{}, done chan *Call) *Call {
	if done == nil {
		done = make(chan *Call, 10) // buffered.
	} else {
		// If caller passes done != nil, it must arrange that
		// done has enough buffer for the number of simultaneous
		// RPCs that will be using that channel.  If the channel
		// is totally unbuffered, it's best not to run at all.
		if cap(done) == 0 {
			panic("launchpad.net/juju-core/rpc: done channel is unbuffered")
		}
	}
	call := &Call{
		Type:     objType,
		Id:       id,
		Request:  request,
		Params:   args,
		Response: response,
		Done:     done,
	}
	c.send(call)
	return call
}