22 // If this is 1, then we've called CleanupClients. This can be used
23 // by plugin RPC implementations to change error behavior since you
24 // can expected network connection errors at this point. This should be
25 // read by using sync/atomic.
28 // This is a slice of the "managed" clients which are cleaned up when
30 var managedClients = make([]*Client, 0, 5)
31 var managedClientsLock sync.Mutex
35 // ErrProcessNotFound is returned when a client is instantiated to
36 // reattach to an existing process and it isn't found.
37 ErrProcessNotFound = errors.New("Reattachment process not found")
40 // Client handles the lifecycle of a plugin application. It launches
41 // plugins, connects to them, dispenses interface implementations, and handles
42 // killing the process.
44 // Plugin hosts should use one Client for each plugin executable. To
45 // dispense a plugin type, use the `Client.Client` function, and then
46 // cal `Dispense`. This awkward API is mostly historical but is used to split
47 // the client that deals with subprocess management and the client that
48 // does RPC management.
50 // See NewClient and ClientConfig for using a Client.
54 doneLogging chan struct{}
61 // ClientConfig is the configuration used to initialize a new
62 // plugin client. After being used to initialize a plugin client,
63 // that configuration must not be modified again.
64 type ClientConfig struct {
65 // HandshakeConfig is the configuration that must match servers.
68 // Plugins are the plugins that can be consumed.
69 Plugins map[string]Plugin
71 // One of the following must be set, but not both.
73 // Cmd is the unstarted subprocess for starting the plugin. If this is
74 // set, then the Client starts the plugin process on its own and connects
77 // Reattach is configuration for reattaching to an existing plugin process
78 // that is already running. This isn't common.
80 Reattach *ReattachConfig
82 // Managed represents if the client should be managed by the
83 // plugin package or not. If true, then by calling CleanupClients,
84 // it will automatically be cleaned up. Otherwise, the client
85 // user is fully responsible for making sure to Kill all plugin
86 // clients. By default the client is _not_ managed.
89 // The minimum and maximum port to use for communicating with
90 // the subprocess. If not set, this defaults to 10,000 and 25,000
94 // StartTimeout is the timeout to wait for the plugin to say it
95 // has started successfully.
96 StartTimeout time.Duration
98 // If non-nil, then the stderr of the client will be written to here
99 // (as well as the log). This is the original os.Stderr of the subprocess.
100 // This isn't the output of synced stderr.
103 // SyncStdout, SyncStderr can be set to override the
104 // respective os.Std* values in the plugin. Care should be taken to
105 // avoid races here. If these are nil, then this will automatically be
106 // hooked up to os.Stdin, Stdout, and Stderr, respectively.
108 // If the default values (nil) are used, then this package will not
109 // sync any of these streams.
114 // ReattachConfig is used to configure a client to reattach to an
115 // already-running plugin process. You can retrieve this information by
116 // calling ReattachConfig on Client.
117 type ReattachConfig struct {
122 // This makes sure all the managed subprocesses are killed and properly
123 // logged. This should be called before the parent process running the
126 // This must only be called _once_.
127 func CleanupClients() {
128 // Set the killed to true so that we don't get unexpected panics
129 atomic.StoreUint32(&Killed, 1)
131 // Kill all the managed clients in parallel and use a WaitGroup
132 // to wait for them all to finish up.
133 var wg sync.WaitGroup
134 managedClientsLock.Lock()
135 for _, client := range managedClients {
138 go func(client *Client) {
143 managedClientsLock.Unlock()
145 log.Println("[DEBUG] plugin: waiting for all plugin processes to complete...")
149 // Creates a new plugin client which manages the lifecycle of an external
150 // plugin and gets the address for the RPC connection.
152 // The client must be cleaned up at some point by calling Kill(). If
153 // the client is a managed client (created with NewManagedClient) you
154 // can just call CleanupClients at the end of your program and they will
155 // be properly cleaned.
156 func NewClient(config *ClientConfig) (c *Client) {
157 if config.MinPort == 0 && config.MaxPort == 0 {
158 config.MinPort = 10000
159 config.MaxPort = 25000
162 if config.StartTimeout == 0 {
163 config.StartTimeout = 1 * time.Minute
166 if config.Stderr == nil {
167 config.Stderr = ioutil.Discard
170 if config.SyncStdout == nil {
171 config.SyncStdout = ioutil.Discard
173 if config.SyncStderr == nil {
174 config.SyncStderr = ioutil.Discard
177 c = &Client{config: config}
179 managedClientsLock.Lock()
180 managedClients = append(managedClients, c)
181 managedClientsLock.Unlock()
187 // Client returns an RPC client for the plugin.
189 // Subsequent calls to this will return the same RPC client.
190 func (c *Client) Client() (*RPCClient, error) {
191 addr, err := c.Start()
203 // Connect to the client
204 conn, err := net.Dial(addr.Network(), addr.String())
208 if tcpConn, ok := conn.(*net.TCPConn); ok {
209 // Make sure to set keep alive so that the connection doesn't die
210 tcpConn.SetKeepAlive(true)
213 // Create the actual RPC client
214 c.client, err = NewRPCClient(conn, c.config.Plugins)
220 // Begin the stream syncing so that stdin, out, err work properly
221 err = c.client.SyncStreams(
233 // Tells whether or not the underlying process has exited.
234 func (c *Client) Exited() bool {
240 // End the executing subprocess (if it is running) and perform any cleanup
241 // tasks necessary such as capturing any remaining logs and so on.
243 // This method blocks until the process successfully exits.
245 // This method can safely be called multiple times.
246 func (c *Client) Kill() {
247 // Grab a lock to read some private fields.
251 doneCh := c.doneLogging
254 // If there is no process, we never started anything. Nothing to kill.
259 // We need to check for address here. It is possible that the plugin
260 // started (process != nil) but has no address (addr == nil) if the
261 // plugin failed at startup. If we do have an address, we need to close
262 // the plugin net connections.
265 // Close the client to cleanly exit the process.
266 client, err := c.Client()
270 // If there is no error, then we attempt to wait for a graceful
271 // exit. If there was an error, we assume that graceful cleanup
272 // won't happen and just force kill.
273 graceful = err == nil
275 // If there was an error just log it. We're going to force
276 // kill in a moment anyways.
278 "[WARN] plugin: error closing client during Kill: %s", err)
283 // If we're attempting a graceful exit, then we wait for a short period
284 // of time to allow that to happen. To wait for this we just wait on the
285 // doneCh which would be closed if the process exits.
290 case <-time.After(250 * time.Millisecond):
294 // If graceful exiting failed, just kill it
297 // Wait for the client to finish logging so we have a complete log
301 // Starts the underlying subprocess, communicating with it to negotiate
302 // a port for RPC connections, and returning the address to connect via RPC.
304 // This method is safe to call multiple times. Subsequent calls have no effect.
305 // Once a client has been started once, it cannot be started again, even if
307 func (c *Client) Start() (addr net.Addr, err error) {
311 if c.address != nil {
312 return c.address, nil
315 // If one of cmd or reattach isn't set, then it is an error. We wrap
316 // this in a {} for scoping reasons, and hopeful that the escape
317 // analysis will pop the stock here.
319 cmdSet := c.config.Cmd != nil
320 attachSet := c.config.Reattach != nil
321 if cmdSet == attachSet {
322 return nil, fmt.Errorf("Only one of Cmd or Reattach must be set")
326 // Create the logging channel for when we kill
327 c.doneLogging = make(chan struct{})
329 if c.config.Reattach != nil {
330 // Verify the process still exists. If not, then it is an error
331 p, err := os.FindProcess(c.config.Reattach.Pid)
336 // Attempt to connect to the addr since on Unix systems FindProcess
337 // doesn't actually return an error if it can't find the process.
338 conn, err := net.Dial(
339 c.config.Reattach.Addr.Network(),
340 c.config.Reattach.Addr.String())
343 return nil, ErrProcessNotFound
347 // Goroutine to mark exit status
349 // Wait for the process to die
352 // Log so we can see it
353 log.Printf("[DEBUG] plugin: reattached plugin process exited\n")
360 // Close the logging channel since that doesn't work on reattach
364 // Set the address and process
365 c.address = c.config.Reattach.Addr
368 return c.address, nil
372 fmt.Sprintf("%s=%s", c.config.MagicCookieKey, c.config.MagicCookieValue),
373 fmt.Sprintf("PLUGIN_MIN_PORT=%d", c.config.MinPort),
374 fmt.Sprintf("PLUGIN_MAX_PORT=%d", c.config.MaxPort),
377 stdout_r, stdout_w := io.Pipe()
378 stderr_r, stderr_w := io.Pipe()
381 cmd.Env = append(cmd.Env, os.Environ()...)
382 cmd.Env = append(cmd.Env, env...)
384 cmd.Stderr = stderr_w
385 cmd.Stdout = stdout_w
387 log.Printf("[DEBUG] plugin: starting plugin: %s %#v", cmd.Path, cmd.Args)
394 c.process = cmd.Process
396 // Make sure the command is properly cleaned up if there is an error
400 if err != nil || r != nil {
409 // Start goroutine to wait for process to exit
410 exitCh := make(chan struct{})
412 // Make sure we close the write end of our stderr/stdout so
413 // that the readers send EOF properly.
414 defer stderr_w.Close()
415 defer stdout_w.Close()
417 // Wait for the command to end.
420 // Log and make sure to flush the logs write away
421 log.Printf("[DEBUG] plugin: %s: plugin process exited\n", cmd.Path)
424 // Mark that we exited
427 // Set that we exited, which takes a lock
433 // Start goroutine that logs the stderr
434 go c.logStderr(stderr_r)
436 // Start a goroutine that is going to be reading the lines
438 linesCh := make(chan []byte)
442 buf := bufio.NewReader(stdout_r)
444 line, err := buf.ReadBytes('\n')
455 // Make sure after we exit we read the lines from stdout forever
456 // so they don't block since it is an io.Pipe
459 for _ = range linesCh {
464 // Some channels for the next step
465 timeout := time.After(c.config.StartTimeout)
467 // Start looking for the address
468 log.Printf("[DEBUG] plugin: waiting for RPC address for: %s", cmd.Path)
471 err = errors.New("timeout while waiting for plugin to start")
473 err = errors.New("plugin exited before we could connect")
474 case lineBytes := <-linesCh:
475 // Trim the line and split by "|" in order to get the parts of
477 line := strings.TrimSpace(string(lineBytes))
478 parts := strings.SplitN(line, "|", 4)
481 "Unrecognized remote plugin message: %s\n\n"+
482 "This usually means that the plugin is either invalid or simply\n"+
483 "needs to be recompiled to support the latest protocol.", line)
487 // Check the core protocol. Wrapped in a {} for scoping.
489 var coreProtocol int64
490 coreProtocol, err = strconv.ParseInt(parts[0], 10, 0)
492 err = fmt.Errorf("Error parsing core protocol version: %s", err)
496 if int(coreProtocol) != CoreProtocolVersion {
497 err = fmt.Errorf("Incompatible core API version with plugin. "+
498 "Plugin version: %s, Ours: %d\n\n"+
499 "To fix this, the plugin usually only needs to be recompiled.\n"+
500 "Please report this to the plugin author.", parts[0], CoreProtocolVersion)
505 // Parse the protocol version
507 protocol, err = strconv.ParseInt(parts[1], 10, 0)
509 err = fmt.Errorf("Error parsing protocol version: %s", err)
513 // Test the API version
514 if uint(protocol) != c.config.ProtocolVersion {
515 err = fmt.Errorf("Incompatible API version with plugin. "+
516 "Plugin version: %s, Ours: %d", parts[1], c.config.ProtocolVersion)
522 addr, err = net.ResolveTCPAddr("tcp", parts[3])
524 addr, err = net.ResolveUnixAddr("unix", parts[3])
526 err = fmt.Errorf("Unknown address type: %s", parts[3])
534 // ReattachConfig returns the information that must be provided to NewClient
535 // to reattach to the plugin process that this client started. This is
536 // useful for plugins that detach from their parent process.
538 // If this returns nil then the process hasn't been started yet. Please
539 // call Start or Client before calling this.
540 func (c *Client) ReattachConfig() *ReattachConfig {
544 if c.address == nil {
548 if c.config.Cmd != nil && c.config.Cmd.Process == nil {
552 // If we connected via reattach, just return the information as-is
553 if c.config.Reattach != nil {
554 return c.config.Reattach
557 return &ReattachConfig{
559 Pid: c.config.Cmd.Process.Pid,
563 func (c *Client) logStderr(r io.Reader) {
564 bufR := bufio.NewReader(r)
566 line, err := bufR.ReadString('\n')
568 c.config.Stderr.Write([]byte(line))
570 line = strings.TrimRightFunc(line, unicode.IsSpace)
571 log.Printf("[DEBUG] plugin: %s: %s", filepath.Base(c.config.Cmd.Path), line)
579 // Flag that we've completed logging for others