import config
from exec_utils import run_silently, cmd_in_background
from decorator_utils import singleton
-import histogram
+import histogram as hist
logger = logging.getLogger(__name__)
RSYNC = 'rsync -q --no-motd -W --ignore-existing --timeout=60 --size-only -z'
SSH = 'ssh -oForwardX11=no'
-HIST = histogram.SimpleHistogram(
- histogram.SimpleHistogram.n_evenly_spaced_buckets(
- int(0), int(500), 25
- )
-)
-
-
-def run_local_bundle(fun, *args, **kwargs):
- logger.debug(f"Running local bundle at {fun.__name__}")
- start = time.time()
- result = fun(*args, **kwargs)
- end = time.time()
- duration = end - start
- logger.debug(f"{fun.__name__} finished; used {duration:.1f}s")
- HIST.add_item(duration)
- return result
-
-
-def run_cloud_pickle(pickle):
- fun, args, kwargs = cloudpickle.loads(pickle)
- logger.debug(f"Running pickled bundle at {fun.__name__}")
- start = time.time()
- result = fun(*args, **kwargs)
- end = time.time()
- duration = end - start
- logger.debug(f"{fun.__name__} finished; used {duration:.1f}s")
- return result
def make_cloud_pickle(fun, *args, **kwargs):
class BaseExecutor(ABC):
- def __init__(self):
- pass
+ def __init__(self, *, title=''):
+ self.title = title
+ self.task_count = 0
+ self.histogram = hist.SimpleHistogram(
+ hist.SimpleHistogram.n_evenly_spaced_buckets(
+ int(0), int(500), 50
+ )
+ )
@abstractmethod
def submit(self,
wait: bool = True) -> None:
pass
+ def adjust_task_count(self, delta: int) -> None:
+ self.task_count += delta
+ logger.debug(f'Executor current task count is {self.task_count}')
+
class ThreadExecutor(BaseExecutor):
def __init__(self,
max_workers=workers,
thread_name_prefix="thread_executor_helper"
)
- self.job_count = 0
+
+ def run_local_bundle(self, fun, *args, **kwargs):
+ logger.debug(f"Running local bundle at {fun.__name__}")
+ start = time.time()
+ result = fun(*args, **kwargs)
+ end = time.time()
+ self.adjust_task_count(-1)
+ duration = end - start
+ logger.debug(f"{fun.__name__} finished; used {duration:.1f}s")
+ self.histogram.add_item(duration)
+ return result
def submit(self,
function: Callable,
*args,
**kwargs) -> fut.Future:
- self.job_count += 1
- logger.debug(
- f'Submitted work to threadpool; there are now {self.job_count} items.'
- )
+ self.adjust_task_count(+1)
newargs = []
newargs.append(function)
for arg in args:
newargs.append(arg)
return self._thread_pool_executor.submit(
- run_local_bundle,
+ self.run_local_bundle,
*newargs,
**kwargs)
def shutdown(self,
wait = True) -> None:
- logger.debug("Shutting down threadpool executor.")
- print(HIST)
+ logger.debug(f'Shutting down threadpool executor {self.title}')
+ print(self.histogram)
self._thread_pool_executor.shutdown(wait)
self._process_executor = fut.ProcessPoolExecutor(
max_workers=workers,
)
- self.job_count = 0
+
+ def run_cloud_pickle(self, pickle):
+ fun, args, kwargs = cloudpickle.loads(pickle)
+ logger.debug(f"Running pickled bundle at {fun.__name__}")
+ result = fun(*args, **kwargs)
+ self.adjust_task_count(-1)
+ return result
def submit(self,
function: Callable,
*args,
**kwargs) -> fut.Future:
- # Bundle it up before submitting because pickle sucks.
+ start = time.time()
+ self.adjust_task_count(+1)
pickle = make_cloud_pickle(function, *args, **kwargs)
- self.job_count += 1
- logger.debug(
- f'Submitting work to processpool executor; there are now {self.job_count} items.'
+ result = self._process_executor.submit(
+ self.run_cloud_pickle,
+ pickle
+ )
+ result.add_done_callback(
+ lambda _: self.histogram.add_item(
+ time.time() - start
+ )
)
- return self._process_executor.submit(run_cloud_pickle, pickle)
+ return result
def shutdown(self, wait=True) -> None:
- logger.debug('Shutting down processpool executor')
- print(HIST)
+ logger.debug(f'Shutting down processpool executor {self.title}')
self._process_executor.shutdown(wait)
+ print(self.histogram)
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state['_process_executor'] = None
+ return state
@dataclass
def launch(self, bundle: BundleDetails) -> Any:
"""Find a worker for bundle or block until one is available."""
+ self.adjust_task_count(+1)
uuid = bundle.uuid
hostname = bundle.hostname
avoid_machine = None
# Whether original or backup, if we finished first we must
# fetch the results if the computation happened on a
# remote machine.
+ bundle.end_ts = time.time()
if not was_cancelled:
assert bundle.machine is not None
if bundle.hostname not in bundle.machine:
try:
run_silently(cmd)
except subprocess.CalledProcessError:
- pass
+ logger.critical(f'Failed to copy {username}@{machine}:{result_file}!')
run_silently(f'{SSH} {username}@{machine}'
f' "/bin/rm -f {code_file} {result_file}"')
- bundle.end_ts = time.time()
+ dur = bundle.end_ts - bundle.start_ts
+ self.histogram.add_item(dur)
assert bundle.worker is not None
self.status.record_release_worker_already_locked(
bundle.worker,
bundle.uuid,
was_cancelled
)
- if not was_cancelled:
- dur = bundle.end_ts - bundle.start_ts
- HIST.add_item(dur)
-
- # Original or not, the results should be back on the local
- # machine. Are they?
- if not os.path.exists(result_file):
- msg = f'{result_file} unexpectedly missing, wtf?!'
- logger.critical(msg)
- bundle.failure_count += 1
- self.release_worker(bundle.worker)
- raise Exception(msg)
# Only the original worker should unpickle the file contents
- # though since it's the only one whose result matters.
+ # though since it's the only one whose result matters. The
+ # original is also the only job that may delete result_file
+ # from disk. Note that the original may have been cancelled
+ # if one of the backups finished first; it still must read the
+ # result from disk.
if is_original:
logger.debug(f"Unpickling {result_file}.")
try:
)
backup.is_cancelled.set()
- # This is a backup.
+ # This is a backup job.
else:
# Backup results don't matter, they just need to leave the
- # result file in the right place for their original to
- # read later.
+ # result file in the right place for their originals to
+ # read/unpickle later.
result = None
# Tell the original to stop if we finished first.
assert bundle.worker is not None
self.release_worker(bundle.worker)
+ self.adjust_task_count(-1)
return result
def create_original_bundle(self, pickle):
pickle = make_cloud_pickle(function, *args, **kwargs)
bundle = self.create_original_bundle(pickle)
self.total_bundles_submitted += 1
- logger.debug(
- f'Submitted work to remote executor; {self.total_bundles_submitted} items now submitted'
- )
return self._helper_executor.submit(self.launch, bundle)
def shutdown(self, wait=True) -> None:
self._helper_executor.shutdown(wait)
- print(HIST)
+ logging.debug(f'Shutting down RemoteExecutor {self.title}')
+ print(self.histogram)
@singleton
#!/usr/bin/env python3
import datetime
+import random
+import re
import unittest
import pytz
import unittest_utils as uu
+parsable_expressions = [
+ ('today',
+ datetime.datetime(2021, 7, 2)),
+ ('tomorrow',
+ datetime.datetime(2021, 7, 3)),
+ ('yesterday',
+ datetime.datetime(2021, 7, 1)),
+ ('21:30',
+ datetime.datetime(2021, 7, 2, 21, 30, 0, 0)),
+ ('12:01am',
+ datetime.datetime(2021, 7, 2, 0, 1, 0, 0)),
+ ('12:02p',
+ datetime.datetime(2021, 7, 2, 12, 2, 0, 0)),
+ ('0:03',
+ datetime.datetime(2021, 7, 2, 0, 3, 0, 0)),
+ ('last wednesday',
+ datetime.datetime(2021, 6, 30)),
+ ('this wed',
+ datetime.datetime(2021, 7, 7)),
+ ('next wed',
+ datetime.datetime(2021, 7, 14)),
+ ('this coming tues',
+ datetime.datetime(2021, 7, 6)),
+ ('this past monday',
+ datetime.datetime(2021, 6, 28)),
+ ('4 days ago',
+ datetime.datetime(2021, 6, 28)),
+ ('4 mondays ago',
+ datetime.datetime(2021, 6, 7)),
+ ('4 months ago',
+ datetime.datetime(2021, 3, 2)),
+ ('3 days back',
+ datetime.datetime(2021, 6, 29)),
+ ('13 weeks from now',
+ datetime.datetime(2021, 10, 1)),
+ ('1 year from now',
+ datetime.datetime(2022, 7, 2)),
+ ('4 weeks from now',
+ datetime.datetime(2021, 7, 30)),
+ ('3 saturdays ago',
+ datetime.datetime(2021, 6, 12)),
+ ('4 months from today',
+ datetime.datetime(2021, 11, 2)),
+ ('4 years from yesterday',
+ datetime.datetime(2025, 7, 1)),
+ ('4 weeks from tomorrow',
+ datetime.datetime(2021, 7, 31)),
+ ('april 15, 2005',
+ datetime.datetime(2005, 4, 15)),
+ ('april 14',
+ datetime.datetime(2021, 4, 14)),
+ ('9:30am on last wednesday',
+ datetime.datetime(2021, 6, 30, 9, 30)),
+ ('2005/apr/15',
+ datetime.datetime(2005, 4, 15)),
+ ('2005 apr 15',
+ datetime.datetime(2005, 4, 15)),
+ ('the 1st wednesday in may',
+ datetime.datetime(2021, 5, 5)),
+ ('last sun of june',
+ datetime.datetime(2021, 6, 27)),
+ ('this Easter',
+ datetime.datetime(2021, 4, 4)),
+ ('last christmas',
+ datetime.datetime(2020, 12, 25)),
+ ('last Xmas',
+ datetime.datetime(2020, 12, 25)),
+ ('xmas, 1999',
+ datetime.datetime(1999, 12, 25)),
+ ('next mlk day',
+ datetime.datetime(2022, 1, 17)),
+ ('Halloween, 2020',
+ datetime.datetime(2020, 10, 31)),
+ ('5 work days after independence day',
+ datetime.datetime(2021, 7, 12)),
+ ('50 working days from last wed',
+ datetime.datetime(2021, 9, 10)),
+ ('25 working days before columbus day',
+ datetime.datetime(2021, 9, 3)),
+ ('today +1 week',
+ datetime.datetime(2021, 7, 9)),
+ ('sunday -3 weeks',
+ datetime.datetime(2021, 6, 13)),
+ ('4 weeks before xmas, 1999',
+ datetime.datetime(1999, 11, 27)),
+ ('3 days before new years eve, 2000',
+ datetime.datetime(2000, 12, 28)),
+ ('july 4th',
+ datetime.datetime(2021, 7, 4)),
+ ('the ides of march',
+ datetime.datetime(2021, 3, 15)),
+ ('the nones of april',
+ datetime.datetime(2021, 4, 5)),
+ ('the kalends of may',
+ datetime.datetime(2021, 5, 1)),
+ ('9/11/2001',
+ datetime.datetime(2001, 9, 11)),
+ ('4 sundays before veterans\' day',
+ datetime.datetime(2021, 10, 17)),
+ ('xmas eve',
+ datetime.datetime(2021, 12, 24)),
+ ('this friday at 5pm',
+ datetime.datetime(2021, 7, 9, 17, 0, 0)),
+ ('presidents day',
+ datetime.datetime(2021, 2, 15)),
+ ('memorial day, 1921',
+ datetime.datetime(1921, 5, 30)),
+ ('today -4 wednesdays',
+ datetime.datetime(2021, 6, 9)),
+ ('thanksgiving',
+ datetime.datetime(2021, 11, 25)),
+ ('2 sun in jun',
+ datetime.datetime(2021, 6, 13)),
+ ('easter -40 days',
+ datetime.datetime(2021, 2, 23)),
+ ('easter +39 days',
+ datetime.datetime(2021, 5, 13)),
+ ('1st tuesday in nov, 2024',
+ datetime.datetime(2024, 11, 5)),
+ ('2 days before last xmas at 3:14:15.92a',
+ datetime.datetime(2020, 12, 23, 3, 14, 15, 92)),
+ ('3 weeks after xmas, 1995 at midday',
+ datetime.datetime(1996, 1, 15, 12, 0, 0)),
+ ('4 months before easter, 1992 at midnight',
+ datetime.datetime(1991, 12, 19)),
+ ('5 months before halloween, 1995 at noon',
+ datetime.datetime(1995, 5, 31, 12)),
+ ('4 days before last wednesday',
+ datetime.datetime(2021, 6, 26)),
+ ('44 months after today',
+ datetime.datetime(2025, 3, 2)),
+ ('44 years before today',
+ datetime.datetime(1977, 7, 2)),
+ ('44 weeks ago',
+ datetime.datetime(2020, 8, 28)),
+ ('15 minutes to 3am',
+ datetime.datetime(2021, 7, 2, 2, 45)),
+ ('quarter past 4pm',
+ datetime.datetime(2021, 7, 2, 16, 15)),
+ ('half past 9',
+ datetime.datetime(2021, 7, 2, 9, 30)),
+ ('4 seconds to midnight',
+ datetime.datetime(2021, 7, 1, 23, 59, 56)),
+ ('4 seconds to midnight, tomorrow',
+ datetime.datetime(2021, 7, 2, 23, 59, 56)),
+ ('2021/apr/15T21:30:44.55',
+ datetime.datetime(2021, 4, 15, 21, 30, 44, 55)),
+ ('2021/apr/15 at 21:30:44.55',
+ datetime.datetime(2021, 4, 15, 21, 30, 44, 55)),
+ ('2021/4/15 at 21:30:44.55',
+ datetime.datetime(2021, 4, 15, 21, 30, 44, 55)),
+ ('2021/04/15 at 21:30:44.55',
+ datetime.datetime(2021, 4, 15, 21, 30, 44, 55)),
+ ('2021/04/15 at 21:30:44.55Z',
+ datetime.datetime(2021, 4, 15, 21, 30, 44, 55,
+ tzinfo=pytz.timezone('UTC'))),
+ ('2021/04/15 at 21:30:44.55EST',
+ datetime.datetime(2021, 4, 15, 21, 30, 44, 55,
+ tzinfo=pytz.timezone('EST'))),
+ ('13 days after last memorial day at 12 seconds before 4pm',
+ datetime.datetime(2020, 6, 7, 15, 59, 48)),
+ (' 2 days before yesterday at 9am ',
+ datetime.datetime(2021, 6, 29, 9)),
+ ('-3 days before today',
+ datetime.datetime(2021, 7, 5)),
+ ('3 days before yesterday at midnight EST',
+ datetime.datetime(2021, 6, 28, tzinfo=pytz.timezone('EST')))
+]
+
+
class TestDateparseUtils(unittest.TestCase):
@uu.check_method_for_perf_regressions
dp = du.DateParser(
override_now_for_test_purposes = datetime.datetime(2021, 7, 2)
)
- parsable_expressions = [
- ('today',
- datetime.datetime(2021, 7, 2)),
- ('tomorrow',
- datetime.datetime(2021, 7, 3)),
- ('yesterday',
- datetime.datetime(2021, 7, 1)),
- ('21:30',
- datetime.datetime(2021, 7, 2, 21, 30, 0, 0)),
- ('12:01am',
- datetime.datetime(2021, 7, 2, 0, 1, 0, 0)),
- ('12:02p',
- datetime.datetime(2021, 7, 2, 12, 2, 0, 0)),
- ('0:03',
- datetime.datetime(2021, 7, 2, 0, 3, 0, 0)),
- ('last wednesday',
- datetime.datetime(2021, 6, 30)),
- ('this wed',
- datetime.datetime(2021, 7, 7)),
- ('next wed',
- datetime.datetime(2021, 7, 14)),
- ('this coming tues',
- datetime.datetime(2021, 7, 6)),
- ('this past monday',
- datetime.datetime(2021, 6, 28)),
- ('4 days ago',
- datetime.datetime(2021, 6, 28)),
- ('4 mondays ago',
- datetime.datetime(2021, 6, 7)),
- ('4 months ago',
- datetime.datetime(2021, 3, 2)),
- ('3 days back',
- datetime.datetime(2021, 6, 29)),
- ('13 weeks from now',
- datetime.datetime(2021, 10, 1)),
- ('1 year from now',
- datetime.datetime(2022, 7, 2)),
- ('4 weeks from now',
- datetime.datetime(2021, 7, 30)),
- ('3 saturdays ago',
- datetime.datetime(2021, 6, 12)),
- ('4 months from today',
- datetime.datetime(2021, 11, 2)),
- ('4 years from yesterday',
- datetime.datetime(2025, 7, 1)),
- ('4 weeks from tomorrow',
- datetime.datetime(2021, 7, 31)),
- ('april 15, 2005',
- datetime.datetime(2005, 4, 15)),
- ('april 14',
- datetime.datetime(2021, 4, 14)),
- ('9:30am on last wednesday',
- datetime.datetime(2021, 6, 30, 9, 30)),
- ('2005/apr/15',
- datetime.datetime(2005, 4, 15)),
- ('2005 apr 15',
- datetime.datetime(2005, 4, 15)),
- ('the 1st wednesday in may',
- datetime.datetime(2021, 5, 5)),
- ('last sun of june',
- datetime.datetime(2021, 6, 27)),
- ('this Easter',
- datetime.datetime(2021, 4, 4)),
- ('last christmas',
- datetime.datetime(2020, 12, 25)),
- ('last Xmas',
- datetime.datetime(2020, 12, 25)),
- ('xmas, 1999',
- datetime.datetime(1999, 12, 25)),
- ('next mlk day',
- datetime.datetime(2022, 1, 17)),
- ('Halloween, 2020',
- datetime.datetime(2020, 10, 31)),
- ('5 work days after independence day',
- datetime.datetime(2021, 7, 12)),
- ('50 working days from last wed',
- datetime.datetime(2021, 9, 10)),
- ('25 working days before columbus day',
- datetime.datetime(2021, 9, 3)),
- ('today +1 week',
- datetime.datetime(2021, 7, 9)),
- ('sunday -3 weeks',
- datetime.datetime(2021, 6, 13)),
- ('4 weeks before xmas, 1999',
- datetime.datetime(1999, 11, 27)),
- ('3 days before new years eve, 2000',
- datetime.datetime(2000, 12, 28)),
- ('july 4th',
- datetime.datetime(2021, 7, 4)),
- ('the ides of march',
- datetime.datetime(2021, 3, 15)),
- ('the nones of april',
- datetime.datetime(2021, 4, 5)),
- ('the kalends of may',
- datetime.datetime(2021, 5, 1)),
- ('9/11/2001',
- datetime.datetime(2001, 9, 11)),
- ('4 sundays before veterans\' day',
- datetime.datetime(2021, 10, 17)),
- ('xmas eve',
- datetime.datetime(2021, 12, 24)),
- ('this friday at 5pm',
- datetime.datetime(2021, 7, 9, 17, 0, 0)),
- ('presidents day',
- datetime.datetime(2021, 2, 15)),
- ('memorial day, 1921',
- datetime.datetime(1921, 5, 30)),
- ('today -4 wednesdays',
- datetime.datetime(2021, 6, 9)),
- ('thanksgiving',
- datetime.datetime(2021, 11, 25)),
- ('2 sun in jun',
- datetime.datetime(2021, 6, 13)),
- ('easter -40 days',
- datetime.datetime(2021, 2, 23)),
- ('easter +39 days',
- datetime.datetime(2021, 5, 13)),
- ('1st tuesday in nov, 2024',
- datetime.datetime(2024, 11, 5)),
- ('2 days before last xmas at 3:14:15.92a',
- datetime.datetime(2020, 12, 23, 3, 14, 15, 92)),
- ('3 weeks after xmas, 1995 at midday',
- datetime.datetime(1996, 1, 15, 12, 0, 0)),
- ('4 months before easter, 1992 at midnight',
- datetime.datetime(1991, 12, 19)),
- ('5 months before halloween, 1995 at noon',
- datetime.datetime(1995, 5, 31, 12)),
- ('4 days before last wednesday',
- datetime.datetime(2021, 6, 26)),
- ('44 months after today',
- datetime.datetime(2025, 3, 2)),
- ('44 years before today',
- datetime.datetime(1977, 7, 2)),
- ('44 weeks ago',
- datetime.datetime(2020, 8, 28)),
- ('15 minutes to 3am',
- datetime.datetime(2021, 7, 2, 2, 45)),
- ('quarter past 4pm',
- datetime.datetime(2021, 7, 2, 16, 15)),
- ('half past 9',
- datetime.datetime(2021, 7, 2, 9, 30)),
- ('4 seconds to midnight',
- datetime.datetime(2021, 7, 1, 23, 59, 56)),
- ('4 seconds to midnight, tomorrow',
- datetime.datetime(2021, 7, 2, 23, 59, 56)),
- ('2021/apr/15T21:30:44.55',
- datetime.datetime(2021, 4, 15, 21, 30, 44, 55)),
- ('2021/apr/15 at 21:30:44.55',
- datetime.datetime(2021, 4, 15, 21, 30, 44, 55)),
- ('2021/4/15 at 21:30:44.55',
- datetime.datetime(2021, 4, 15, 21, 30, 44, 55)),
- ('2021/04/15 at 21:30:44.55',
- datetime.datetime(2021, 4, 15, 21, 30, 44, 55)),
- ('2021/04/15 at 21:30:44.55Z',
- datetime.datetime(2021, 4, 15, 21, 30, 44, 55,
- tzinfo=pytz.timezone('UTC'))),
- ('2021/04/15 at 21:30:44.55EST',
- datetime.datetime(2021, 4, 15, 21, 30, 44, 55,
- tzinfo=pytz.timezone('EST'))),
- ('13 days after last memorial day at 12 seconds before 4pm',
- datetime.datetime(2020, 6, 7, 15, 59, 48)),
- (' 2 days before yesterday at 9am ',
- datetime.datetime(2021, 6, 29, 9)),
- ('-3 days before today',
- datetime.datetime(2021, 7, 5)),
- ('3 days before yesterday at midnight EST',
- datetime.datetime(2021, 6, 28, tzinfo=pytz.timezone('EST'))),
- ]
for (txt, expected_dt) in parsable_expressions:
try:
- print(f'> {txt}')
+ actual_dt = dp.parse(txt)
+ self.assertIsNotNone(actual_dt)
+ self.assertEqual(
+ actual_dt,
+ expected_dt,
+ f'"{txt}", got "{actual_dt}" while expecting "{expected_dt}"'
+ )
+ except du.ParseException:
+ self.fail(f'Expected "{txt}" to parse successfully.')
+
+ def test_whitespace_handling(self):
+ dp = du.DateParser(
+ override_now_for_test_purposes = datetime.datetime(2021, 7, 2)
+ )
+
+ for (txt, expected_dt) in parsable_expressions:
+ try:
+ txt = f' {txt} '
+ i = random.randint(2, 5)
+ replacement = ' ' * i
+ txt = re.sub('\s', replacement, txt)
actual_dt = dp.parse(txt)
self.assertIsNotNone(actual_dt)
self.assertEqual(