Skip to content

Commit 1f53be7

Browse files
fred-yu-2013stiartsly
authored andcommitted
CU-95wju9 - Make the test case of backup API work.
1 parent 5b4f1ae commit 1f53be7

File tree

6 files changed

+56
-25
lines changed

6 files changed

+56
-25
lines changed

manage.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from src import create_app
44

55
manager = Manager(create_app)
6-
manager.add_command("runserver", Server(host="0.0.0.0", port=5000, threaded=False, processes=2))
6+
manager.add_command("runserver", Server(host="0.0.0.0", port=5000, threaded=True))
77
manager.add_option('-c', '--config', dest='mode', required=False)
88

99
if __name__ == "__main__":

src/__init__.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -57,5 +57,9 @@ def create_app(mode=HIVE_MODE_PROD, hive_config='/etc/hive/.env'):
5757
if mode == HIVE_MODE_DEV:
5858
CORS(app, supports_credentials=True)
5959
print("hive node cors supported")
60-
logging.getLogger("create_app").debug("create_app")
60+
# The logging examples, the output is in CONSOLE and hive.log:
61+
# 2021-06-15 12:06:08,527 - Initialize - DEBUG - create_app
62+
# 2021-06-15 12:06:08,527 - root - INFO - [Initialize] create_app is processing now.
63+
logging.getLogger("Initialize").debug("create_app")
64+
logging.info('[Initialize] create_app is processing now.')
6165
return app

src/modules/backup/backup.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,11 @@ def backup_service(self):
4848

4949
@hive_restful_response
5050
def backup_finish(self, checksum_list):
51-
self.server.backup_finish(checksum_list)
51+
return self.server.backup_finish(checksum_list)
5252

5353
@hive_restful_response
5454
def backup_files(self):
55-
self.server.backup_files()
55+
return self.server.backup_files()
5656

5757
@hive_restful_response
5858
def backup_get_file(self, file_name):

src/modules/backup/backup_server.py

+41-14
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
# -*- coding: utf-8 -*-
22
import _thread
3+
import logging
34
import pickle
45
import shutil
56
import subprocess
7+
import threading
8+
import traceback
69
from datetime import datetime
710
from pathlib import Path
811

@@ -38,12 +41,23 @@
3841
URL_BACKUP_PATCH_HASH, URL_BACKUP_PATCH_FILE, URL_RESTORE_FINISH
3942

4043

44+
def clog():
45+
return logging.getLogger('BACKUP_CLIENT')
46+
47+
48+
def slog():
49+
return logging.getLogger('BACKUP_SERVER')
50+
51+
4152
class BackupClient:
42-
def __init__(self, app, hive_setting):
53+
def __init__(self, app=None, hive_setting=None):
54+
self.http = HttpClient()
55+
self.backup_thread = None
4356
self.hive_setting = hive_setting
44-
self.mongo_host, self.mongo_port = self.hive_setting.MONGO_HOST, self.hive_setting.MONGO_PORT
57+
self.mongo_host, self.mongo_port = None, None
58+
if hive_setting:
59+
self.mongo_host, self.mongo_port = self.hive_setting.MONGO_HOST, self.hive_setting.MONGO_PORT
4560
self.auth = Auth(app, hive_setting)
46-
self.http = HttpClient()
4761

4862
def check_backup_status(self, did):
4963
doc = cli.find_one_origin(DID_INFO_DB_NAME, VAULT_BACKUP_INFO_COL, {DID: did})
@@ -75,7 +89,10 @@ def execute_backup(self, did, credential_info, backup_service_info, access_token
7589
if use_storage > backup_service_info[VAULT_BACKUP_SERVICE_MAX_STORAGE]:
7690
raise InsufficientStorageException(msg='Insufficient storage to execute backup.')
7791

78-
_thread.start_new_thread(self.__class__.backup_main, (did, self))
92+
clog().debug('start new thread for backup processing.')
93+
94+
self.backup_thread = threading.Thread(target=BackupClient.backup_main, args=(did, self))
95+
self.backup_thread.start()
7996

8097
def update_backup_state(self, did, state, msg):
8198
cli.update_one_origin(DID_INFO_DB_NAME,
@@ -102,20 +119,29 @@ def import_mongodb(self, did):
102119
@staticmethod
103120
def backup_main(did, client):
104121
try:
122+
clog().info(f'[backup_main] enter backup thread, {did}, {client}.')
105123
client.backup(did)
106-
except Exception as e:
124+
except BaseException as e:
125+
clog().error(f'Failed to backup really: {traceback.format_exc()}')
107126
client.update_backup_state(did, VAULT_BACKUP_STATE_STOP, VAULT_BACKUP_MSG_FAILED)
127+
clog().info('[backup_main] leave backup thread.')
108128

109129
def backup(self, did):
130+
clog().info('[backup_main] enter backup().')
110131
self.export_mongodb_data(did)
132+
clog().info('[backup_main] success to export mongodb data.')
111133
vault_root = get_vault_path(did)
112134
doc = cli.find_one_origin(DID_INFO_DB_NAME, VAULT_BACKUP_INFO_COL, {DID: did})
135+
clog().info('[backup_main] success to get backup info.')
113136
self.backup_really(vault_root, doc[VAULT_BACKUP_INFO_DRIVE], doc[VAULT_BACKUP_INFO_TOKEN])
137+
clog().info('[backup_main] success to execute backup.')
114138

115139
checksum_list = get_file_checksum_list(vault_root)
116140
self.backup_finish(doc[VAULT_BACKUP_INFO_DRIVE], doc[VAULT_BACKUP_INFO_TOKEN], checksum_list)
141+
clog().info('[backup_main] success to finish backup.')
117142
self.delete_mongodb_data(did)
118143
self.update_backup_state(did, VAULT_BACKUP_STATE_STOP, VAULT_BACKUP_MSG_SUCCESS)
144+
clog().info('[backup_main] success to backup really.')
119145

120146
def restore(self, did):
121147
vault_root = get_vault_path(did)
@@ -148,7 +174,7 @@ def restore_really(self, vault_root, host_url, access_token):
148174
self.restore_delete_files(host_url, access_token, delete_files)
149175

150176
def backup_finish(self, host_url, access_token, checksum_list):
151-
self.http.post(host_url + URL_BACKUP_FINISH, access_token, {'checksum_list': checksum_list})
177+
self.http.post(host_url + URL_BACKUP_FINISH, access_token, {'checksum_list': checksum_list}, is_body=False)
152178

153179
def diff_backup_files(self, remote_files, local_files, vault_root):
154180
remote_files_d = dict((d[1], d[0]) for d in remote_files) # name: checksum
@@ -169,10 +195,9 @@ def diff_restore_files(self, remote_files, local_files, vault_root):
169195
return new_files, patch_files, delete_files
170196

171197
def backup_new_files(self, host_url, access_token, new_files):
172-
for info in new_files:
173-
src_file, dst_file = info[0], info[1]
174-
with open(src_file, 'br') as f:
175-
self.http.put(host_url + URL_BACKUP_FILE + f'?file={dst_file}', access_token, f)
198+
for full_name, name in new_files:
199+
with open(full_name, 'br') as f:
200+
self.http.put(host_url + URL_BACKUP_FILE + f'?file={name}', access_token, f, is_body=False)
176201

177202
def restore_new_files(self, host_url, access_token, new_files):
178203
for info in new_files:
@@ -206,7 +231,8 @@ def backup_patch_files(self, host_url, access_token, patch_files):
206231
pickle.dump(patch_data, f)
207232

208233
with open(temp_file.as_posix(), 'rb') as f:
209-
self.http.post(host_url + URL_BACKUP_PATCH_FILE + f'?file={full_name}', body=f, is_json=False)
234+
self.http.post(host_url + URL_BACKUP_PATCH_FILE + f'?file={full_name}',
235+
body=f, is_json=False, is_body=False)
210236

211237
temp_file.unlink()
212238

@@ -255,6 +281,7 @@ def restore_main(did, client):
255281
try:
256282
client.restore(did)
257283
except Exception as e:
284+
clog().error(f'Failed to restore really: {traceback.format_exc()}')
258285
client.update_backup_state(did, VAULT_BACKUP_STATE_STOP, VAULT_BACKUP_MSG_FAILED)
259286

260287
def restore_finish(self, did, host_url, access_token):
@@ -354,12 +381,12 @@ def backup_finish(self, checksum_list):
354381
def backup_files(self):
355382
did, _, _ = self.__check_auth_backup()
356383

357-
result = dict()
384+
backup_files = list()
358385
backup_root = get_vault_backup_path(did)
359386
if backup_root.exists():
360387
md5_list = deal_dir(backup_root.as_posix(), get_file_md5_info)
361-
result['backup_files'] = [(md5[0], Path(md5[1]).relative_to(backup_root).as_posix()) for md5 in md5_list]
362-
return result
388+
backup_files = [(md5[0], Path(md5[1]).relative_to(backup_root).as_posix()) for md5 in md5_list]
389+
return {'backup_files': backup_files}
363390

364391
def backup_get_file(self, file_name):
365392
if not file_name:

src/utils/http_client.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def get(self, url, access_token, is_body=True, options=None):
2222
except Exception as e:
2323
raise InvalidParameterException(msg=f'[HttpClient] Failed to GET ({url}) with exception: {str(e)}')
2424

25-
def post(self, url, access_token, body, is_json=True):
25+
def post(self, url, access_token, body, is_json=True, is_body=True):
2626
try:
2727
headers = dict()
2828
if access_token:
@@ -33,19 +33,19 @@ def post(self, url, access_token, body, is_json=True):
3333
if is_json else requests.post(url, headers=headers, data=body)
3434
if r.status_code != 201:
3535
raise InvalidParameterException(f'Failed to POST with status code: {r.status_code}')
36-
return r.json()
36+
return r.json() if is_body else r
3737
except Exception as e:
3838
raise InvalidParameterException(f'Failed to POST with exception: {str(e)}')
3939

40-
def put(self, url, access_token, body):
40+
def put(self, url, access_token, body, is_body=False):
4141
try:
4242
headers = {"Authorization": "token " + access_token}
4343
r = requests.put(url, headers=headers, data=body)
4444
if r.status_code != 200:
45-
raise InvalidParameterException(f'Failed to PUT with status code: {r.status_code}')
46-
return r.json()
45+
raise InvalidParameterException(f'Failed to PUT {url} with status code: {r.status_code}')
46+
return r.json() if is_body else r
4747
except Exception as e:
48-
raise InvalidParameterException(f'Failed to PUT with exception: {str(e)}')
48+
raise InvalidParameterException(f'Failed to PUT {url} with exception: {str(e)}')
4949

5050
def delete(self, url, access_token):
5151
try:

src/utils/http_response.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import json
1212

1313

14-
class HiveException(BaseException):
14+
class HiveException(Exception):
1515
NO_INTERNAL_CODE = -1
1616

1717
def __init__(self, code, internal_code, msg):

0 commit comments

Comments
 (0)