♻ Use monotonic_time for relative times

Timeouts, durations and such shouldn't depend on the non-monotonic
system clock but instead use a monotonic time source.
This commit is contained in:
Gina Häußge committed 2019-03-12 16:03:58 +01:00
1 parent 93ab7bb089
commit 76ad332287
12 files changed
+68 -70

No files matched your search

+3 -2
View File
@@ -34,6 +34,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
import time
import yaml
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
throttle_callback = None
@@ -52,7 +53,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = time.time()
start_time = monotonic_time()
progress_callback = None
if progress:
@@ -68,7 +69,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
max_extruders=maxt,
g90_extruder=g90_extruder)
click.echo("DONE:{}s".format(time.time() - start_time))
click.echo("DONE:{}s".format(monotonic_time() - start_time))
click.echo("RESULTS:")
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
+2 -3
View File
@@ -351,7 +351,7 @@ class FileManager(object):
display=display, links=links, allow_overwrite=True,
printer_profile=printer_profile, analysis=_analysis)
end_time = time.time()
end_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
@@ -376,8 +376,7 @@ class FileManager(object):
slicer = self._slicing_manager.get_slicer(slicer_name)
import time
start_time = time.time()
start_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
"stl_location": source_location,
"gcode": dest_path,
+3 -2
View File
@@ -18,6 +18,7 @@ import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import monotonic_time
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
@@ -249,7 +250,7 @@ class AbstractAnalysisQueue(object):
self._current_progress = 0
try:
start_time = time.time()
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
"path": entry.path,
@@ -262,7 +263,7 @@ class AbstractAnalysisQueue(object):
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, time.time() - start_time))
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
self._finished_callback(self._current, result)
finally:
self._current = None
@@ -22,7 +22,7 @@ from collections import OrderedDict
from octoprint.server import admin_permission
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.util import utmify
from octoprint.util import utmify, monotonic_time
from flask_babel import gettext
from octoprint import __version__ as OCTOPRINT_VERSION
@@ -351,10 +351,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
url = config["url"]
try:
start = time.time()
start = monotonic_time()
r = requests.get(url, timeout=30)
r.raise_for_status()
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start))
except Exception as e:
self._logger.exception(
u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e)))
+2 -3
View File
@@ -562,9 +562,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
"""
import socket
import time
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > time.time():
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > octoprint.util.monotonic_time():
# we just sent an alive, no need to send another one now
return
@@ -603,7 +602,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
except:
pass
self._ssdp_last_notify = time.time()
self._ssdp_last_notify = octoprint.util.monotonic_time()
def _ssdp_monitor(self, timeout=5):
"""
@@ -18,7 +18,7 @@ from serial import SerialTimeoutException
from octoprint.settings import settings
from octoprint.plugin import plugin_manager
from octoprint.util import RepeatedTimer
from octoprint.util import RepeatedTimer, monotonic_time
class VirtualPrinter(object):
command_regex = re.compile("^([GMTF])(\d+)")
@@ -84,7 +84,7 @@ class VirtualPrinter(object):
self.targetTemp = [0.0] * self.temperatureCount
self.bedTemp = self._ambient_temperature
self.bedTargetTemp = 0.0
self.lastTempAt = time.time()
self.lastTempAt = monotonic_time()
self._relative = True
self._lastX = 0.0
@@ -264,7 +264,7 @@ class VirtualPrinter(object):
pass
def _processIncoming(self):
next_wait_timeout = time.time() + self._waitInterval
next_wait_timeout = monotonic_time() + self._waitInterval
buf = ""
while self.incoming is not None and not self._killed:
self._simulateTemps()
@@ -277,9 +277,9 @@ class VirtualPrinter(object):
data = self.incoming.get(timeout=0.01)
self.incoming.task_done()
except queue.Empty:
if self._sendWait and time.time() > next_wait_timeout:
if self._sendWait and monotonic_time() > next_wait_timeout:
self._send("wait")
next_wait_timeout = time.time() + self._waitInterval
next_wait_timeout = monotonic_time() + self._waitInterval
continue
buf += data
@@ -289,7 +289,7 @@ class VirtualPrinter(object):
else:
continue
next_wait_timeout = time.time() + self._waitInterval
next_wait_timeout = monotonic_time() + self._waitInterval
if data is None:
continue
@@ -640,8 +640,8 @@ class VirtualPrinter(object):
_timeout = float(matchS.group(1))
if self._sendBusy and self._busyInterval > 0:
until = time.time() + _timeout
while time.time() < until:
until = monotonic_time() + _timeout
while monotonic_time() < until:
time.sleep(self._busyInterval)
self._send("busy:processing")
else:
@@ -653,8 +653,8 @@ class VirtualPrinter(object):
timeout = 60
if self._sendBusy and self._busyInterval > 0:
until = time.time() + timeout
while time.time() < until:
until = monotonic_time() + timeout
while monotonic_time() < until:
time.sleep(self._busyInterval)
self._send("busy:processing")
else:
@@ -1199,7 +1199,7 @@ class VirtualPrinter(object):
def _waitForHeatup(self, heater, only_wait_if_higher):
delta = 1
delay = 1
last_busy = time.time()
last_busy = monotonic_time()
self._heatingUp = True
try:
@@ -1216,9 +1216,9 @@ class VirtualPrinter(object):
while not self._killed and self._heatingUp and test():
self._simulateTemps(delta=delta)
self._output(output())
if self._sendBusy and time.time() - last_busy >= self._busyInterval:
if self._sendBusy and monotonic_time() - last_busy >= self._busyInterval:
self._output("echo:busy: processing")
last_busy = time.time()
last_busy = monotonic_time()
time.sleep(delay)
except AttributeError:
if self.outgoing is not None:
@@ -1234,8 +1234,8 @@ class VirtualPrinter(object):
os.remove(f)
def _simulateTemps(self, delta=0.5):
timeDiff = self.lastTempAt - time.time()
self.lastTempAt = time.time()
timeDiff = self.lastTempAt - monotonic_time()
self.lastTempAt = monotonic_time()
def simulate(actual, target, ambient):
if target > 0 and abs(actual - target) > delta:
@@ -1409,9 +1409,9 @@ class CharCountingQueue(queue.Queue):
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = time.time() + timeout
endtime = monotonic_time() + timeout
while not self._will_it_fit(item):
remaining = endtime - time.time()
remaining = endtime - monotonic_time()
if remaining <= 0.0:
raise queue.Full
self.not_full.wait(remaining)
+4 -3
View File
@@ -29,6 +29,7 @@ from octoprint.settings import settings
from octoprint.util import comm as comm
from octoprint.util import InvariantContainer
from octoprint.util import to_unicode
from octoprint.util import monotonic_time
class Printer(PrinterInterface, comm.MachineComPrintCallback):
@@ -1379,7 +1380,7 @@ class StateMonitor(object):
self._state_lock = threading.Lock()
self._progress_lock = threading.Lock()
self._last_update = time.time()
self._last_update = monotonic_time()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
@@ -1443,7 +1444,7 @@ class StateMonitor(object):
while True:
self._change_event.wait()
now = time.time()
now = monotonic_time()
delta = now - self._last_update
additional_wait_time = self._interval - delta
if additional_wait_time > 0:
@@ -1452,7 +1453,7 @@ class StateMonitor(object):
with self._state_lock:
data = self.get_current_data()
self._update_callback(data)
self._last_update = time.time()
self._last_update = monotonic_time()
self._change_event.clear()
except:
logging.getLogger(__name__).exception("Looks like something crashed inside the state update worker. Please report this on the OctoPrint issue tracker (make sure to include logs!)")
+2 -2
View File
@@ -1097,7 +1097,7 @@ class Server(object):
kwargs.update(additional_request_data)
try:
start = time.time()
start = octoprint.util.monotonic_time()
if plugin:
logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs))
else:
@@ -1111,7 +1111,7 @@ class Server(object):
builder = EnvironBuilder(**kwargs)
app(builder.get_environ(), lambda *a, **kw: None)
logger.info("... done in {:.2f}s".format(time.time() - start))
logger.info("... done in {:.2f}s".format(octoprint.util.monotonic_time() - start))
except:
logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
-3
View File
@@ -377,7 +377,6 @@ class Timelapse(object):
self._capture_success = 0
self._post_roll = post_roll
self._post_roll_start = None
self._on_post_roll_done = None
self._capture_dir = settings().getBaseFolder("timelapse_tmp")
@@ -528,7 +527,6 @@ class Timelapse(object):
dict(postroll_duration=self.calculate_post_roll(),
postroll_length=self.post_roll,
postroll_fps=self.fps))
self._post_roll_start = time.time()
if do_create_movie:
self._on_post_roll_done = create_wait_for_captures(reset_and_create)
else:
@@ -536,7 +534,6 @@ class Timelapse(object):
self.process_post_roll()
else:
# no post roll? perfect, render
self._post_roll_start = None
if do_create_movie:
wait_for_captures(reset_and_create)
else:
+3 -4
View File
@@ -20,7 +20,7 @@ from builtins import range, bytes
from octoprint.settings import settings
from octoprint.util import atomic_write, to_bytes, deprecated
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
class UserManager(object):
valid_roles = ["user", "admin"]
@@ -121,11 +121,10 @@ class UserManager(object):
self._logger.exception("Error while calling logout callback {!r}".format(callback))
def _cleanup_sessions(self):
import time
for session, user in self._session_users_by_session.items():
if not isinstance(user, SessionUser):
continue
if user.created + (24 * 60 * 60) < time.time():
if user.created + (24 * 60 * 60) < monotonic_time():
self.logout_user(user)
@staticmethod
@@ -540,7 +539,7 @@ class SessionUser(wrapt.ObjectProxy):
import time
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
self._self_session = "".join(random.choice(chars) for _ in range(10))
self._self_created = time.time()
self._self_created = monotonic_time()
def asDict(self):
result = self.__wrapped__.asDict()
+26 -25
View File
@@ -37,7 +37,8 @@ from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks, ResettableTimer
to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks, ResettableTimer, \
monotonic_time
try:
import _winreg
@@ -755,7 +756,7 @@ class MachineCom(object):
if self._currentFile is None or self._currentFile.getStartTime() is None:
return None
else:
return time.time() - self._currentFile.getStartTime() - self._pauseWaitTimeLost
return monotonic_time() - self._currentFile.getStartTime() - self._pauseWaitTimeLost
def getCleanedPrintTime(self):
printTime = self.getPrintTime()
@@ -872,8 +873,8 @@ class MachineCom(object):
self.sendGcodeScript("beforePrinterDisconnected")
if wait:
if timeout is not None:
stop = time.time() + timeout
while (self._command_queue.unfinished_tasks or self._send_queue.unfinished_tasks) and time.time() < stop:
stop = monotonic_time() + timeout
while (self._command_queue.unfinished_tasks or self._send_queue.unfinished_tasks) and monotonic_time() < stop:
time.sleep(0.1)
else:
self._command_queue.join()
@@ -1024,7 +1025,7 @@ class MachineCom(object):
if self._currentFile is None:
raise ValueError("No file selected for printing")
self._heatupWaitStartTime = None if not self._heating else time.time()
self._heatupWaitStartTime = None if not self._heating else monotonic_time()
self._heatupWaitTimeLost = 0.0
self._pauseWaitStartTime = 0
self._pauseWaitTimeLost = 0.0
@@ -1301,7 +1302,7 @@ class MachineCom(object):
with self._jobLock:
if not pause and self._state in (self.STATE_PAUSED, self.STATE_PAUSING):
if self._pauseWaitStartTime:
self._pauseWaitTimeLost = self._pauseWaitTimeLost + (time.time() - self._pauseWaitStartTime)
self._pauseWaitTimeLost = self._pauseWaitTimeLost + (monotonic_time() - self._pauseWaitStartTime)
self._pauseWaitStartTime = None
self._changeState(self.STATE_RESUMING)
@@ -1327,7 +1328,7 @@ class MachineCom(object):
elif pause and self._state in (self.STATE_PRINTING, self.STATE_STARTING, self.STATE_RESUMING):
if not self._pauseWaitStartTime:
self._pauseWaitStartTime = time.time()
self._pauseWaitStartTime = monotonic_time()
self._changeState(self.STATE_PAUSING)
if self.isSdFileSelected() and local_handling:
@@ -1555,7 +1556,7 @@ class MachineCom(object):
if line is None:
break
now = time.time()
now = monotonic_time()
if line.strip() is not "":
self._consecutive_timeouts = 0
@@ -1768,7 +1769,7 @@ class MachineCom(object):
and self._firmware_info_received:
self._logger.info("Externally triggered heatup detected")
self._heating = True
self._heatupWaitStartTime = time.time()
self._heatupWaitStartTime = monotonic_time()
self._processTemperatures(line)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed)
@@ -2054,7 +2055,7 @@ class MachineCom(object):
### Baudrate detection
if self._state == self.STATE_DETECT_BAUDRATE:
if line == '' or time.time() > self._timeout:
if line == '' or monotonic_time() > self._timeout:
self._perform_baudrate_detection_step()
elif 'start' in line or line.startswith('ok'):
self._onConnected()
@@ -2071,7 +2072,7 @@ class MachineCom(object):
# if it was a wait we probably missed an ok, so let's simulate that now
self._handle_ok()
self._onConnected()
elif time.time() > self._timeout:
elif monotonic_time() > self._timeout:
self._log("There was a timeout while trying to connect to the printer")
self.close(wait=False)
@@ -2213,7 +2214,7 @@ class MachineCom(object):
if self._baudrateDetectRetry > 0:
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = time.time() + timeout
self._timeout = monotonic_time() + timeout
self._log("Baudrate test retry #{}".format(5 - self._baudrateDetectRetry))
self._baudrateDetectRetry -= 1
@@ -2226,7 +2227,7 @@ class MachineCom(object):
self._serial.baudrate = baudrate
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = time.time() + timeout
self._timeout = monotonic_time() + timeout
self._log("Trying baudrate: {}".format(baudrate))
self._baudrateDetectRetry = 4
@@ -2243,7 +2244,7 @@ class MachineCom(object):
def _finish_heatup(self):
if self._heating:
if self._heatupWaitStartTime:
self._heatupWaitTimeLost = self._heatupWaitTimeLost + (time.time() - self._heatupWaitStartTime)
self._heatupWaitTimeLost = self._heatupWaitTimeLost + (monotonic_time() - self._heatupWaitStartTime)
self._heatupWaitStartTime = None
self._heating = False
@@ -2460,7 +2461,7 @@ class MachineCom(object):
return max(comm_timeout, temperature_timeout + 1)
def _get_new_communication_timeout(self):
return time.time() + self._get_communication_timeout_interval()
return monotonic_time() + self._get_communication_timeout_interval()
def _send_from_command_queue(self):
# We loop here to make sure that if we do NOT send the first command
@@ -2850,7 +2851,7 @@ class MachineCom(object):
#
# this it to prevent the log from getting flooded for extremely bad communication issues
if self._log_resends:
now = time.time()
now = monotonic_time()
new_rate_window = self._log_resends_rate_start is None or self._log_resends_rate_start + self._log_resends_rate_frame < now
in_rate = self._log_resends_rate_count < self._log_resends_max
@@ -3036,7 +3037,7 @@ class MachineCom(object):
break
# sleep if we are dwelling
now = time.time()
now = monotonic_time()
if self._blockWhileDwelling and self._dwelling_until and now < self._dwelling_until:
time.sleep(self._dwelling_until - now)
self._dwelling_until = False
@@ -3486,19 +3487,19 @@ class MachineCom(object):
pass
def _gcode_M109_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self._heatupWaitStartTime = time.time()
self._heatupWaitStartTime = monotonic_time()
self._long_running_command = True
self._heating = True
self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M190_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self._heatupWaitStartTime = time.time()
self._heatupWaitStartTime = monotonic_time()
self._long_running_command = True
self._heating = True
self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M116_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
self._heatupWaitStartTime = time.time()
self._heatupWaitStartTime = monotonic_time()
self._long_running_command = True
self._heating = True
@@ -3597,7 +3598,7 @@ class MachineCom(object):
_timeout = float(s_match.group("value"))
self._timeout = self._get_new_communication_timeout() + _timeout
self._dwelling_until = time.time() + _timeout
self._dwelling_until = monotonic_time() + _timeout
def _emergency_force_send(self, cmd, message, gcode=None, *args, **kwargs):
# only jump the queue with our command if the EMERGENCY_PARSER capability is available
@@ -3787,7 +3788,7 @@ class PrintingFileInformation(object):
"""
Marks the print job as started and remembers the start time.
"""
self._start_time = time.time()
self._start_time = monotonic_time()
self._done = False
def close(self):
@@ -3937,7 +3938,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
return process_gcode_line(line, offsets=offsets, current_tool=current_tool)
def _report_stats(self):
duration = time.time() - self._start_time
duration = monotonic_time() - self._start_time
self._logger.info("Finished in {:.3f} s.".format(duration))
pass
@@ -3949,7 +3950,7 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
def start(self):
PrintingGcodeFileInformation.start(self)
self._start_time = time.time()
self._start_time = monotonic_time()
def getLocalFilename(self):
return self._localFilename
@@ -3961,7 +3962,7 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
return process_gcode_line(line)
def _report_stats(self):
duration = time.time() - self._start_time
duration = monotonic_time() - self._start_time
read_lines = self._read_lines
if duration > 0 and read_lines > 0:
stats = dict(lines=read_lines,
+3 -3
View File
@@ -25,12 +25,12 @@ def duration_log(context=None, log=None):
import logging
log = logging.getLogger(__name__).debug
import time
start = time.time()
import octoprint.util
start = octoprint.util.monotonic_time()
try:
yield
finally:
end = time.time()
end = octoprint.util.monotonic_time()
duration = end - start
if context: