Skip to content

Replace some of the unwrap() calls #308

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 40 additions & 17 deletions src/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl<'docker> Container<'docker> {
psargs: Option<&str>,
) -> Result<Top> {
let mut path = vec![format!("/containers/{}/top", self.id)];
if let Some(ref args) = psargs {
if let Some(args) = psargs {
let encoded = form_urlencoded::Serializer::new(String::new())
.append_pair("ps_args", args)
.finish();
Expand Down Expand Up @@ -386,7 +386,7 @@ impl<'docker> Container<'docker> {
.append_pair("path", &path.to_string_lossy())
.finish();

let mime = "application/x-tar".parse::<Mime>().unwrap();
let mime = "application/x-tar".parse::<Mime>()?;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this actually ever fail? unwrap/expect seems to be ok here.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is right. Thanks for your advice a lot


self.docker
.put(
Expand Down Expand Up @@ -571,26 +571,49 @@ fn insert<'a, I, V>(
key_path: &mut Peekable<I>,
value: &V,
parent_node: &mut Value,
) where
) -> io::Result<()>
where
V: Serialize,
I: Iterator<Item = &'a str>,
{
let local_key = key_path.next().unwrap();
let local_key = match key_path.next() {
Some(val) => val,
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
"Key path is not provided!",
))
}
};

if key_path.peek().is_some() {
let node = parent_node
.as_object_mut()
.unwrap()
.entry(local_key.to_string())
.or_insert(Value::Object(Map::new()));

insert(key_path, value, node);
let node = match parent_node.as_object_mut() {
Some(object) => object
.entry(local_key.to_string())
.or_insert(Value::Object(Map::new())),
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Value {} is not an object", local_key.to_string()),
))
}
};

insert(key_path, value, node)?;
} else {
parent_node
.as_object_mut()
.unwrap()
.insert(local_key.to_string(), serde_json::to_value(value).unwrap());
}
match parent_node.as_object_mut() {
Some(object) => {
object.insert(local_key.to_string(), serde_json::to_value(value).unwrap())
}
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Value {} is not an object", local_key.to_string()),
))
}
};
}
Ok(())
}

impl ContainerOptions {
Expand Down Expand Up @@ -625,7 +648,7 @@ impl ContainerOptions {
{
for (k, v) in params.iter() {
let key_string = k.to_string();
insert(&mut key_string.split('.').peekable(), v, body)
insert(&mut key_string.split('.').peekable(), v, body).unwrap();
}
}
}
Expand Down
37 changes: 15 additions & 22 deletions src/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,24 +48,18 @@ fn get_http_connector() -> HttpConnector {
}

#[cfg(feature = "tls")]
fn get_docker_for_tcp(tcp_host_str: String) -> Docker {
fn get_docker_for_tcp(tcp_host_str: String) -> Result<Docker> {
let http = get_http_connector();
if let Ok(ref certs) = env::var("DOCKER_CERT_PATH") {
// fixme: don't unwrap before you know what's in the box
// https://github.com/hyperium/hyper/blob/master/src/net.rs#L427-L428
let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
connector.set_cipher_list("DEFAULT").unwrap();
let mut connector = SslConnector::builder(SslMethod::tls())?;
connector.set_cipher_list("DEFAULT")?;
let cert = &format!("{}/cert.pem", certs);
let key = &format!("{}/key.pem", certs);
connector
.set_certificate_file(&Path::new(cert), SslFiletype::PEM)
.unwrap();
connector
.set_private_key_file(&Path::new(key), SslFiletype::PEM)
.unwrap();
connector.set_certificate_file(&Path::new(cert), SslFiletype::PEM)?;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of the generic Ssl error, we could map to a variant Error::InvalidCertificate. That would give us something meaningful to say in our Display impl without having to print the inner error.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SSL error can be returned not just here, it will be generated, for example in docker.rs at line 54: let mut connector = SslConnector::builder(SslMethod::tls())?;, and on line 59: connector.set_private_key_file(&Path::new(key), SslFiletype::PEM)?; (And there are more). So we can't really guarantee that all of these errors will be caused by an invalid certificate, and in my opinion, it's better to make just a general SSL error, containing an inner error

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we would need more than one variant, not just InvalidCertificate but also InvalidPrivateKey etc.

Which is why I said "feel free to ignore if you think it becomes too verbose" :)

A general Ssl error is certainly more concise but the error messages will be less helpful because it is not as clear where the error originated.

connector.set_private_key_file(&Path::new(key), SslFiletype::PEM)?;
if env::var("DOCKER_TLS_VERIFY").is_ok() {
let ca = &format!("{}/ca.pem", certs);
connector.set_ca_file(&Path::new(ca)).unwrap();
connector.set_ca_file(&Path::new(ca))?;
}

// If we are attempting to connec to the docker daemon via tcp
Expand All @@ -78,32 +72,31 @@ fn get_docker_for_tcp(tcp_host_str: String) -> Docker {
tcp_host_str
};

Docker {
Ok(Docker {
transport: Transport::EncryptedTcp {
client: Client::builder()
.build(HttpsConnector::with_connector(http, connector).unwrap()),
client: Client::builder().build(HttpsConnector::with_connector(http, connector)?),
host: tcp_host_str,
},
}
})
} else {
Docker {
Ok(Docker {
transport: Transport::Tcp {
client: Client::builder().build(http),
host: tcp_host_str,
},
}
})
}
}

#[cfg(not(feature = "tls"))]
fn get_docker_for_tcp(tcp_host_str: String) -> Docker {
fn get_docker_for_tcp(tcp_host_str: String) -> Result<Docker> {
let http = get_http_connector();
Docker {
Ok(Docker {
transport: Transport::Tcp {
client: Client::builder().build(http),
host: tcp_host_str,
},
}
})
}

// https://docs.docker.com/reference/api/docker_remote_api_v1.17/
Expand Down Expand Up @@ -165,7 +158,7 @@ impl Docker {
#[cfg(not(feature = "unix-socket"))]
Some("unix") => panic!("Unix socket support is disabled"),

_ => get_docker_for_tcp(tcp_host_str),
_ => get_docker_for_tcp(tcp_host_str).unwrap(),
}
}

Expand Down
20 changes: 20 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! Representations of various client errors

use hyper::{self, http, StatusCode};
use mime::FromStrError;
use openssl::error::ErrorStack;
use serde_json::Error as SerdeError;
use std::{error::Error as StdError, fmt, string::FromUtf8Error};

Expand All @@ -18,6 +20,8 @@ pub enum Error {
IO(IoError),
Encoding(FromUtf8Error),
InvalidResponse(String),
Ssl(ErrorStack),
Mime(FromStrError),
Fault {
code: StatusCode,
message: String,
Expand Down Expand Up @@ -62,6 +66,18 @@ impl From<FromUtf8Error> for Error {
}
}

impl From<ErrorStack> for Error {
fn from(error: ErrorStack) -> Error {
Error::Ssl(error)
}
}

impl From<FromStrError> for Error {
fn from(error: FromStrError) -> Error {
Error::Mime(error)
}
}

impl fmt::Display for Error {
fn fmt(
&self,
Expand All @@ -77,6 +93,8 @@ impl fmt::Display for Error {
Error::InvalidResponse(ref cause) => {
write!(f, "Response doesn't have the expected format: {}", cause)
}
Error::Ssl(ref err) => write!(f, "SSL error: {}", err),
Error::Mime(ref err) => write!(f, "Mime error: {}", err),
Error::Fault { code, message } => write!(f, "{}: {}", code, message),
Error::ConnectionNotUpgraded => write!(
f,
Expand All @@ -93,6 +111,8 @@ impl StdError for Error {
Error::Http(ref err) => Some(err),
Error::IO(ref err) => Some(err),
Error::Encoding(e) => Some(e),
Error::Ssl(ref err) => Some(err),
Error::Mime(ref err) => Some(err),
_ => None,
}
}
Expand Down
30 changes: 21 additions & 9 deletions src/tarball.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ where
{
if fs::metadata(dir)?.is_dir() {
if bundle_dir {
f(&dir)?;
f(dir)?;
}
for entry in fs::read_dir(dir)? {
let entry = entry?;
if fs::metadata(entry.path())?.is_dir() {
bundle(&entry.path(), f, true)?;
} else {
f(&entry.path().as_path())?;
f(entry.path().as_path())?;
}
}
}
Expand All @@ -41,8 +41,15 @@ where

{
let base_path = Path::new(path).canonicalize()?;
// todo: don't unwrap
let mut base_path_str = base_path.to_str().unwrap().to_owned();
let mut base_path_str = match base_path.to_str() {
Some(path) => path.to_owned(),
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Path uses non UTF-8 characters",
))
}
};
if let Some(last) = base_path_str.chars().last() {
if last != MAIN_SEPARATOR {
base_path_str.push(MAIN_SEPARATOR)
Expand All @@ -51,11 +58,16 @@ where

let mut append = |path: &Path| {
let canonical = path.canonicalize()?;
// todo: don't unwrap
let relativized = canonical
.to_str()
.unwrap()
.trim_start_matches(&base_path_str[..]);

let relativized = match canonical.to_str() {
Some(path) => path.trim_start_matches(&base_path_str[..]),
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Path uses non UTF-8 characters",
))
}
};
if path.is_dir() {
archive.append_dir(Path::new(relativized), &canonical)?
} else {
Expand Down