update method _timestamp2filename() since it introduces timing precision problems

master
Emmanuelle Vargas-Gonzalez 2018-12-11 13:06:51 -05:00
parent c75a0857ec
commit ff098a19b1
1 changed files with 14 additions and 12 deletions

View File

@ -4,9 +4,10 @@ import errno
import io import io
import json import json
import os import os
import re
import stat import stat
import sys
import pytz
import six import six
from stix2 import v20, v21 from stix2 import v20, v21
@ -14,7 +15,7 @@ from stix2.base import _STIXBase
from stix2.core import parse from stix2.core import parse
from stix2.datastore import DataSink, DataSource, DataStoreMixin from stix2.datastore import DataSink, DataSource, DataStoreMixin
from stix2.datastore.filters import Filter, FilterSet, apply_common_filters from stix2.datastore.filters import Filter, FilterSet, apply_common_filters
from stix2.utils import get_type_from_id, is_marking from stix2.utils import format_datetime, get_type_from_id, is_marking
def _timestamp2filename(timestamp): def _timestamp2filename(timestamp):
@ -26,13 +27,10 @@ def _timestamp2filename(timestamp):
timestamp: A timestamp, as a datetime.datetime object. timestamp: A timestamp, as a datetime.datetime object.
""" """
# Different times will only produce different file names if all timestamps # The format_datetime will determine the correct level of precision.
# are in the same time zone! So if timestamp is timezone-aware convert ts = format_datetime(timestamp)
# to UTC just to be safe. If naive, just use as-is. ts = re.sub(r"[-T:\.Z ]", "", ts)
if timestamp.tzinfo is not None: return ts
timestamp = timestamp.astimezone(pytz.utc)
return timestamp.strftime("%Y%m%d%H%M%S%f")
class AuthSet(object): class AuthSet(object):
@ -544,9 +542,13 @@ class FileSystemSink(DataSink):
else: else:
stix_obj = v20.Bundle(stix_obj, allow_custom=self.allow_custom) stix_obj = v20.Bundle(stix_obj, allow_custom=self.allow_custom)
with io.open(file_path, 'w', encoding=encoding) as f: # TODO: Better handling of the overwriting case.
stix_obj = stix_obj.serialize(pretty=True, encoding=encoding, ensure_ascii=False) if os.path.isfile(file_path):
f.write(stix_obj) print("Attempted to overwrite file!", file_path, file=sys.stderr)
else:
with io.open(file_path, 'w', encoding=encoding) as f:
stix_obj = stix_obj.serialize(pretty=True, encoding=encoding, ensure_ascii=False)
f.write(stix_obj)
def add(self, stix_data=None, version=None): def add(self, stix_data=None, version=None):
"""Add STIX objects to file directory. """Add STIX objects to file directory.