Debian Codegraph @

biomaj_core/utils.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 import os
2 import errno
3 import re
4 import logging
5 import shutil
6 import datetime
7 import time
8 import subprocess
9 from subprocess import CalledProcessError
10 import socket
•11 from importlib.metadata import version
12 from mimetypes import MimeTypes
13 import requests
14
15
16 class Utils(object):
17 """
18 Utility classes
19 """
20
21 services = ['USER', 'DOWNLOAD', 'PROCESS', 'RELEASE', 'CRON', 'DAEMON', 'FTP', 'WATCHER']
22
23 mime = None
24
25 @staticmethod
26 def get_module_version(module_name):
27 '''
28 Get module_name version and latest version on pypi
29 '''
30 try:
31 latest = None
32 req = requests.get('https://pypi.python.org/pypi/' + module_name + '/json')
33 if req.status_code == 200:
34 req_json = req.json()
35 latest = str(req_json['info']['version'])
•36 return (version(module_name), latest)
37 except Exception as e:
38 logging.debug(str(e))
39 return (None, latest)
40
41 @staticmethod
42 def get_service_endpoint(config, service):
43 '''
44 Get endpoint from config for a service. If not defined, return global endpoint
45 '''
46 if service.upper() not in Utils.services:
47 if 'web' not in config or 'local_endpoint' not in config['web']:
48 return None
49 return config['web']['local_endpoint']
50 service_endpoint_name = 'local_endpoint_' + service.lower()
51 if service_endpoint_name in config['web'] and config['web'][service_endpoint_name]:
52 return config['web'][service_endpoint_name]
53 else:
54 if 'web' not in config or 'local_endpoint' not in config['web']:
55 return None
56 return config['web']['local_endpoint']
57
58 @staticmethod
59 def service_config_override(config):
60 if 'rabbitmq' not in config:
61 config['rabbitmq'] = {}
62 if 'RABBITMQ_HOST' in os.environ and os.environ['RABBITMQ_HOST']:
63 config['rabbitmq']['host'] = os.environ['RABBITMQ_HOST']
64 if 'RABBITMQ_PORT' in os.environ and os.environ['RABBITMQ_PORT']:
65 config['rabbitmq']['port'] = int(os.environ['RABBITMQ_PORT'])
66 if 'RABBITMQ_USER' in os.environ and os.environ['RABBITMQ_USER']:
67 config['rabbitmq']['user'] = os.environ['RABBITMQ_USER']
68 if 'RABBITMQ_PASSWORD' in os.environ and os.environ['RABBITMQ_PASSWORD']:
69 config['rabbitmq']['password'] = os.environ['RABBITMQ_PASSWORD']
70 if 'RABBITMQ_VHOST' in os.environ and os.environ['RABBITMQ_VHOST']:
71 config['rabbitmq']['virtual_host'] = os.environ['RABBITMQ_VHOST']
72 if 'consul' not in config:
73 config['consul'] = {'host': None, 'id': None}
74 if not config['consul']['id']:
75 if 'HOSTNAME' in os.environ and os.environ['HOSTNAME']:
76 config['consul']['id'] = os.environ['HOSTNAME']
77 else:
78 config['consul']['id'] = socket.gethostname()
79
80 if 'web' not in config:
81 config['web'] = {}
82 if 'BIOMAJ_HOSTNAME' in os.environ and os.environ['BIOMAJ_HOSTNAME']:
83 config['web']['hostname'] = os.environ['BIOMAJ_HOSTNAME']
84 else:
85 if 'HOSTNAME' in os.environ and os.environ['HOSTNAME']:
86 config['web']['hostname'] = os.environ['HOSTNAME']
87 else:
88 config['web']['hostname'] = socket.gethostname()
89
90 if 'docker' not in config:
91 config['docker'] = {}
92 if 'DOCKER_URL' in os.environ and os.environ['DOCKER_URL']:
93 config['docker']['url'] = os.environ['DOCKER_URL']
94 else:
95 config['docker']['url'] = None
96
97 if 'REDIS_HOST' in os.environ and os.environ['REDIS_HOST']:
98 config['redis']['host'] = os.environ['REDIS_HOST']
99 if 'REDIS_PORT' in os.environ and os.environ['REDIS_PORT']:
100 config['redis']['port'] = int(os.environ['REDIS_PORT'])
101 if 'REDIS_PREFIX' in os.environ and os.environ['REDIS_PREFIX']:
102 config['redis']['prefix'] = os.environ['REDIS_PREFIX']
103 if 'CONSUL_HOST' in os.environ and os.environ['CONSUL_HOST']:
104 config['consul']['host'] = os.environ['CONSUL_HOST']
105 if 'CONSUL_ID' in os.environ and os.environ['CONSUL_ID']:
106 config['consul']['id'] = os.environ['CONSUL_ID']
107 if 'WEB_PORT' in os.environ and os.environ['WEB_PORT']:
108 config['web']['port'] = int(os.environ['WEB_PORT'])
109 if 'WEB_LOCAL_ENDPOINT' in os.environ and os.environ['WEB_LOCAL_ENDPOINT']:
110 config['web']['local_endpoint'] = os.environ['WEB_LOCAL_ENDPOINT']
111 for service in Utils.services:
112 if 'WEB_LOCAL_ENDPOINT_' + service in os.environ and os.environ['WEB_LOCAL_ENDPOINT_' + service]:
113 config['web']['local_endpoint_' + service.lower()] = os.environ['WEB_LOCAL_ENDPOINT_' + service]
114 if 'mongo' not in config:
115 config['mongo'] = {'url': None, 'db': 'biomaj'}
116 if 'MONGO_URL' in os.environ and os.environ['MONGO_URL']:
117 config['mongo']['url'] = os.environ['MONGO_URL']
118 if 'MONGO_DB' in os.environ and os.environ['MONGO_DB']:
119 config['mongo']['db'] = os.environ['MONGO_DB']
120
121 @staticmethod
122 def get_folder_size(folder):
123 """
124 Get directory path full size
125
126 :param folder: directory path
127 :type folder: str
128 """
129 logger = logging.getLogger('biomaj')
130 if not os.path.exists(folder):
131 return -1
132 folder_size = 0
133 for (path, dirs, files) in os.walk(folder):
134 for ffile in files:
135 filename = os.path.join(path, ffile)
136 try:
137 folder_size += os.path.getsize(filename)
138 except Exception:
139 logger.error('[stat][size] file not found %s' % filename)
140 return folder_size
141
142 @staticmethod
143 def detect_format(filename):
144 """
145 try to detect file format by extension
146 """
147 if Utils.mime is None:
148 Utils.mime = MimeTypes()
149 mimesfile = os.path.join(os.path.dirname(__file__), 'mimes-bio.txt')
150 Utils.mime.read(mimesfile, True)
151 return Utils.mime.guess_type(filename, True)
152
153 @staticmethod
154 def get_more_recent_file(files):
155 """
156 Return the date of the most recent file in list.
157
158 Each file is a dict like with (at least) parameters: year, month, day
159 """
160 if not files:
161 return None
162 # release = None
163 rfile = files[0]
164 release = {'year': rfile['year'], 'month': rfile['month'], 'day': rfile['day'], 'file': rfile}
165 for rfile in files:
166 rel_date = datetime.date(int(release['year']), int(release['month']), int(release['day']))
167 file_date = datetime.date(int(rfile['year']), int(rfile['month']), int(rfile['day']))
168 if file_date > rel_date:
169 release['year'] = rfile['year']
170 release['month'] = rfile['month']
171 release['day'] = rfile['day']
172 release['file'] = rfile
173 return release
174
175 @staticmethod
176 def month_to_num(date):
177 return {
178 'Jan': 1,
179 'Feb': 2,
180 'Mar': 3,
181 'Apr': 4,
182 'May': 5,
183 'Jun': 6,
184 'Jul': 7,
185 'Aug': 8,
186 'Sep': 9,
187 'Oct': 10,
188 'Nov': 11,
189 'Dec': 12,
190 '01': 1,
191 '02': 2,
192 '03': 3,
193 '04': 4,
194 '05': 5,
195 '06': 6,
196 '07': 7,
197 '08': 8,
198 '09': 9,
199 '10': 10,
200 '11': 11,
201 '12': 12
202 }[date]
203
204 @staticmethod
205 def copy_files(files_to_copy, to_dir, move=False, lock=None,
206 use_hardlinks=False):
207 """
208 Copy or move files to to_dir, keeping directory structure.
209
210 Copy keeps the original file stats.
211 Files should have attributes name and root:
212 - root: root directory
213 - name: relative path of file in root directory
214
215 /root/file/file1 will be copied in to_dir/file/file1
216
217 :param files_to_copy: list of files to copy
218 :type files_to_copy: list
219 :param to_dir: destination directory
220 :type to_dir: str
221 :param move: move instead of copy
222 :type move: bool
223 :param lock: thread lock object for multi-threads
224 :type lock: Lock
225 :param use_hardlinks: use hard links (if possible)
226 :type link: bool
227 """
228 logger = logging.getLogger('biomaj')
229 nb_files = len(files_to_copy)
230 cur_files = 1
231 for file_to_copy in files_to_copy:
232 logger.debug(str(cur_files) + '/' + str(nb_files) + ' copy file ' + file_to_copy['name'])
233 cur_files += 1
234 from_file = file_to_copy['root'] + '/' + file_to_copy['name']
235 to_file = to_dir + '/' + file_to_copy['name']
236 if lock is not None:
237 lock.acquire()
238 try:
239 if not os.path.exists(os.path.dirname(to_file)):
240 os.makedirs(os.path.dirname(to_file))
241 except Exception as e:
242 logger.error(e)
243 finally:
244 lock.release()
245
246 else:
247 if not os.path.exists(os.path.dirname(to_file)):
248 try:
249 os.makedirs(os.path.dirname(to_file))
250 except Exception as e:
251 logger.error(e)
252 if move:
253 shutil.move(from_file, to_file)
254 else:
255 start_time = datetime.datetime.now()
256 start_time = time.mktime(start_time.timetuple())
257 if use_hardlinks:
258 try:
259 os.link(from_file, to_file)
260 logger.debug("Using hardlinks to copy %s",
261 file_to_copy['name'])
262 except OSError as e:
263 if e.errno in (errno.ENOSYS, errno.ENOTSUP):
264 msg = "Your system doesn't support hard links. Using regular copy."
265 logger.warn(msg)
266 # Copy this file (the stats are copied at the end
267 # of the function)
268 shutil.copyfile(from_file, to_file)
269 # Don't try links anymore
270 use_hardlinks = False
271 elif e.errno == errno.EPERM:
272 msg = "The FS at %s doesn't support hard links. Using regular copy."
273 logger.warn(msg, to_dir)
274 # Copy this file (the stats are copied at the end
275 # of the function)
276 shutil.copyfile(from_file, to_file)
277 # Don't try links anymore
278 use_hardlinks = False
279 elif e.errno == errno.EXDEV:
280 msg = "Cross device hard link is impossible (source: %s, dest: %s). Using regular copy."
281 logger.warn(msg, from_file, to_dir)
282 # Copy this file
283 shutil.copyfile(from_file, to_file)
284 # Don't try links anymore
285 use_hardlinks = False
286 else:
287 raise
288 else:
289 shutil.copyfile(from_file, to_file)
290 end_time = datetime.datetime.now()
291 end_time = time.mktime(end_time.timetuple())
292 file_to_copy['download_time'] = end_time - start_time
293 if not use_hardlinks:
294 shutil.copystat(from_file, to_file)
295
296 @staticmethod
297 def copy_files_with_regexp(from_dir, to_dir, regexps, move=False, lock=None,
298 use_hardlinks=False):
299 """
300 Copy or move files from from_dir to to_dir matching regexps.
301 Copy keeps the original file stats.
302
303 :param from_dir: origin directory
304 :type from_dir: str
305 :param to_dir: destination directory
306 :type to_dir: str
307 :param regexps: list of regular expressions that files in from_dir should match to be copied
308 :type regexps: list
309 :param move: move instead of copy
310 :type move: bool
311 :param lock: thread lock object for multi-threads
312 :type lock: Lock
313 :param use_hardlinks: use hard links (if possible)
314 :type link: bool
315 :return: list of copied files with their size
316 """
317 logger = logging.getLogger('biomaj')
318 files_to_copy = []
319 files_list = []
320 for root, _, files in os.walk(from_dir, topdown=True):
321 for name in files:
322 for reg in regexps:
323 file_relative_path = os.path.join(root, name).replace(from_dir, '')
324 if file_relative_path.startswith('/'):
325 file_relative_path = file_relative_path.replace('/', '', 1)
326 # sometimes files appear twice.... check not already managed
327 if file_relative_path in files_list:
328 continue
329 if reg == "**/*":
330 files_to_copy.append({'name': file_relative_path})
331 files_list.append(file_relative_path)
332 continue
333 if re.match(reg, file_relative_path):
334 files_list.append(file_relative_path)
335 files_to_copy.append({'name': file_relative_path})
336 continue
337
338 for file_to_copy in files_to_copy:
339 from_file = from_dir + '/' + file_to_copy['name']
340 to_file = to_dir + '/' + file_to_copy['name']
341
342 if lock is not None:
343 lock.acquire()
344 try:
345 if not os.path.exists(os.path.dirname(to_file)):
346 os.makedirs(os.path.dirname(to_file))
347 except Exception as e:
348 logger.error(e)
349 finally:
350 lock.release()
351 else:
352 if not os.path.exists(os.path.dirname(to_file)):
353 os.makedirs(os.path.dirname(to_file))
354 if not os.path.exists(from_file):
355 logger.warn('File does not exists: %s' % (from_file))
356 continue
357 if move:
358 shutil.move(from_file, to_file)
359 else:
360 if use_hardlinks:
361 try:
362 os.link(from_file, to_file)
363 logger.debug("Using hardlinks to copy %s",
364 file_to_copy['name'])
365 except OSError as e:
366 if e.errno in (errno.ENOSYS, errno.ENOTSUP):
367 msg = "Your system doesn't support hard links. Using regular copy."
368 logger.warn(msg)
369 # Copy this file (the stats are copied at the end
370 # of the function)
371 shutil.copyfile(from_file, to_file)
372 # Don't try links anymore
373 use_hardlinks = False
374 elif e.errno == errno.EPERM:
375 msg = "The FS at %s doesn't support hard links. Using regular copy."
376 logger.warn(msg, to_dir)
377 # Copy this file (we copy the stats here because
378 # it's not done at the end of the function)
379 shutil.copyfile(from_file, to_file)
380 shutil.copystat(from_file, to_file)
381 # Don't try links anymore
382 use_hardlinks = False
383 elif e.errno == errno.EXDEV:
384 msg = "Cross device hard link is impossible (source: %s, dest: %s). Using regular copy."
385 logger.warn(msg, from_file, to_dir)
386 # Copy this file (we copy the stats here because
387 # it's not done at the end of the function)
388 shutil.copyfile(from_file, to_file)
389 shutil.copystat(from_file, to_file)
390 # Don't try links anymore
391 use_hardlinks = False
392 else:
393 raise
394 else:
395 shutil.copyfile(from_file, to_file)
396 shutil.copystat(from_file, to_file)
397 file_to_copy['size'] = os.path.getsize(to_file)
398 f_stat = datetime.datetime.fromtimestamp(os.path.getmtime(to_file))
399 file_to_copy['year'] = str(f_stat.year)
400 file_to_copy['month'] = str(f_stat.month)
401 file_to_copy['day'] = str(f_stat.day)
402 (file_format, encoding) = Utils.detect_format(to_file)
403 file_to_copy['format'] = file_format
404 return files_to_copy
405
406 @staticmethod
407 def archive_check(archivefile):
408 """
409 Test file archive integrity
410
411 :param file: full path to file to check and uncompress
412 :type file: str
413 :return: True if ok, False if an error occured
414 """
415 logger = logging.getLogger('biomaj')
416 try:
417 if archivefile.endswith(('.tar.gz', '.tgz')):
418 subprocess.check_call("tar tfz " + archivefile, shell=True)
419 elif archivefile.endswith('.tar'):
420 subprocess.check_call("tar tf " + archivefile, shell=True)
421 elif archivefile.endswith('.bz2'):
422 subprocess.check_call("tar tjf " + archivefile, shell=True)
423 elif archivefile.endswith('.gz'):
424 subprocess.check_call("gunzip -t " + archivefile, shell=True)
425 elif archivefile.endswith('.zip'):
426 subprocess.check_call("unzip -t " + archivefile, shell=True)
427 else:
428 logger.warn("archive_check: unable to process check call for '" + str(archivefile) + "'")
429 except CalledProcessError as uncompresserror:
430 logger.error("Archive integrity error of %s: %s" % (archivefile, str(uncompresserror)))
431 return False
432
433 return True
434
435 @staticmethod
436 def uncompress(archivefile, remove=True):
437 """
438 Test if file is an archive, and uncompress it
439 Remove archive file if specified
440
441 :param file: full path to file to check and uncompress
442 :type file: str
443 :param remove: remove archive if present
444 :type remove: bool
445 :return: True if ok, False if an error occured
446 """
447 is_archive = False
448 logger = logging.getLogger('biomaj')
449 try:
450 if archivefile.endswith(('.tar.gz', '.tgz')):
451 subprocess.check_call("tar xfz " + archivefile + " --overwrite -C " + os.path.dirname(archivefile), shell=True)
452 is_archive = True
453 elif archivefile.endswith('.tar'):
454 subprocess.check_call("tar xf " + archivefile + " --overwrite -C " + os.path.dirname(archivefile), shell=True)
455 is_archive = True
456 elif archivefile.endswith('.bz2'):
457 subprocess.check_call("tar xjf " + archivefile + " --overwrite -C " + os.path.dirname(archivefile), shell=True)
458 is_archive = True
459 elif archivefile.endswith('.gz'):
460 subprocess.check_call("gunzip -f " + archivefile, shell=True)
461 is_archive = True
462 elif archivefile.endswith('.zip'):
463 subprocess.check_call("unzip -o " + archivefile + " -d " + os.path.dirname(archivefile), shell=True)
464 is_archive = True
465 else:
466 raise Exception("uncompress: Unknown file extension in '" + str(archivefile) + "'")
467 except CalledProcessError as uncompresserror:
468 logger.error("Uncompress error of %s: %s" % (archivefile, str(uncompresserror)))
469 return False
470 except Exception as e:
471 logger.error(e)
472 return False
473
474 if is_archive:
475 logger.debug('Uncompress:uncompress:' + archivefile)
476
477 if is_archive and remove and os.path.exists(archivefile):
478 os.remove(archivefile)
479
480 return True
481
482 @staticmethod
483 def to_bool(value):
484 if isinstance(value, bool):
485 return value
486 if not value:
487 return False
488 try:
489 if value.lower() == 'true' or value == '1':
490 return True
491 else:
492 return False
493 except Exception:
494 return False
495
496 @staticmethod
497 def to_int(value):
498 if isinstance(value, int):
499 return value
500 if not value:
501 return 0
502 try:
503 return int(value)
504 except Exception:
505 return 0