Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,9 @@
#
# # File System Watcher
# You can configure the pipeline builder to watch for changes to the currently loaded device
# detection data file, and to replace the file currently in use with the new one. This is
# useful, for example, if you wish to download and update the device detection file "manually" -
# detection data file, and to replace the data currently in use with the new file when the new
# file was published later. This is useful, for example, if you wish to download and update the
# device detection file "manually" -
# i.e. you would download it then drop it into place with the same path as the currently loaded
# file. That location is checked periodically (by default every 30 mins) and this frequency can be
# configured.
Expand Down Expand Up @@ -399,7 +400,8 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non
pipeline = DeviceDetectionPipelineBuilder(
# specify the filename for the data file. When using update on start-up
# the file need not exist, but the directory it is in must exist.
# Any file that is present is overwritten. Because the file will be
# A file that is present is overwritten by a download published
# later. Because the file may be
# overwritten the pipeline must be configured to copy the supplied
# file to a temporary file (create_temp_copy parameter == True).
data_file_path = data_file,
Expand All @@ -417,8 +419,8 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non
update_on_start = True,
# Enable automatic updates once the pipeline has started
auto_update = True,
# Watch the data file on disk and refresh the engine
# as soon as that file is updated.
# Watch the data file on disk and refresh the engine as
# soon as a file published later is put in its place.
file_system_watcher=True,
# The product the 51Degrees distributor is asked for, which
# is named only when this example is given one. With none
Expand All @@ -438,15 +440,15 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non

if update_event.status == UpdateStatus.AUTO_UPDATE_SUCCESS:

output("Modifying downloaded file to trigger reload - please wait for that"
output("Modifying downloaded file to trigger a check - please wait for that"
" to complete")

# wait for the dataUpdateService to notify us that it has updated
update_event.clear()

# it's the same file but changing the file metadata will trigger reload,
# demonstrating that if you download a new file and replace the
# existing one, then it will be loaded
# it's the same file, so changing its time triggers a check that
# reports AUTO_UPDATE_NOT_NEEDED. A file put in place of the
# existing one is loaded only when it was published later.
now = datetime.now().timestamp()
try:
os.utime(data_file, (now, now))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
# *********************************************************************

from __future__ import absolute_import
import datetime
import multiprocessing
import os.path

Expand Down Expand Up @@ -372,6 +373,26 @@ def init_engine(self):
for key, property in self.get_metric_properties().items():
self.properties[key] = property

def get_date_published_from_file(self, path):

"""!
Reads the date a data file was published from its header, without
loading the file. The data file update service loads a watched or
downloaded file only when this date is later than that of the data
in use.
@type path: string
@param path: path to the data file
@rtype: date
@return: the date the data file was published
@raise RuntimeError: when the file cannot be opened, is shorter than
its header, holds no valid date, or is not a data file this engine
reads
"""

published = EngineHashSwig.getPublishedTimeFromFile(path)
return datetime.date(
published.getYear(), published.getMonth(), published.getDay())

def read_evidence_keys(self):

"""!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def test_the_watcher_runs_with_no_licence_key(self):
self.assertFalse(watched.auto_update)
self.assertFalse(watched.update_on_start)

def test_a_replaced_file_is_loaded_with_no_licence_key(self):
def test_a_replaced_file_is_checked_with_no_licence_key(self):
service = DataFileUpdateService()
service.FILE_SYSTEM_WATCHER_INTERVAL_SECONDS = \
WATCHER_INTERVAL_SECONDS
Expand All @@ -95,7 +95,9 @@ def on_complete(status, watched):
self.assertTrue(
reloaded.wait(RELOAD_WAIT_SECONDS),
"The watcher did not report the replaced file.")
self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], statuses)
# The copy was published on the same day as the data in use, so it
# is not loaded, whatever its time, and the engine keeps its data.
self.assertEqual([UpdateStatus.AUTO_UPDATE_NOT_NEEDED], statuses)

with pipeline.create_flowdata() as flowdata:
flowdata.evidence.add("header.user-agent", mobile_ua)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@
#
# ## Filesystem watcher
# Configure the pipeline to watch the loaded data file on disk and reload it
# when it changes (file_system_watcher=True). Useful if you download files
# yourself and drop them into place.
# when a file published later is put in its place (file_system_watcher=True).
# Useful if you download files yourself and drop them into place.
#
# ## Daily auto-update
# Each data file records when the next file is expected. With auto_update
Expand Down Expand Up @@ -266,8 +266,9 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non
# Build the pipeline, configuring it for automatic updates.
pipeline = IpIntelligencePipelineBuilder(
# The file need not exist when using update on start-up, but its
# directory must. Any file present is overwritten, so the engine
# is configured to use a temporary copy.
# directory must. A file present is overwritten by a download
# published later, so the engine is configured to use a temporary
# copy.
data_file_path = data_file,
create_temp_data_copy = True,
# The Enterprise data file is large, so the LowMemory profile
Expand Down Expand Up @@ -302,12 +303,13 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non
output(f"Update on start-up complete - status - {update_event.status}")

if update_event.status == UpdateStatus.AUTO_UPDATE_SUCCESS:
output("Modifying downloaded file to trigger reload - please wait "
output("Modifying downloaded file to trigger a check - please wait "
"for that to complete")
update_event.clear()

# Touching the file metadata triggers the filesystem watcher,
# demonstrating reload when a new file is dropped into place.
# Touching the file triggers the filesystem watcher. It is the
# same file, so the check reports AUTO_UPDATE_NOT_NEEDED, as only
# a file published later is loaded.
now = datetime.now().timestamp()
try:
os.utime(data_file, (now, now))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
# *********************************************************************

from __future__ import absolute_import
import datetime
import multiprocessing
import os.path

Expand Down Expand Up @@ -309,6 +310,26 @@ def init_engine(self):
for metric_property_name, metric_property in self.get_metric_properties().items():
self.properties[metric_property_name] = metric_property

def get_date_published_from_file(self, path):

"""!
Reads the date a data file was published from its header, without
loading the file. The data file update service loads a watched or
downloaded file only when this date is later than that of the data
in use.
@type path: string
@param path: path to the data file
@rtype: date
@return: the date the data file was published
@raise RuntimeError: when the file cannot be opened, is shorter than
its header, holds no valid date, or is not a data file this engine
reads
"""

published = EngineIpiSwig.getPublishedTimeFromFile(path)
return datetime.date(
published.getYear(), published.getMonth(), published.getDay())

def read_evidence_keys(self):

"""!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def test_the_watcher_runs_with_no_licence_key(self):
self.assertFalse(watched.auto_update)
self.assertFalse(watched.update_on_start)

def test_a_changed_file_is_loaded_with_no_licence_key(self):
def test_a_changed_file_is_checked_with_no_licence_key(self):
service = DataFileUpdateService()
service.FILE_SYSTEM_WATCHER_INTERVAL_SECONDS = \
WATCHER_INTERVAL_SECONDS
Expand All @@ -93,7 +93,9 @@ def on_complete(status, watched):
self.assertTrue(
reloaded.wait(RELOAD_WAIT_SECONDS),
"The watcher did not report the changed file.")
self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], statuses)
# The file was published on the same day as the data in use, so it
# is not loaded, whatever its time, and the engine keeps its data.
self.assertEqual([UpdateStatus.AUTO_UPDATE_NOT_NEEDED], statuses)

with pipeline.create_flowdata() as flowdata:
flowdata.evidence.add("query.client-ip", "8.8.8.8")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def __init__(self, flow_element, identifier, update_url_params = None, data = No
@type auto_update: bool
@param: auto_update: whether to automatically update the datafile when required
@type file_system_watcher: bool
@param file_system_watcher: whether to check the datafile's path for changes and update the connected FlowElement's data automatically when the file is changed in the operating system
@param file_system_watcher: whether to check the datafile's path for changes and update the connected FlowElement's data automatically when the file is changed in the operating system. When the FlowElement has a get_date_published_from_file method, a changed or downloaded file is loaded only when the date it gives for the file is later than get_date_published gives for the data in use
@type polling_interval: int
@param polling_interval: How often to poll for updates to the datafile (minutes)
@type update_time_maximum_randomisation : int
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,15 @@ def _update_data_file(self, data_file):
# write that failed leaves it with the data it already had and
# the update ends there, as it does in .NET and
# 51degrees-node.
self._write_data_file(data_file, data)
if self._published_date_reader(data_file) is None:
self._write_data_file(data_file, data)
else:
# A download that is not newer than the data in use replaces
# neither the data file nor the engine's data.
staged = self._stage_data_file(data_file, data, True)
if not self._is_newer_or_discard(data_file, staged):
return UpdateStatus.AUTO_UPDATE_NOT_NEEDED
self._replace_data_file(data_file, staged)

else:

Expand Down Expand Up @@ -604,6 +612,17 @@ def _write_data_file(self, data_file, data):
# when the data file asks for one. A failure raises a
# DataUpdateException with the message and status of its row of the
# errors table, and leaves the file on disk as it was.
self._replace_data_file(
data_file, self._stage_data_file(data_file, data, False))

def _stage_data_file(self, data_file, data, apart):
# Write new data to the file that replaces the data file, and answer
# its path. That is a temporary copy when the data file asks for
# one. Otherwise it is a file beside the data file when the data
# must be kept apart until it is known to be newer, and the data
# file itself when not. A failure raises a DataUpdateException with
# the message and status of its row of the errors table, and leaves
# the data file as it was.
if data_file.create_temp_copy:
if not getattr(data_file, "temp_directory", None):
raise DataUpdateException(
Expand All @@ -614,6 +633,10 @@ def _write_data_file(self, data_file, data):
filename = os.path.join(
data_file.temp_directory,
data_file.identifier + str(time.time()))
elif apart:
filename = os.path.join(
os.path.dirname(data_file.path),
data_file.identifier + str(time.time()))
else:
filename = data_file.path

Expand All @@ -634,8 +657,13 @@ def _write_data_file(self, data_file, data):
raise DataUpdateException(
self._unhandled_message(data_file),
UpdateStatus.AUTO_UPDATE_UNKNOWN_ERROR) from e
return filename

if data_file.create_temp_copy:
def _replace_data_file(self, data_file, filename):
# Put the file written by _stage_data_file in place of the data
# file. A failure raises a DataUpdateException with the message and
# status of its row of the errors table.
if filename != data_file.path:
try:
shutil.move(filename, data_file.path)
except (OSError, shutil.Error) as e:
Expand All @@ -653,6 +681,91 @@ def _write_data_file(self, data_file, data):
except OSError:
pass

@staticmethod
def _published_date_reader(data_file):
# The method of the data file's engine that reads the published date
# in a data file's header, or None when the engine has none, and a
# new file is then loaded without comparing dates.
return getattr(
getattr(data_file, "flow_element", None),
"get_date_published_from_file", None)

@staticmethod
def _published_day(moment):
# The day of a published date, in UTC for a time with a zone. A data
# file's header holds a date with no time or zone, so dates are
# compared by the day. None for anything that is not a date.
if isinstance(moment, datetime.datetime):
if moment.tzinfo is not None:
moment = moment.astimezone(datetime.timezone.utc)
return moment.date()
if isinstance(moment, datetime.date):
return moment
return None

def _is_newer(self, data_file, path):
# Whether the data file at the path was published on a later day
# than the data in use, by the date the engine reads in its header.
# A file is newer when the engine reads no date from it or no date
# is known for the data in use, so it is loaded as it was before
# dates could be read. A header that cannot be read raises a
# DataUpdateException as any other error.
read = self._published_date_reader(data_file)
if read is None:
return True
try:
published = self._published_day(read(path))
except Exception as e:
raise DataUpdateException(
self._unhandled_message(data_file),
UpdateStatus.AUTO_UPDATE_UNKNOWN_ERROR) from e
if published is None:
return True
in_use = self._published_day_in_use(data_file, read, path)
return in_use is None or published > in_use

def _published_day_in_use(self, data_file, read, path):
# The day the data in use was published. Before the engine has
# loaded data, as at the update on start-up, it is the day the file
# already at the data file's path was published, which is loaded
# otherwise. None when neither is known, as when there is no file
# there or its header cannot be read.
try:
in_use = self._published_day(data_file.get_date_published())
except Exception:
in_use = None
if in_use is not None:
return in_use
local = getattr(data_file, "path", None)
if not local or local == path or not os.path.isfile(local):
return None
try:
return self._published_day(read(local))
except Exception:
return None

def _is_newer_or_discard(self, data_file, staged):
# Whether the file staged for a download is newer than the data in
# use. A staged file that is not, or whose header cannot be read, is
# deleted, so the data file is left as it was.
try:
newer = self._is_newer(data_file, staged)
except DataUpdateException:
self._discard(staged)
raise
if not newer:
self._discard(staged)
return newer

@staticmethod
def _discard(path):
# Delete a staged download that is not used. One that cannot be
# deleted is left, as it holds none of the data in use.
try:
os.remove(path)
except OSError:
pass

def _log_failed_check(self, data_file, error):
# A check or a watched change that failed is logged with the message
# of its row of the errors table and the error that caused it.
Expand Down Expand Up @@ -989,8 +1102,12 @@ def track_local_data_file_changes(self, data_file):
event. It is first opened for reading, waiting up to
WATCHED_FILE_WAIT_SECONDS for a copy still being made, and a file
that does not open is reported as AUTO_UPDATE_TIMEOUT without a log
entry. Otherwise the refresh takes the same route as the polling one,
so the attempt is logged, a failure carries the errors table's
entry. A file whose engine reads a published date in its header that
is not later than that of the data in use is not loaded, and is
reported as AUTO_UPDATE_NOT_NEEDED without a log entry. A header
that cannot be read is any other error, which is logged and
reported. Otherwise the refresh takes the same route as the polling
one, so the attempt is logged, a failure carries the errors table's
message and level, and the result is reported to the update complete
callbacks either way. The next check is scheduled whatever happens,
so that a later file is still picked up, until the data file is
Expand Down Expand Up @@ -1028,13 +1145,15 @@ def track_local_data_file_changes(self, data_file):
data_file.updating = True
try:
data_file.last_changed_time = changed_time
if self._wait_until_readable(data_file.path):
self._refresh(data_file)
status = UpdateStatus.AUTO_UPDATE_SUCCESS
else:
if not self._wait_until_readable(data_file.path):
# The errors table's row for a watched file that
# could not be opened is not logged.
status = UpdateStatus.AUTO_UPDATE_TIMEOUT
elif self._is_newer(data_file, data_file.path):
self._refresh(data_file)
status = UpdateStatus.AUTO_UPDATE_SUCCESS
else:
status = UpdateStatus.AUTO_UPDATE_NOT_NEEDED
except DataUpdateException as e:
self._log_failed_check(data_file, e)
status = e.status
Expand Down
Loading
Loading