/
osprey_worker.py
184 lines (163 loc) · 6.24 KB
/
osprey_worker.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
#!/usr/bin/env python3
#
# Osprey script
# https://github.com/Smithsonian/Osprey
#
# Validate images in Digitization Projects
#
############################################
# Import modules
############################################
import logging
import os
import time
import requests
# Import settings from settings.py file
import settings
# Import helper functions
from functions import *
ver = "2.7.6"
# Pass an argument in the CLI 'debug'
if len(sys.argv) > 1:
run_debug = sys.argv[1]
else:
run_debug = False
############################################
# Logging
############################################
log_folder = "logs"
if not os.path.exists(log_folder):
os.makedirs(log_folder)
# Logging
current_time = time.strftime("%Y%m%d_%H%M%S", time.localtime())
logfile = '{}/{}_{}.log'.format(log_folder, settings.project_alias, current_time)
logging.basicConfig(filename=logfile, filemode='a', level=logging.DEBUG,
format='%(levelname)s | %(asctime)s | %(filename)s:%(lineno)s | %(message)s',
datefmt='%y-%b-%d %H:%M:%S')
logger = logging.getLogger("osprey")
logging.info("osprey version {}".format(ver))
# Set locale for number format
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
############################################
# Check requirements
############################################
if check_requirements(settings.jhove) is False:
logger.error("JHOVE was not found")
sys.exit(1)
if check_requirements(settings.exiftool) is False:
logger.error("exiftool was not found")
sys.exit(1)
if check_requirements(settings.magick) is False:
logger.error("imagemagick was not found")
sys.exit(1)
############################################
# Main
############################################
def main():
# Check that the paths are valid dirs and are mounted
if not os.path.isdir(settings.project_datastorage):
logger.error("Path not found: {}".format(settings.project_datastorage))
sys.exit(1)
r = requests.get('{}/api/'.format(settings.api_url))
if r.status_code != 200:
# Something went wrong
query_results = r.text.encode('utf-8')
logger.error("API Returned Error: {}".format(query_results))
sys.exit(1)
system_info = json.loads(r.text.encode('utf-8'))
if system_info['sys_ver'] != ver:
logger.error("API version ({}) does not match this script ({})".format(system_info['sys_ver'], ver))
sys.exit(1)
default_payload = {'api_key': settings.api_key}
r = requests.post('{}/api/projects/{}'.format(settings.api_url, settings.project_alias), data=default_payload)
if r.status_code != 200:
# Something went wrong
query_results = r.text.encode('utf-8')
logger.error("API Returned Error: {}".format(query_results))
sys.exit(1)
project_info = json.loads(r.text.encode('utf-8'))
# Reset folders under verification and other pending tasks
payload = {'type': 'startup',
'property': 'startup',
'api_key': settings.api_key,
'value': True
}
r = requests.post('{}/api/update/{}'.format(settings.api_url, settings.project_alias), data=payload)
if r.status_code != 200:
# Something went wrong
query_results = r.text.encode('utf-8')
logger.error("API Returned Error: {}".format(query_results))
sys.exit(1)
# Generate list of folders in the path
folders = []
for entry in os.scandir(settings.project_datastorage):
if entry.is_dir() and entry.path != settings.project_datastorage:
print(entry)
folders.append(entry.path)
else:
logger.error("Extraneous files in: {}".format(entry.path))
sys.exit(1)
# No folders found
if len(folders) == 0:
logger.info("No folders found in: {}".format(settings.project_datastorage))
return True
# Check each folder
logger.info("project_info: {}".format(project_info))
for folder in folders:
run_checks_folder_p(project_info, folder, log_folder, logger)
return True
############################################
# Main loop
############################################
if __name__ == "__main__":
if run_debug == 'debug':
print("Running debug version...")
main()
else:
orig_dir = os.getcwd()
while True:
try:
# Check if there is a pre script to run
if settings.pre_script is not None:
p = subprocess.Popen([settings.pre_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
if p.returncode != 0:
print("Pre-script error")
print(out)
print(err)
sys.exit(9)
else:
print(out)
# Run main function
mainval = main()
# Return to main dir
os.chdir(orig_dir)
# Check if there is a post script to run
if settings.post_script is not None:
p = subprocess.Popen([settings.post_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
if p.returncode != 0:
print("Post-script error")
print(out)
print(err)
sys.exit(9)
else:
print(out)
if settings.sleep is False:
logger.info("Process completed!")
compress_log()
sys.exit(0)
else:
logger.info("Sleeping for {} secs".format(settings.sleep))
# Sleep before trying again
time.sleep(settings.sleep)
continue
except KeyboardInterrupt:
logger.info("Ctrl-c detected. Leaving program.")
compress_log()
sys.exit(0)
except Exception as e:
logger.error("There was an error: {}".format(e))
compress_log()
sys.exit(1)
sys.exit(0)