/
views.py
1494 lines (1110 loc) · 47.7 KB
/
views.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Python file uses the following encoding: utf-8
"""
Gaebar (Google App Engine Backup and Restore) Beta 1
A Naklab™ production sponsored by the <head> web conference - http://headconference.com
Copyright (c) 2009 Aral Balkan. http://aralbalkan.com
Released under the GNU GPL v3 License. See license.txt for the full license or read it here:
http://www.gnu.org/licenses/gpl-3.0-standalone.html
"""
import os
import sys
import re
import pickle
import time
import datetime
import functools
import logging
import traceback
from django import http
from django.shortcuts import render_to_response
from django.conf import settings
from django.utils.http import urlquote
from django.utils import simplejson
from django.template import loader
from django.http import HttpResponse
from django.http import HttpResponseNotFound
from django.http import HttpResponseForbidden
from django.http import HttpResponseServerError
from django.http import HttpResponseRedirect
from django.http import Http404
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.api.datastore_errors import BadKeyError
from google.appengine.api import urlfetch
from google.appengine.api import users
# According to Guido in Rietveld,
# DeadlineExceededError can live in two different places.
# TODO - Aral: Has this been fixed yet?
try:
# When deployed
from google.appengine.runtime import DeadlineExceededError
from google.appengine.runtime import OverQuotaError
from google.appengine.runtime import RequestTooLargeError
from google.appengine.runtime import CapabilityDisabledError
except ImportError:
# In the development server
from google.appengine.runtime.apiproxy_errors import DeadlineExceededError
from google.appengine.runtime.apiproxy_errors import OverQuotaError
from google.appengine.runtime.apiproxy_errors import RequestTooLargeError
from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError
# This is the Gaebar apps models not the user's app's models.
from gaebar import models
# Load the all the model classes specified by the user
# for their app in the settings file.
for modelstuple in settings.GAEBAR_MODELS:
model_package = modelstuple[0]
model_classes = modelstuple[1]
for model_class in model_classes:
__import__(model_package, globals(), locals(), model_classes)
######################################################################
#
# Constants and other globals
#
######################################################################
"""
We limit shards to 300KB to be on the safe side
(far enough away from the 1MB limit in the datastore).
If you are storing large blobs in your entities, you may need to lower this.
(The dev size is kept low so we can see shards in action without
populating the local datastore with too many entries.)
"""
#MAX_SHARD_SIZE = 2000 if IS_DEV else 300000
MAX_SHARD_SIZE = 300000
"""
Number of rows to backup on each iteration of the backup process.
5 appears to be the number at which we do not tax the deployment environment
(we don't get any short term Over Quota errors when running this
with over 2,000 rows of data to backup over a period of several minutes.)
"""
#ROWS_TO_BACKUP_ON_EACH_ITERATION = 5
ROWS_TO_BACKUP_ON_EACH_ITERATION = 5
"""
Regular expressions used by the backup and restore process (compile once)
Used to find numeric IDs in old keys while updating old keys to new
ones in the generated source code during the backup process.
"""
backup_update_key = r'(\d+?)(?:L)?,'
backup_update_key_rc = re.compile(backup_update_key)
"""
Matches string representations of timestamps.
"""
timestamp_regexp = r'^(\d\d\d\d)-(\d\d)-(\d\d)\s(\d\d):(\d\d):(\d\d)\.(\d*?)$'
timestamp_regexp_compiled = re.compile(timestamp_regexp)
"""
App.yaml app name regexp
"""
# Note: Not searching for ^application since the default app.yaml that comes
# in appenginepatch has a few invisible characters before the application and fails
# the match.
# app_name_from_app_yaml_regexp = r'application: (.*?)\n'
# app_name_from_app_yaml_regexp_compiled = re.compile(app_name_from_app_yaml_regexp)
"""
Other globals
"""
# Are we running on the local development server?
IS_DEV = False
if 'SERVER_SOFTWARE' in os.environ:
IS_DEV = os.environ['SERVER_SOFTWARE'].startswith('Dev')
# Get the application name. Many thanks to yejun for showing me
# how to get the application id on the App Engine Google Group.
application_name = os.environ.get('APPLICATION_ID')
logging.info('Application name: ')
logging.info(application_name)
######################################################################
#
# Decorators
#
######################################################################
def authorize(target_method):
"""Authorization decorator"""
def autorization_decorator(request, *args, **kwargs):
# Current user information.
user = users.get_current_user()
# Is user logged in?
if user == None:
return HttpResponseForbidden('You must <a href="%s">sign in</a> to access this feature.' % users.create_login_url('/gaebar/'))
# Is user admin?
if not users.is_current_user_admin():
return HttpResponseForbidden('You must be an administrator to access this feature. Click here to <a href="%s">sign out</a>.' % users.create_logout_url('/gaebar/'))
# User is admin; authorization OK:
# Try and call the requested view method. Very simple error handling.
try:
# For testing quota errors, enable the following line:
# raise OverQuotaError
return target_method(request, *args, **kwargs)
except DeadlineExceededError:
logging.exception('DeadlineExceededError')
return HttpResponseServerError('Deadline exceeded.')
except OverQuotaError:
logging.exception('OverQuotaError')
return HttpResponseServerError('Over quota error.')
except CapabilityDisabledError:
logging.exception('CapabilityDisabledError')
return HttpResponseServerError('Capability disabled error.')
except RequestTooLargeError:
logging.exception('RequestTooLargeError')
return HttpResponseServerError('Request too large error.')
except MemoryError:
logging.exception('MemoryError')
return HttpResponseServerError('Memory error.')
except AssertionError:
logging.exception('AssertionError')
return HttpResponseServerError('Assetion error.')
functools.update_wrapper(autorization_decorator, target_method)
return autorization_decorator
######################################################################
#
# View methods
#
######################################################################
@authorize
def index(request):
"""List backups available for restore."""
# Get the list of backups avaiable
context={}
if 'complete' in request.REQUEST:
context['complete'] = True
# Default backups folder -- will work everywhere except locally
# on app-engine-patch projects (again, because the working folder is
# common/appenginepatch/ instead of the app root.)
backups_folder = 'gaebar/backups/'
# App engine patch?
if not os.path.exists('gaebar'):
# Yep
backups_folder = '../../gaebar/backups/'
logging.info('**** Backups folder is ' + backups_folder)
current_host = request.get_host()
# Make sure that the current host isn't the local server (so that user doesn't
# accidentally backup the local server).
if current_host in settings.GAEBAR_LOCAL_URL:
context['running_on_local_server'] = True
context['current_host'] = "local development"
else:
# Check if the host is in the settings file, and, if so, use the nice name for it
servers = settings.GAEBAR_SERVERS
for server in servers:
url = servers[server]
if current_host in url:
current_host = server
context['current_host'] = current_host
folder_names = [x for x,y,z in os.walk(backups_folder)]
folders = [z for x,y,z in os.walk(backups_folder)]
folder_info = []
if (len(folders) > 1):
for i in range(len(folders)):
if i == 0: continue
num_files = len(folders[i])
try:
folder_name_index = folder_names[i].index('backup_')
except ValueError:
continue # It's some other folder, not a backup
folder_name = folder_names[i][folder_name_index:]
# TODO: We need to store host information for backups with the backup
# so we know where to go to re-download stuff if any fail.
metadata_url = request.get_host() + '/gaebar/metadata/' + urlquote(make_timestamp_from_safe_file_name(folder_name)) + '/' + urlquote(settings.SECRET_KEY) + '/'
# e.g., details = ['backup', '2008', '09', '21', 'at', '10', '15', '47', '931862']
details = folder_name.split('_')
details_object = dict(year=details[1], month=details[2], day=details[3], hour=details[5], minutes=details[6], seconds=details[7], ms=details[8])
pretty_name = details_object['year'] + '/' + details_object['month'] + '/' + details_object['day'] + ' at ' + details_object['hour'] + ':' + details_object['minutes'] + ':' + details_object['seconds']
info_object = dict(name=folder_name, num_files=num_files, metadata_url=metadata_url, details=details_object, pretty_name=pretty_name)
folder_info.append(info_object)
folder_info.reverse()
else:
# No backups
context['no_backups'] = True
context['folder_info'] = folder_info
# Servers
servers = settings.GAEBAR_SERVERS
keys = servers.keys()
keys.sort()
servers_dict = [dict(name=key, url=servers[key]) for key in keys]
context['servers'] = servers_dict
server_str = 'local development' if current_host in settings.GAEBAR_LOCAL_URL else current_host
context['title'] = " Google App Engine Backup and Restore running on " + server_str + " server."
return render_to_response('gaebar/index.html', context)
@authorize
def backup_start(request):
"""
Starts a new datastore backup.
"""
current_host = request.get_host()
server_name = ''
server_url = ''
# Make sure that the current host isn't the local server (so that user doesn't
# accidentally backup the local server).
if current_host in settings.GAEBAR_LOCAL_URL:
error_message='Backup start called on local dev server - cannot backup the local server.'
logging.error(error_message)
result_dict = dict(error=True, error_message=error_message)
result_json = simplejson.dumps(result_dict)
return HttpResponseServerError(result_json)
else:
# Check if the host is in the settings file, and, if so, use the nice name for it
servers = settings.GAEBAR_SERVERS
for server in servers:
url = servers[server]
if current_host in url:
server_name = server
server_url = url
# If the user has not setup the server in settings, use the host name.
if server_name == '':
server_name = 'Unknown server: ' + current_host
if server_url == '':
server_url = 'http://' + current_host
logging.info('Backup start: ')
logging.info('Server name: ' + server_name)
logging.info('Server url: ' + server_url)
# Make sure no code shards were left over from a previous backup
# (This can happen if the backup failed with an error.)
active_code_shards = models.GaebarCodeShard.all().filter('active = ', True).fetch(100)
for active_code_shard in active_code_shards:
active_code_shard.active = False
active_code_shard.put()
backup = models.GaebarBackup()
# Save the server details for the server we're backing up.
backup.server_name = server_name
backup.server_url = server_url
# Current solution: Manual list of models stored in the settings file.
# Dynamically generating this list is possible but you also have to keep the models in
# source-order to maintain reference-order when restoring.
models_ordered_list = []
for models_tuple in settings.GAEBAR_MODELS:
model_classes = models_tuple[1]
for model_class in model_classes:
models_ordered_list.append(model_class)
logging.info(models_ordered_list)
current_model = models_ordered_list[0]
backup.models_remaining_to_back_up = models_ordered_list
backup.ordered_model_list = models_ordered_list
backup.current_model = current_model
backup.current_index = 0
backup.put()
# Create the first code shard (since the backup code may be
# greater than 1MB in size, we need to break it up into
# several entity instances in the datastore.)
code_shard = models.GaebarCodeShard()
code_shard.backup = backup
code = code_shard.code
code = u'"""\n\tDatastore backup for %s\n\tStarted on: %s.\n"""\n\n' % (server_name, get_date_string())
code = add_code_shard_imports(code)
code_shard.code = code
code_shard.put()
context=dict(last_key=0, new_backup=True, created_at=str(backup.created_at), all_models=backup.ordered_model_list)
return backup_model(backup, context)
@authorize
def backup_rows(request):
"""
Backs up a number of rows from the datastore.
All return values are JSON-encoded HttpResponse[...] instances.
"""
# To test the 500 error resiliance,
# return HttpResponseServerError('Muhahaha!')
context=dict()
backup_key = ''
if 'backup_key' in request.REQUEST:
backup_key = request.REQUEST['backup_key']
else:
result_dict = dict(error=True, error_message='Backup key not provided in call to backup rows.')
result_json = simplejson.dumps(result_dict)
return HttpResponseServerError(result_json)
if 'last_key' in request.REQUEST:
last_key = request.REQUEST['last_key']
else:
result_dict = dict(error=True, error_message='Last key not provided in call to backup rows.')
result_json = simplejson.dumps(result_dict)
return HttpResponseServerError(result_json)
try:
backup = models.GaebarBackup.get(backup_key)
except BadKeyError:
logging.error('Error: backup with key backup_key not found in call to backup rows.')
result_dict = dict(error=True, error_message='Backup with key backup_key not found in call to backup rows.')
result_json = simplejson.dumps(result_dict)
return HttpResponseNotFound(result_json)
code_shard = models.GaebarCodeShard().all().filter('active = ', True).get()
models_list = backup.models_remaining_to_back_up
current_model = backup.current_model
current_index = backup.current_index
kind_map = db._kind_map
model_classes = []
for model_name in kind_map:
model_classes.append(kind_map[model_name])
Model = kind_map[current_model]
fields = Model.fields()
# Forced to use GQL since __key__ is not recognized for order() in App Engine 1.1.7 - yay! Joy! etc.
# logging.info('Last key:')
# logging.info(last_key)
if last_key == '0':
# No last key, get the first N rows for this model
# logging.info('NO LAST KEY, START FROM TOP')
query = Model.gql('ORDER BY __key__')
else:
# Use the new sortable keys feature
# logging.info('Has last key, using that...')
# logging.info('===> ' + last_key)
last_key_as_Key = db.Key(last_key)
query = Model.gql('WHERE __key__ > :1 ORDER BY __key__', last_key_as_Key)
rows = query.fetch(ROWS_TO_BACKUP_ON_EACH_ITERATION+1)
# logging.info('Num rows:')
# logging.info(len(rows))
new_last_key = None
last_iteration_for_model = True
if len(rows) == ROWS_TO_BACKUP_ON_EACH_ITERATION+1:
new_last_key = str(rows[ROWS_TO_BACKUP_ON_EACH_ITERATION].key())
context['last_key'] = new_last_key
last_iteration_for_model = False
# logging.info('NOT last iteration for model...')
# logging.info('New last key!')
# logging.info(new_last_key)
code = code_shard.code
#if rows:
# Go through the rows and save each one.
counter = current_index
for row in rows:
# Check if there's enough space left in this code shard.
if len(code) >= MAX_SHARD_SIZE:
# logging.info('Backup: current code shard is full, starting a new one...')
# Update the metadata (end row for this model for this shard)
update_code_shard_metadata(code_shard, backup, current_model)
# Update the shard row limits on the backup so we don't have to
# generate these after the backup (CPU-heavy)
backup.shard_row_limits.append(backup.num_rows - 1)
close_code_shard(code_shard, backup, code)
# Start the new code shard
code_shard = models.GaebarCodeShard()
code_shard.backup = backup
code_shard.start_row = backup.num_rows
code = add_code_shard_imports('')
# Update the code shard count on the backup instance
backup.num_shards += 1
# Check if we've saved this model in this code shard
# already and, if not, do so (metadata).
if not current_model in code_shard.models:
# logging.info('ADDING::::: ' + current_model)
code_shard.models.append(current_model)
code_shard.models_start_row.append(backup.num_rows)
code_shard.models_end_row.append(backup.num_rows)
# Create the entity
row_name = current_model.lower() + u'_' + unicode(counter)
existing_key_name = row.key()
key_id = row.key().id_or_name()
key_repr = row.key().__repr__()
# So that it doesn't get replaced in our regexp sweep later,
# modify numeric indices so that they don't match the pattern
# (couldn't find another way to do this since Python doesn't
# support regular expression in negative lookbehinds.)
# This will change, for example:
#
# datastore_types.Key.from_path('GoogleAccount', 2L, _app=u'si')
#
# to:
#
# datastore_types.Key.from_path('GoogleAccount', long(2L), _app=u'si')
# key_repr_safe = backup_existing_key_hack_rc.sub(r'long(\1)', key_repr)
code += u'def row_%d(app_name):\n' % backup.num_rows
# Generate code: Check if entity already exists and delete it if it does
code += u'\texisting_entity = %s.get(%s)\n' % (current_model, key_repr)
code += u'\tif existing_entity:\n'
code += u'\t\texisting_entity.delete()\n'
# code += u'\t# Key id = ' + unicode(key_id) + '\n'
# code += u'\t# Parent = ' + unicode(row.parent()) + '\n'
# code += u'\t# Key repr = ' + unicode(key_repr) + '\n'
##################################################################################
#
# Don't think this is going to work. Can't guarantee key ids... reverting to r.955
# (see below)...
#
##################################################################################
# Generate code: Create the new entity (entities are created
# differently based on whether they have key names or not).
# key_name = None
# if row.key().name():
# # Row has a key name, use this when creating the new entity
# key_name = row.key().name()
# code += u'\t\t%s = %s(key_name="%s")\n' % (row_name, current_model, key_name)
# else:
# # Don't add a key name if the row didn't have one originally
# code += u'\t\t%s = %s()\n' % (row_name, current_model)
##################################################################################
##################################################################################
#
# REVERT r.955
#
##################################################################################
if row.key().name():
key_name = row.key().name()
# code += u'\t# Key has name: ' + row.key().name()
else:
key_name = u'id' + unicode(row.key().id())
# Store the mapping from the old key to the new key
#
# new_key_code = 'datastore_entities.Key.from_path()'
# code += u'\t# (%s, )\n' % unicode(key_repr),
##################################################################################
# Does this entity have a parent?
parent_code = ''
if row.parent():
# Entity has a parent, maintain the ancestor relationship.
parent = row.parent()
parent_key = row.parent().key().__repr__()
parent_key = update_keys(parent_key)
# logging.info(parent_key)
parent_code = ', parent=%s' % parent_key
# logging.info('Parent key found, adding %s ' % parent_key)
# Create all of the properties first so that we can include them
# in the constructor (this is to support required properties which _must_ be
# included in the constructor). Thanks to Jonathan and Thomas for reporting this
# to me (see http://aralbalkan.com/1784#comment-201846).
# Property population code
properties_code = ', '
# Store fields with references separately as these will be
# handled in pass 2 of the restore process (so that we can guarantee
# that all records exist in the datastore before they are referenced.)
reference_fields_code = ', '
# Populate the fields
for field in fields:
try:
raw_value = getattr(row, field)
raw_value_type = type(raw_value)
raw_value_type_name = raw_value_type.__name__
# To test ReferenceProperty failed to be resolved error, uncomment the following line:
# raise(db.Error('ReferenceProperty failed to be resolved error.'))
except db.Error:
# If a reference property doesn't exist, this will throw a
# ReferenceProperty failed to be resolved error.
# Catch this and make a note in the code but carry on trucking
# as this is an issue with this particular datastore and
# it's not something we can fix.
#
# (Unfortunately, this will also catch other db errors as there
# isn't a specific sub-class for ReferencePropertyFailedToBeResolvedError).
# code += u"\t\t# Warning: Datastore error\n"
datastore_error_message = u"%s: %s\n\n" % sys.exc_info()[:2]
# code += u"\t\t# %s" % datastore_error_message
context['datastore_error'] = True
context['datastore_error_message'] = "Ignoring datastore error: %s" % datastore_error_message
continue
#
# Check if the field is a reference value. If so, don't pickle
# the actual reference entity but create code that can actually save
# the reference at restore-time. We save references later as they
# will be created in Pass 2 of the restore process.
#
stored = False
if raw_value_type in model_classes:
#
# Storing references as the actual datastore_entities.Key.from_path code.
# If this ReferenceProperty contains a numeric ID for the old
# datastore, it will be rewritten while writing out the references section.
#
reference_key = raw_value.key().__repr__()
reference_fields_code += u'%s=%s, ' % (field, reference_key)
stored = True
elif raw_value_type_name == 'list':
if len(raw_value) > 0:
list_type_name = type(raw_value[0]).__name__
if list_type_name == 'Key':
# ListPropert(db.Key) - list of keys (references)
# Rewrite the code to use the new ids if they contain numeric ids.
list_code = raw_value.__repr__()
reference_fields_code += '%s=%s, ' % (field, list_code)
stored = True
if not stored:
# Pickle and store (not a reference, list of keys, etc.)
value = repr(pickle.dumps(raw_value))
properties_code += u'%s=pickle.loads(%s), ' % (field, value)
# Update any old datastore numeric keys in reference properties to
# their key_name equivalents for the new datastore.
reference_fields_code = update_keys(reference_fields_code)
# Remove the trailing comma and space from the properties and reference field code strings.
properties_code = properties_code[:-2]
reference_fields_code = reference_fields_code[:-2]
# OK, all properties are ready, write out the row's constructor to create the row.
code += u'\t%s = %s(key_name=%s%s%s%s)\n' % (row_name, current_model, key_name.__repr__(), properties_code, reference_fields_code, parent_code)
# Does this row belong to an Expando model? (It's OK to put Expoando properties after the
# constructor as they cannot be required.)
if hasattr(row, '_dynamic_properties'):
# Expando row, add the dynamic properties.
logging.info('Expando row found, pickling dynamic properties...')
code += u'\t# Expando dynamic properties:\n'
dynamic_properties = row._dynamic_properties
for dynamic_property in dynamic_properties:
value = repr(pickle.dumps(dynamic_properties[dynamic_property]))
code += u'\t%s.%s = pickle.loads(%s)\n' % (row_name, dynamic_property, value)
# Put the new row
code += u'\t%s.put()\n\n' % row_name
# Update the index counter for this model
counter += 1
# Update the global row count for this backup
backup.num_rows += 1
# Update the backup position
backup.current_index = counter
# And the current code shard
code_shard.code = code
try:
code_shard.put()
except db.InternalError:
logging.warning('InternalError detected. on code_shard put. Trying twice more.')
# Try twice more to see if the datastore error goes away.
success = False
for tries in range(2):
try:
code_shard.put()
success = True
break
except db.InternalError:
logging.warning('InternalError on code_shard put attempt ' + str(tries+1))
if not success:
logging.error('InternalError: could not put code_shard.')
return helpers.render_response('500', first_level, second_level, context, 'HttpResponseServerError')
# And continue backing up
if not last_iteration_for_model:
# Continue backup
return backup_model(backup, context)
else:
# No rows left on the current model:
# start on the next model, if there is one.
# Update the metadata (end row for this model for this shard)
# code_shard.models_end_row.append(backup.num_rows)
update_code_shard_metadata(code_shard, backup, current_model)
try:
# logging.info('Backup: model ' + current_model + ': done')
code_shard.put()
models_list.remove(current_model)
next_model = models_list[0]
# logging.info('Backup: next model is ' + next_model)
backup.current_model = next_model
backup.current_index = 0
# Signal that there is no last key for this model yet so that backup starts from the first row.
context['last_key'] = 0
return backup_model(backup, context)
except IndexError:
# That was the last model, backing up the rows is over.
# Update the shard row limits on the backup so we don't have to
# generate these after the backup (CPU-heavy)
backup.shard_row_limits.append(backup.num_rows - 1)
# Close the code shard
close_code_shard(code_shard, backup, code)
# The backup is complete
backup.complete=True
backup.put()
# Check if there was any data in the datastore (do not store empty backups)
shard_row_limits = backup.shard_row_limits
if len(shard_row_limits) == 1:
if shard_row_limits[0] == -1:
# Nothing was backed up
result_json = simplejson.dumps(dict(empty_datastore=True))
return HttpResponse(result_json)
# Set the local and remote URLs
remote_url = backup.server_url
local_url = settings.GAEBAR_LOCAL_URL
logging.info('remote_url = ' + remote_url)
logging.info('local_url = ' + local_url)
# TODO: Make the gaebar app name configurable
download_url = local_url + '/gaebar/download-remote/?created_at=' + urlquote(backup.created_at) + '&num_shards=' + str(backup.num_shards) + '&url=' + remote_url
context['url'] = download_url
context['backup_key'] = backup_key
# Backing up of data is done. Inform user and start
# downloading it to their local machine.
logging.info('Backup: completed backing up rows.')
result_json = simplejson.dumps(dict(complete=True, download_url=download_url))
return HttpResponse(result_json)
# Not using @authorize - runs on localhost.
def backup_local_download_remote_backup(request):
"""
Download a remote backup to the local machine.
Arguments: created_at, num_shards.
IMPORTANT: _This runs on localhost_ and gets called by the deployment
environment (i.e., the local server must be running before you do
a remote backup to get this to work automatically.)
Downloaded files are saved in the backups folder of your
Django project.
File structure:
backups
|
|- __init__.py
|_ <created_at>
|
|- __init__.py
|_ metadata.py
|_ shard0.py
|_ shard1.py
|_ shard<n>.py
"""
# Depending on which app engine patch we're using, the cwd will be different.
# In appenginepatch, we'll be in /common/appenginepatch/ and will need to go to /../../gaebar/backups/
# If I remember correctly, in AppEngine Helper, you should be in the root folder of your
# project so the backups will simply be in gaebar/backups/
#
# These are the only two configurations currently supported. If this breaks for you, let me know
# and I'll try and add support for your configuration too. (Or, if someone has a portable solution,
# please let me know at aral@aralbalkan.com and I'll implement that.)
##############################################################
# Monkeypatch: Remove the dev appserver restrictions
# until we're done doing what we need to do.
#
# Note, requires dev_appserver.py to be patched as
# described at http://aralbalkan.com/1440
#
##############################################################
from google.appengine.tools import dev_appserver
# Add 'w' to the allowed modes
OLD_ALLOWED_MODES = dev_appserver.FakeFile.ALLOWED_MODES
dev_appserver.FakeFile.ALLOWED_MODES = frozenset(['r', 'rb', 'U', 'rU', 'w'])
# Add mkdir back to os
os.mkdir = os.old_mkdir
# Add chdir back to os
os.chdir = os.old_chdir
##################### End monkeypatches ########################
if 'url' in request.REQUEST:
host_url = request.REQUEST['url']
# Make sure host URL starts with http:// protocol.
if not host_url[0:7] == 'http://':
host_url = 'http://' + host_url
logging.info('Host url: ' + host_url)
else:
return HttpResponse('Missing URL in local download of remote backup.')
if 'created_at' in request.REQUEST:
created_at = request.REQUEST['created_at']
logging.info('Created at: ' + created_at)
else:
return HttpResponse('Missing created at in local download of remote backup.')
if 'num_shards' in request.REQUEST:
num_shards = request.REQUEST['num_shards']
logging.info('Num shards: ' + num_shards)
else:
return HttpResponse('Missing num shards in local download of remote backup.')
# Check that we're running locally. If not, exit
# (this is not currently meant for pulling backups from
# one server to the other. However, it could be used for that later on.)
# TODO: Make this generic - not everyone will have IS_DEV in their settings.
if not IS_DEV:
return HttpResponseForbidden('Please run locally.')
# Check if we're running on appenginepatch
cwd = os.getcwd()
is_appenginepatch = (cwd[-14:] == 'appenginepatch')
if is_appenginepatch:
logging.info('Running on appenginepatch: Massaging the working directory...')
os.chdir('../../')
# Write the __init__.py in the backups package if it doesn't already exist
top_package = 'gaebar/backups/__init__.py'
if not os.path.exists(top_package):
f = file(top_package, 'w')
f.close()
# Check if the backup already exists. If it does, we fail.
existing_backups = os.listdir('gaebar/backups')
if make_safe_file_name_from_timestamp(created_at) in existing_backups:
# TODO: Ask user if they want to replace it, etc.
return HttpResponse('Sorry, backup %s is already on your local machine. Please delete it from your backups folder before downloading it again.' % created_at)
# OK, backup does not already exist. Create its folder.
backup_folder = 'gaebar/backups/' + make_safe_file_name_from_timestamp(created_at)
os.mkdir(backup_folder)
# logging.info('Backup folder created successfully.')
# And add the __init__.py to it.
f = file(backup_folder + '/__init__.py', 'w')
f.close()
# logging.info('Added package file.')
# We use the Django secret key to authenticate with the remote download handler (shared secret).
secret = urlquote(settings.GAEBAR_SECRET_KEY)
# Get all the code shards and save them as files.
result = ''
shard_index = -1
while result != 'NO_MORE_SHARDS':
shard_index += 1
logging.info('Attempting to download the next code shard (number ' + str(shard_index) + ')...')
download_url = host_url + '/gaebar/download-py/' + urlquote(created_at) + '/' + secret + '/'
file_path = backup_folder + '/shard' + str(shard_index) + '.py'
result = save_file_from_url(download_url, file_path)
# Did the download fail?
if result == 'DOWNLOAD_FAILED':
return HttpResponseServerError('Sorry, downloading shard ' + str(shard_index) + ' failed after repeated retries. Backup failed.')
# Get the metadata file:
# http://localhost:8080/admin/backup/metadata/agJzaXIMCxIGQmFja3VwGAMM/
metadata_url = host_url + '/gaebar/metadata/' + urlquote(created_at) + '/' + secret + '/'
metadata_file_path = backup_folder + '/metadata.py'
save_file_from_url(metadata_url, metadata_file_path)
logging.info('Gaebar: Downloaded all files for current backup.')
##############################################################
# Monkeypatch: Reset the local appserver restrictions
##############################################################
# Remove 'w' from the allowed modes for file.
dev_appserver.FakeFile.ALLOWED_MODES = OLD_ALLOWED_MODES
# Remove mkdir from os
del os.mkdir
# Remove chdir from os
del os.chdir
##################### End monkeypatch resets ##################
return HttpResponseRedirect('/gaebar/?complete=' + urlquote(make_safe_file_name_from_timestamp(created_at)))
# No @authorize - see notes.
def backup_download_py(request, created_at='', secret=''):
"""
Download a python source file.
This routine is meant to be called from the app. Does _not_ use the
auth system but the Django secret key so we can use urlfetch.
Note: Stores the last downloaded shard in the backup entity.
"""
logging.info('Backup download py called!')
if secret == settings.GAEBAR_SECRET_KEY: