| 1 |
# Copyright 2014 Google Inc. All Rights Reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
"""File based cache for the discovery document. |
| 16 |
|
| 17 |
The cache is stored in a single file so that multiple processes can |
| 18 |
share the same cache. It locks the file whenever accessing to the |
| 19 |
file. When the cache content is corrupted, it will be initialized with |
| 20 |
an empty cache. |
| 21 |
""" |
| 22 |
|
| 23 |
from __future__ import division |
| 24 |
|
| 25 |
import datetime |
| 26 |
import json |
| 27 |
import logging |
| 28 |
import os |
| 29 |
import tempfile |
| 30 |
|
| 31 |
try: |
| 32 |
from oauth2client.contrib.locked_file import LockedFile |
| 33 |
except ImportError: |
| 34 |
# oauth2client < 2.0.0 |
| 35 |
try: |
| 36 |
from oauth2client.locked_file import LockedFile |
| 37 |
except ImportError: |
| 38 |
# oauth2client > 4.0.0 or google-auth |
| 39 |
raise ImportError( |
| 40 |
"file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth" |
| 41 |
) |
| 42 |
|
| 43 |
from . import base |
| 44 |
from ..discovery_cache import DISCOVERY_DOC_MAX_AGE |
| 45 |
|
| 46 |
LOGGER = logging.getLogger(__name__) |
| 47 |
|
| 48 |
FILENAME = "google-api-python-client-discovery-doc.cache" |
| 49 |
EPOCH = datetime.datetime(1970, 1, 1) |
| 50 |
|
| 51 |
|
| 52 |
def _to_timestamp(date): |
| 53 |
try: |
| 54 |
return (date - EPOCH).total_seconds() |
| 55 |
except AttributeError: |
| 56 |
# The following is the equivalent of total_seconds() in Python2.6. |
| 57 |
# See also: https://docs.python.org/2/library/datetime.html |
| 58 |
delta = date - EPOCH |
| 59 |
return ( |
| 60 |
delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10**6 |
| 61 |
) / 10**6 |
| 62 |
|
| 63 |
|
| 64 |
def _read_or_initialize_cache(f): |
| 65 |
f.file_handle().seek(0) |
| 66 |
try: |
| 67 |
cache = json.load(f.file_handle()) |
| 68 |
except Exception: |
| 69 |
# This means it opens the file for the first time, or the cache is |
| 70 |
# corrupted, so initializing the file with an empty dict. |
| 71 |
cache = {} |
| 72 |
f.file_handle().truncate(0) |
| 73 |
f.file_handle().seek(0) |
| 74 |
json.dump(cache, f.file_handle()) |
| 75 |
return cache |
| 76 |
|
| 77 |
|
| 78 |
class Cache(base.Cache): |
| 79 |
"""A file based cache for the discovery documents.""" |
| 80 |
|
| 81 |
def __init__(self, max_age): |
| 82 |
"""Constructor. |
| 83 |
|
| 84 |
Args: |
| 85 |
max_age: Cache expiration in seconds. |
| 86 |
""" |
| 87 |
self._max_age = max_age |
| 88 |
self._file = os.path.join(tempfile.gettempdir(), FILENAME) |
| 89 |
f = LockedFile(self._file, "a+", "r") |
| 90 |
try: |
| 91 |
f.open_and_lock() |
| 92 |
if f.is_locked(): |
| 93 |
_read_or_initialize_cache(f) |
| 94 |
# If we can not obtain the lock, other process or thread must |
| 95 |
# have initialized the file. |
| 96 |
except Exception as e: |
| 97 |
LOGGER.warning(e, exc_info=True) |
| 98 |
finally: |
| 99 |
f.unlock_and_close() |
| 100 |
|
| 101 |
def get(self, url): |
| 102 |
f = LockedFile(self._file, "r+", "r") |
| 103 |
try: |
| 104 |
f.open_and_lock() |
| 105 |
if f.is_locked(): |
| 106 |
cache = _read_or_initialize_cache(f) |
| 107 |
if url in cache: |
| 108 |
content, t = cache.get(url, (None, 0)) |
| 109 |
if _to_timestamp(datetime.datetime.now()) < t + self._max_age: |
| 110 |
return content |
| 111 |
return None |
| 112 |
else: |
| 113 |
LOGGER.debug("Could not obtain a lock for the cache file.") |
| 114 |
return None |
| 115 |
except Exception as e: |
| 116 |
LOGGER.warning(e, exc_info=True) |
| 117 |
finally: |
| 118 |
f.unlock_and_close() |
| 119 |
|
| 120 |
def set(self, url, content): |
| 121 |
f = LockedFile(self._file, "r+", "r") |
| 122 |
try: |
| 123 |
f.open_and_lock() |
| 124 |
if f.is_locked(): |
| 125 |
cache = _read_or_initialize_cache(f) |
| 126 |
cache[url] = (content, _to_timestamp(datetime.datetime.now())) |
| 127 |
# Remove stale cache. |
| 128 |
for k, (_, timestamp) in list(cache.items()): |
| 129 |
if ( |
| 130 |
_to_timestamp(datetime.datetime.now()) |
| 131 |
>= timestamp + self._max_age |
| 132 |
): |
| 133 |
del cache[k] |
| 134 |
f.file_handle().truncate(0) |
| 135 |
f.file_handle().seek(0) |
| 136 |
json.dump(cache, f.file_handle()) |
| 137 |
else: |
| 138 |
LOGGER.debug("Could not obtain a lock for the cache file.") |
| 139 |
except Exception as e: |
| 140 |
LOGGER.warning(e, exc_info=True) |
| 141 |
finally: |
| 142 |
f.unlock_and_close() |
| 143 |
|
| 144 |
|
| 145 |
cache = Cache(max_age=DISCOVERY_DOC_MAX_AGE) |