From bb00ef54d1e61f9a528a79a09638b5f4414c3e7f Mon Sep 17 00:00:00 2001 From: Fabian Freyer Date: Wed, 2 Jan 2019 15:37:17 +0100 Subject: [PATCH] python: allow constructin RunningJail from name --- bindings/python/src/running.rs | 33 ++++++++++++++++++++++++------ bindings/python/tests/test_jail.py | 17 +++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/bindings/python/src/running.rs b/bindings/python/src/running.rs index da2e3d1d4..4457753bb 100644 --- a/bindings/python/src/running.rs +++ b/bindings/python/src/running.rs @@ -52,12 +52,33 @@ impl DerefMut for RunningJail { #[pymethods] impl RunningJail { #[new] - fn __new__(obj: &PyRawObject, jid: i32) -> PyResult<()> { - obj.init(|token| RunningJail { - inner: native::RunningJail::from_jid(jid), - dead: false, - token, - }) + fn __new__(obj: &PyRawObject, identifier: PyObject) -> PyResult<()> { + // Attempt to parse the id as a jid + let py_num: Result<&PyInt, PyDowncastError> = identifier.as_ref(obj.py()).try_into(); + if let Ok(jid) = py_num { + let jid: i32 = jid.extract()?; + return obj.init(|token| RunningJail { + inner: native::RunningJail::from_jid(jid), + dead: false, + token, + }); + } + + // Attempt to parse the id as a string and interpret it as a name + let py_string: Result<&PyString, PyDowncastError> = identifier.as_ref(obj.py()).try_into(); + if let Ok(name) = py_string { + let name: String = name.extract()?; + let inner = native::RunningJail::from_name(&name) + .map_err(JailError::from) + .map_err::(|e| e.into())?; + return obj.init(|token| RunningJail { + inner: inner, + dead: false, + token, + }); + } + + Err(exceptions::ValueError::py_err("Invalid JID or name passed")) } /// Return a String representation of the Jail diff --git a/bindings/python/tests/test_jail.py b/bindings/python/tests/test_jail.py index 92fe14a01..ec9ff2931 100644 --- a/bindings/python/tests/test_jail.py +++ b/bindings/python/tests/test_jail.py @@ -61,3 +61,20 @@ def test_jls(benchmark): r.stop(); assert started_jids <= jids + + +def get_jail_by_name(name): + r = RunningJail(name) + hostname = r.parameters['host.hostname'] + del r + return hostname + +def test_get_jail_by_name(benchmark): + s = StoppedJail('/rescue', name="foobar", parameters={"host.hostname": "foobar"}) + r = s.start() + + hostname = benchmark(get_jail_by_name, "foobar") + + r.stop() + + assert hostname == "foobar"