Skip to content
Merged
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
1 change: 0 additions & 1 deletion pyensembl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@
"MissingGenomeFastaError",
"prune_genome_fastas",
"Locus",
"Exon",
"ensembl_grch36",
"ensembl_grch37",
"ensembl_grch38",
Expand Down
9 changes: 5 additions & 4 deletions pyensembl/annotation_genetic_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@

import datacache

from .common import file_fingerprint
from .database import (
DATABASE_SCHEMA_VERSION, GENETIC_CODE_SOURCE_TABLE, _file_state, annotation_db_filename,
DATABASE_SCHEMA_VERSION, GENETIC_CODE_SOURCE_TABLE, annotation_db_filename,
)
from .genetic_code import translation_table

Expand Down Expand Up @@ -51,12 +52,12 @@ def __init__(self, path, source, cache_directory):

def _file_state(self):
try:
source = _file_state(self.path)
source = file_fingerprint(self.path)
except FileNotFoundError as error:
raise FileNotFoundError(
"Cannot check source translation-table declarations: installed GTF is missing: " + self.path
) from error
return source, _file_state(self.index) if isfile(self.index) else None
return source, file_fingerprint(self.index) if isfile(self.index) else None

def _read_index(self):
if not isfile(self.index):
Expand All @@ -74,7 +75,7 @@ def _read_index(self):
if marker is None:
return None
row = connection.execute('SELECT state FROM "' + GENETIC_CODE_SOURCE_TABLE + '"').fetchone()
if row is None or json.loads(row[0]) != _file_state(self.path):
if row is None or json.loads(row[0]) != file_fingerprint(self.path):
return None
tables = []
for feature in ("transcript", "CDS"):
Expand Down
23 changes: 9 additions & 14 deletions pyensembl/annotation_integrity.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,15 @@

from filelock import FileLock

from .common import _atomic_output
from .common import _atomic_output, file_digest, parse_md5sum_manifest


class AnnotationIntegrityError(ValueError):
"""A provider checksum is missing, ambiguous, or differs from a pinned one."""


def file_md5(path):
digest = hashlib.md5(usedforsecurity=False)
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
return file_digest(path, "md5")


def source_checksum(url):
Expand All @@ -36,15 +32,14 @@ def source_checksum(url):
data = response.read(2 * 1024 * 1024 + 1)
if len(data) > 2 * 1024 * 1024:
raise AnnotationIntegrityError("Checksum manifest is unexpectedly large: " + manifest_url)
matches = []
for line in data.decode("utf-8").splitlines():
match = re.fullmatch(r"([a-fA-F0-9]{32})\s+\*?(?:\./)?([^/]+)", line.strip())
if match and match[2] == name:
matches.append(match[1].lower())
if len(matches) != 1:
raise AnnotationIntegrityError("Expected one checksum for %s in %s" % (name, manifest_url))
try:
md5 = parse_md5sum_manifest(data.decode("utf-8"), name)
except ValueError as error:
raise AnnotationIntegrityError(
"Expected one checksum for %s in %s" % (name, manifest_url)
) from error
return dict(
source=url, md5=matches[0], manifest_url=manifest_url,
source=url, md5=md5, manifest_url=manifest_url,
manifest_sha256=hashlib.sha256(data).hexdigest(),
retrieved_at=datetime.now(timezone.utc).isoformat(),
)
Expand Down
46 changes: 46 additions & 0 deletions pyensembl/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,58 @@

from contextlib import contextmanager
from functools import wraps
import hashlib
import os
from pathlib import Path
import pickle
import re
from uuid import uuid4


_MD5SUM_LINE = re.compile(r"([a-fA-F0-9]{32})\s+\*?(?:\./)?([^/]+)")


def _md5_hasher():
return hashlib.md5(usedforsecurity=False)


def file_digest(path, algorithm="sha256", *, opener=open):
"""Return the hex digest of a file's bytes."""
digest = _md5_hasher if algorithm == "md5" else algorithm
with opener(path, "rb") as handle:
return hashlib.file_digest(handle, digest).hexdigest()


def parse_md5sum_manifest(text, filename):
"""Return the unique lowercase MD5 hex digest for ``filename`` in ``text``."""
matches = []
for line in text.splitlines():
match = _MD5SUM_LINE.fullmatch(line.strip())
if match and match[2] == filename:
matches.append(match[1].lower())
if len(matches) != 1:
raise ValueError("Expected one checksum for %s" % filename)
return matches[0]


def file_fingerprint(path, *, ctime=True, include_dev=False):
"""Return JSON-compatible stat identity for a file.

Returns ``[size, mtime_ns, ctime_ns, ino]`` by default, omitting
``ctime_ns`` when ``ctime=False`` (for cache-owned files whose metadata
may change on chmod/chown) and appending ``st_dev`` when
``include_dev=True``.
"""
info = os.stat(path)
fields = [info.st_size, info.st_mtime_ns]
if ctime:
fields.append(info.st_ctime_ns)
fields.append(info.st_ino)
if include_dev:
fields.append(info.st_dev)
return fields


def _staging_path(directory, name):
# Dot files in cache directories are always staging files.
return Path(directory) / (".%s.%s.tmp" % (name, uuid4().hex))
Expand Down
28 changes: 7 additions & 21 deletions pyensembl/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

import datacache

from .common import memoize
from .common import file_digest, file_fingerprint, memoize
from .normalization import normalize_chromosome, normalize_strand
from .locus import Locus
from .versioned_ids import _split_ens_version, match_version
Expand Down Expand Up @@ -62,17 +62,11 @@ def report(stage, completed, total):
yield report


def _file_state(path):
"""File identity that changes for ordinary in-place edits and replacements."""
stat = os.stat(path)
return [stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns, stat.st_ino]


def _source_state(gtf_path, source):
state = {"source": source, "gtf": _file_state(gtf_path)}
state = {"source": source, "gtf": file_fingerprint(gtf_path)}
if "://" not in source:
try:
state["original"] = _file_state(source)
state["original"] = file_fingerprint(source)
except FileNotFoundError:
if os.path.abspath(gtf_path) == source:
raise
Expand All @@ -81,14 +75,6 @@ def _source_state(gtf_path, source):
return state


def _source_digest(path):
digest = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()


def _stored_source(connection):
try:
row = connection.execute(
Expand Down Expand Up @@ -122,7 +108,7 @@ def _source_matches(connection, gtf_path, source, verify_hash=False):
if not verify_hash:
return True
try:
return _source_digest(gtf_path) == sha256
return file_digest(gtf_path) == sha256
except OSError:
return False

Expand Down Expand Up @@ -384,7 +370,7 @@ def create(self, overwrite=False, show_progress=False):
datacache.ensure_dir(self.cache_directory_path)
local_source = "://" not in self.source
source_before = _source_state(self.gtf_path, self.source) if local_source else None
genetic_code_state = _file_state(self.gtf_path)
genetic_code_state = file_fingerprint(self.gtf_path)

df = self._load_gtf_as_dataframe(
usecols=self.restrict_gtf_columns,
Expand Down Expand Up @@ -437,7 +423,7 @@ def create(self, overwrite=False, show_progress=False):
if ({"transl_table", "translation_table"}.issubset(df.columns)
and (self.restrict_gtf_features is None
or {"transcript", "CDS"}.issubset(self.restrict_gtf_features))):
if _file_state(self.gtf_path) != genetic_code_state:
if file_fingerprint(self.gtf_path) != genetic_code_state:
self.close()
raise OSError("GTF source changed while its index was being built")
self._connection.execute('CREATE TABLE "' + GENETIC_CODE_SOURCE_TABLE + '" (state TEXT)')
Expand All @@ -450,7 +436,7 @@ def create(self, overwrite=False, show_progress=False):
if _source_state(self.gtf_path, self.source) != source_before:
self.close()
raise OSError("GTF source changed while its index was being built")
digest = _source_digest(self.gtf_path)
digest = file_digest(self.gtf_path)
if _source_state(self.gtf_path, self.source) != source_before:
self.close()
raise OSError("GTF source changed while its index was being built")
Expand Down
10 changes: 2 additions & 8 deletions pyensembl/download_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
NON_GENOME_CACHE_DIRECTORIES,
cache_root,
)
from .common import file_digest


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -61,15 +62,8 @@ def _require_available(inspection):

def _same_file_bytes(first, second, decompress=False):
"""Compare copied local input with its cached counterpart."""
def digest(path, opener=open):
value = hashlib.sha256()
with opener(path, "rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
value.update(chunk)
return value.digest()

opener = gzip.open if decompress and first.lower().endswith(".gz") else open
return digest(first, opener) == digest(second)
return file_digest(first, opener=opener) == file_digest(second)


def cache_subdirectory(
Expand Down
8 changes: 4 additions & 4 deletions pyensembl/gene.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# limitations under the License.


from memoized_property import memoized_property
from functools import cached_property

from .locus_with_genome import LocusWithGenome

Expand Down Expand Up @@ -79,7 +79,7 @@ def to_dict(self):
state_dict["gene_name"] = self.gene_name
return state_dict

@memoized_property
@cached_property
def gene_version(self):
"""
Ensembl annotation version for this gene (int) or None if the GTF
Expand Down Expand Up @@ -115,7 +115,7 @@ def versioned_id(self):
"""Alias for :attr:`versioned_gene_id`."""
return self.versioned_gene_id

@memoized_property
@cached_property
def transcripts(self):
"""
Property which dynamically construct transcript objects for all
Expand All @@ -137,7 +137,7 @@ def transcripts(self):
self.genome.transcript_by_id(result[0]) for result in transcript_id_results
]

@memoized_property
@cached_property
def exons(self):
exon_set = set([])
for transcript in self.transcripts:
Expand Down
31 changes: 14 additions & 17 deletions pyensembl/genome_fasta.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,15 @@

from datacache import FileValidationError, fetch_file

from .common import _atomic_output, _publish, _read_progress, _remove, _staging_path
from .common import (
_atomic_output,
_publish,
_read_progress,
_remove,
_staging_path,
file_digest,
file_fingerprint,
)
from .download_cache import DOWNLOAD_TIMEOUT
from .normalization import normalize_chromosome

Expand All @@ -35,13 +43,6 @@ def _write_json(path, value):
json.dump(value, handle)


def _fingerprint(path, ctime=True):
stat = os.stat(path)
if not ctime:
return [stat.st_size, stat.st_mtime_ns, stat.st_ino]
return [stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns, stat.st_ino]


class GenomeFasta:
"""A single combined FASTA; never modifies an attached local source.

Expand Down Expand Up @@ -83,7 +84,7 @@ def _file_fingerprint(self, path):
# Cache-owned files change only by atomic replacement (a new inode).
# Ignore their ctime, which chmod/chown of a shared cache also update;
# keep it for user files, which may be rewritten in place.
return _fingerprint(path, ctime=path == self.source)
return file_fingerprint(path, ctime=path == self.source)

def _file_fingerprints(self, paths):
try:
Expand All @@ -107,7 +108,7 @@ def installed_path(self):
if not os.path.isfile(path) or os.path.getsize(path) == 0:
return None
if not self.remote and path != self.source:
if _read_json(self.source_state_path) != _fingerprint(self.source):
if _read_json(self.source_state_path) != file_fingerprint(self.source):
return None
return path

Expand Down Expand Up @@ -175,11 +176,7 @@ def _download(self, expected_size=None, show_progress=False, *, expected_md5=Non
)
fetch_file(self.source, **options)
if expected_md5 is not None:
with open(raw, "rb") as handle:
digest = hashlib.file_digest(
handle, lambda: hashlib.md5(usedforsecurity=False)
).hexdigest()
if digest != expected_md5:
if file_digest(raw, "md5") != expected_md5:
raise FileValidationError(str(raw), "MD5 does not match upstream manifest")
self._write_uncompressed(raw, self.materialized_path, show_progress)
finally:
Expand All @@ -201,9 +198,9 @@ def prepare(self, download=False, overwrite=False, show_progress=False):
overwrite or self.installed_path is None
):
logger.info("Decompressing genome FASTA %s", self.source)
fingerprint = _fingerprint(self.source)
fingerprint = file_fingerprint(self.source)
self._write_uncompressed(self.source, self.materialized_path, show_progress)
if fingerprint != _fingerprint(self.source):
if fingerprint != file_fingerprint(self.source):
raise ValueError(
"Genome FASTA changed during decompression: %s" % self.source
)
Expand Down
10 changes: 3 additions & 7 deletions pyensembl/genome_fasta_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from filelock import FileLock, Timeout

from .download_cache import cache_root
from .common import _remove
from .common import _remove, parse_md5sum_manifest
from .genome_fasta import GenomeFasta, _read_json, _write_json

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -205,18 +205,14 @@ def _dated_remote_identity(source, match):
directory, filename = source.rsplit("/", 1)
with urlopen(directory + "/md5sum.txt", timeout=60) as response:
manifest = response.read(4 * 1024 * 1024).decode("utf-8")
entries = [line.split() for line in manifest.splitlines()]
matches = [fields[0].lower() for fields in entries
if len(fields) == 2 and fields[1].removeprefix("*").removeprefix("./") == filename]
if len(matches) != 1 or not re.fullmatch(r"[0-9a-f]{32}", matches[0]):
raise ValueError("No unique MD5 for this FASTA")
md5 = parse_md5sum_manifest(manifest, filename)
with urlopen(Request(source, method="HEAD"), timeout=60) as response:
length = int(response.headers["Content-Length"])
if length <= 0:
raise ValueError("No compressed size for this FASTA")
return dict(platform="ensemblorganisms", provider="ftp.ebi.ac.uk",
assembly=accession, annotation_provider=provider, masking=masking,
md5=matches[0], compressed_size=length)
md5=md5, compressed_size=length)


def _check_object_identity(root, directory, identity):
Expand Down
Loading
Loading