From 4e6a6deca6655d949daa69d5b5ef2e31b85532e6 Mon Sep 17 00:00:00 2001 From: Joshua Harlow Date: Thu, 24 Apr 2014 16:29:11 -0700 Subject: [PATCH] Add a jobboard fetching context manager Allow the jobboard backend to be fetched and automatically connected and closed by providing a method that does the fetching, connecting and closing as a context manager. Change-Id: I3b2ea707009f8154f2c68652f101490c09f35c8c --- taskflow/jobs/backends/__init__.py | 12 ++++++++++++ taskflow/jobs/jobboard.py | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/taskflow/jobs/backends/__init__.py b/taskflow/jobs/backends/__init__.py index b720024b..0299636a 100644 --- a/taskflow/jobs/backends/__init__.py +++ b/taskflow/jobs/backends/__init__.py @@ -14,6 +14,7 @@ # License for the specific language governing permissions and limitations # under the License. +import contextlib import logging import six @@ -53,3 +54,14 @@ def fetch(name, conf, namespace=BACKEND_NAMESPACE, **kwargs): return mgr.driver except RuntimeError as e: raise exc.NotFound("Could not find jobboard %s" % (board), e) + + +@contextlib.contextmanager +def backend(name, conf, namespace=BACKEND_NAMESPACE, **kwargs): + """Fetches a jobboard backend, connects to it and allows it to be used in + a context manager statement with the jobboard being closed upon completion. + """ + jb = fetch(name, conf, namespace=namespace, **kwargs) + jb.connect() + with contextlib.closing(jb): + yield jb diff --git a/taskflow/jobs/jobboard.py b/taskflow/jobs/jobboard.py index 070b3ea3..0f3d4455 100644 --- a/taskflow/jobs/jobboard.py +++ b/taskflow/jobs/jobboard.py @@ -132,6 +132,18 @@ class JobBoard(object): this must be the same name that was used for claiming this job. """ + @abc.abstractmethod + def connect(self): + """Opens the connection to any backend system.""" + + @abc.abstractmethod + def close(self): + """Close the connection to any backend system. + + Once closed the jobboard can no longer be used (unless reconnection + occurs). + """ + # Jobboard events POSTED = 'POSTED' # new job is/has been posted