1 // Copyright 2016 Mozilla Foundation
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use crate::errors::*;
16 use crate::protocol::{Request, Response};
17 use crate::util;
18 use byteorder::{BigEndian, ByteOrder};
19 use retry::{delay::Fixed, retry};
20 use std::io::{self, BufReader, BufWriter, Read};
21 use std::net::TcpStream;
22 
23 /// A connection to an sccache server.
24 pub struct ServerConnection {
25     /// A reader for the socket connected to the server.
26     reader: BufReader<TcpStream>,
27     /// A writer for the socket connected to the server.
28     writer: BufWriter<TcpStream>,
29 }
30 
31 impl ServerConnection {
32     /// Create a new connection using `stream`.
new(stream: TcpStream) -> io::Result<ServerConnection>33     pub fn new(stream: TcpStream) -> io::Result<ServerConnection> {
34         let writer = stream.try_clone()?;
35         Ok(ServerConnection {
36             reader: BufReader::new(stream),
37             writer: BufWriter::new(writer),
38         })
39     }
40 
41     /// Send `request` to the server, read and return a `Response`.
request(&mut self, request: Request) -> Result<Response>42     pub fn request(&mut self, request: Request) -> Result<Response> {
43         trace!("ServerConnection::request");
44         util::write_length_prefixed_bincode(&mut self.writer, request)?;
45         trace!("ServerConnection::request: sent request");
46         self.read_one_response()
47     }
48 
49     /// Read a single `Response` from the server.
read_one_response(&mut self) -> Result<Response>50     pub fn read_one_response(&mut self) -> Result<Response> {
51         trace!("ServerConnection::read_one_response");
52         let mut bytes = [0; 4];
53         self.reader
54             .read_exact(&mut bytes)
55             .context("Failed to read response header")?;
56         let len = BigEndian::read_u32(&bytes);
57         trace!("Should read {} more bytes", len);
58         let mut data = vec![0; len as usize];
59         self.reader.read_exact(&mut data)?;
60         trace!("Done reading");
61         Ok(bincode::deserialize(&data)?)
62     }
63 }
64 
65 /// Establish a TCP connection to an sccache server listening on `port`.
connect_to_server(port: u16) -> io::Result<ServerConnection>66 pub fn connect_to_server(port: u16) -> io::Result<ServerConnection> {
67     trace!("connect_to_server({})", port);
68     let stream = TcpStream::connect(("127.0.0.1", port))?;
69     ServerConnection::new(stream)
70 }
71 
72 /// Attempt to establish a TCP connection to an sccache server listening on `port`.
73 ///
74 /// If the connection fails, retry a few times.
connect_with_retry(port: u16) -> io::Result<ServerConnection>75 pub fn connect_with_retry(port: u16) -> io::Result<ServerConnection> {
76     trace!("connect_with_retry({})", port);
77     // TODOs:
78     // * Pass the server Child in here, so we can stop retrying
79     //   if the process exited.
80     // * Send a pipe handle to the server process so it can notify
81     //   us once it starts the server instead of us polling.
82     match retry(Fixed::from_millis(500).take(10), || connect_to_server(port)) {
83         Ok(conn) => Ok(conn),
84         _ => Err(io::Error::new(
85             io::ErrorKind::TimedOut,
86             "Connection to server timed out",
87         )),
88     }
89 }
90