This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
314 lines (269 loc) · 11 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
Models used by the block structure framework.
"""
import errno
from contextlib import contextmanager
from datetime import datetime
from logging import getLogger
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.core.files.base import ContentFile
from django.db import models, transaction
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeStampedModel
from openedx.core.djangoapps.xmodule_django.models import UsageKeyWithRunField
from openedx.core.storage import get_storage
from . import config
from .exceptions import BlockStructureNotFound
log = getLogger(__name__)
def _create_path(directory, filename):
"""
Returns the full path for the given directory and filename.
"""
return f'{directory}/{filename}'
def _directory_name(data_usage_key):
"""
Returns the directory name for the given
data_usage_key.
"""
# .. setting_name: BLOCK_STRUCTURES_SETTINGS['DIRECTORY_PREFIX']
# .. setting_default: ''
# .. setting_description: Specifies the path in storage where block structures would be saved,
# for storage-backed block structure cache.
# For more information, check https://github.com/edx/edx-platform/pull/14571.
# .. setting_warnings: Depends on `BLOCK_STRUCTURES_SETTINGS['STORAGE_CLASS']` and on
# `block_structure.storage_backing_for_cache`.
directory_prefix = settings.BLOCK_STRUCTURES_SETTINGS.get('DIRECTORY_PREFIX', '')
# replace any '/' in the usage key so they aren't interpreted
# as folder separators.
encoded_usage_key = str(data_usage_key).replace('/', '_')
return '{}{}'.format(
directory_prefix,
encoded_usage_key,
)
def _path_name(bs_model, _filename):
"""
Returns path name to use for the given
BlockStructureModel instance.
"""
filename = datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S-%f')
return _create_path(
_directory_name(bs_model.data_usage_key),
filename,
)
def _bs_model_storage():
"""
Get django Storage object for BlockStructureModel.
"""
# .. setting_name: BLOCK_STRUCTURES_SETTINGS['STORAGE_CLASS']
# .. setting_default: None
# .. setting_description: Specifies the storage used for storage-backed block structure cache.
# For more information, check https://github.com/edx/edx-platform/pull/14571.
# .. setting_warnings: Depends on `block_structure.storage_backing_for_cache`.
storage_class = settings.BLOCK_STRUCTURES_SETTINGS.get('STORAGE_CLASS')
# .. setting_name: BLOCK_STRUCTURES_SETTINGS['STORAGE_KWARGS']
# .. setting_default: {}
# .. setting_description: Specifies the keyword arguments needed to setup the storage, which
# would be used for storage-backed block structure cache.
# For more information, check https://github.com/edx/edx-platform/pull/14571.
# .. setting_warnings: Depends on `BLOCK_STRUCTURES_SETTINGS['STORAGE_CLASS']` and on
# `block_structure.storage_backing_for_cache`.
storage_kwargs = settings.BLOCK_STRUCTURES_SETTINGS.get('STORAGE_KWARGS', {})
return get_storage(storage_class, **storage_kwargs)
class CustomizableFileField(models.FileField):
"""
Subclass of FileField that allows custom settings to not
be serialized (hard-coded) in migrations. Otherwise,
migrations include optional settings for storage (such as
the storage class and bucket name); we don't want to
create new migration files for each configuration change.
"""
def __init__(self, *args, **kwargs):
kwargs.update(dict(
upload_to=_path_name,
storage=_bs_model_storage(),
max_length=500, # allocate enough for base path + prefix + usage_key + timestamp in filepath
))
super().__init__(*args, **kwargs)
def deconstruct(self): # lint-amnesty, pylint: disable=missing-function-docstring
name, path, args, kwargs = super().deconstruct()
del kwargs['upload_to']
del kwargs['storage']
del kwargs['max_length']
return name, path, args, kwargs
@contextmanager
def _storage_error_handling(bs_model, operation, is_read_operation=False):
"""
Helpful context manager that handles various errors
from the backend storage.
Typical errors at read time on configuration changes:
IOError:
- File not found (S3 or FS)
- Bucket name changed (S3)
SuspiciousOperation
- Path mismatches when changing backends
Other known errors:
OSError
- Access issues in creating files (FS)
S3ResponseError
- Incorrect credentials with 403 status (S3)
- Non-existent bucket with 404 status (S3)
"""
try:
yield
except Exception as error: # pylint: disable=broad-except
log.exception('BlockStructure: Exception %s on store %s; %s.', error.__class__, operation, bs_model)
if isinstance(error, OSError) and error.errno in (errno.EACCES, errno.EPERM): # lint-amnesty, pylint: disable=no-else-raise, no-member
raise
elif is_read_operation and isinstance(error, (IOError, SuspiciousOperation)):
# May have been caused by one of the possible error
# situations listed above. Raise BlockStructureNotFound
# so the block structure can be regenerated and restored.
raise BlockStructureNotFound(bs_model.data_usage_key) # lint-amnesty, pylint: disable=raise-missing-from
else:
raise
@python_2_unicode_compatible
class BlockStructureModel(TimeStampedModel):
"""
Model for storing Block Structure information.
.. no_pii:
"""
VERSION_FIELDS = [
'data_version',
'data_edit_timestamp',
'transformers_schema_version',
'block_structure_schema_version',
]
UNIQUENESS_FIELDS = ['data_usage_key'] + VERSION_FIELDS
class Meta:
db_table = 'block_structure'
data_usage_key = UsageKeyWithRunField(
'Identifier of the data being collected.',
blank=False,
max_length=255,
unique=True,
)
data_version = models.CharField(
'Version of the data at the time of collection.',
blank=True,
null=True,
max_length=255,
)
data_edit_timestamp = models.DateTimeField(
'Edit timestamp of the data at the time of collection.',
blank=True,
null=True,
)
transformers_schema_version = models.CharField(
'Representation of the schema version of the transformers used during collection.',
blank=False,
max_length=255,
)
block_structure_schema_version = models.CharField(
'Version of the block structure schema at the time of collection.',
blank=False,
max_length=255,
)
data = CustomizableFileField()
def get_serialized_data(self):
"""
Returns the collected data for this instance.
"""
operation = 'Read'
with _storage_error_handling(self, operation, is_read_operation=True):
serialized_data = self.data.read()
self._log(self, operation, serialized_data)
return serialized_data
@classmethod
def get(cls, data_usage_key):
"""
Returns the entry associated with the given data_usage_key.
Raises:
BlockStructureNotFound if an entry for data_usage_key is not found.
"""
try:
return cls.objects.get(data_usage_key=data_usage_key)
except cls.DoesNotExist:
log.info('BlockStructure: Not found in table; %s.', data_usage_key)
raise BlockStructureNotFound(data_usage_key) # lint-amnesty, pylint: disable=raise-missing-from
@classmethod
def update_or_create(cls, serialized_data, data_usage_key, **kwargs):
"""
Updates or creates the BlockStructureModel entry
for the given data_usage_key in the kwargs,
uploading serialized_data as the content data.
"""
# Use an atomic transaction so the model isn't updated
# unless the file is successfully persisted.
with transaction.atomic():
bs_model, created = cls.objects.update_or_create(defaults=kwargs, data_usage_key=data_usage_key)
operation = 'Created' if created else 'Updated'
with _storage_error_handling(bs_model, operation):
bs_model.data.save('', ContentFile(serialized_data))
cls._log(bs_model, operation, serialized_data)
if not created:
cls._prune_files(data_usage_key)
return bs_model, created
def __str__(self):
"""
Returns a string representation of this model.
"""
return ', '.join(
'{}: {}'.format(field_name, str(getattr(self, field_name)))
for field_name in self.UNIQUENESS_FIELDS
)
@classmethod
def _prune_files(cls, data_usage_key, num_to_keep=None):
"""
Deletes previous file versions for data_usage_key.
"""
if not settings.BLOCK_STRUCTURES_SETTINGS.get('PRUNING_ACTIVE', False):
return
if num_to_keep is None:
num_to_keep = config.num_versions_to_keep()
try:
all_files_by_date = sorted(cls._get_all_files(data_usage_key))
files_to_delete = all_files_by_date[:-num_to_keep] if num_to_keep > 0 else all_files_by_date # lint-amnesty, pylint: disable=invalid-unary-operand-type
cls._delete_files(files_to_delete)
log.info(
'BlockStructure: Deleted %d out of total %d files in store; data_usage_key: %s, num_to_keep: %d.',
len(files_to_delete),
len(all_files_by_date),
data_usage_key,
num_to_keep,
)
except Exception: # pylint: disable=broad-except
log.exception('BlockStructure: Exception when deleting old files; data_usage_key: %s.', data_usage_key)
@classmethod
def _delete_files(cls, files):
"""
Deletes the given files from storage.
"""
storage = _bs_model_storage()
list(map(storage.delete, files))
@classmethod
def _get_all_files(cls, data_usage_key):
"""
Returns all filenames that exist for the given key.
"""
directory = _directory_name(data_usage_key)
_, filenames = _bs_model_storage().listdir(directory)
return [
_create_path(directory, filename)
for filename in filenames
if filename and not filename.startswith('.')
]
@classmethod
def _log(cls, bs_model, operation, serialized_data):
"""
Writes log information for the given values.
"""
log.info(
'BlockStructure: %s in store %s at %s%s; %s, size: %d',
operation,
bs_model.data.storage.__class__,
getattr(bs_model.data.storage, 'bucket_name', ''),
getattr(bs_model.data.storage, 'location', ''),
bs_model,
len(serialized_data),
)