| 1 |
from concurrent.futures import ThreadPoolExecutor |
| 2 |
from .utils import CountUpDownLatch |
| 3 |
import threading |
| 4 |
import logging |
| 5 |
import multiprocessing |
| 6 |
import os |
| 7 |
import logging.handlers |
| 8 |
from .exceptions import FileNotFoundError |
| 9 |
try: |
| 10 |
from queue import Empty # Python 3 |
| 11 |
import _thread |
| 12 |
except ImportError: |
| 13 |
from Queue import Empty # Python 2 |
| 14 |
import thread |
| 15 |
|
| 16 |
WORKER_THREAD_PER_PROCESS = 50 |
| 17 |
QUEUE_BUCKET_SIZE = 10 |
| 18 |
END_QUEUE_SENTINEL = [None, None] |
| 19 |
GLOBAL_EXCEPTION = None |
| 20 |
GLOBAL_EXCEPTION_LOCK = threading.Lock() |
| 21 |
|
| 22 |
|
| 23 |
def monitor_exception(exception_queue, process_ids): |
| 24 |
global GLOBAL_EXCEPTION |
| 25 |
logger = logging.getLogger("azure.datalake.store") |
| 26 |
|
| 27 |
while True: |
| 28 |
try: |
| 29 |
local_exception = exception_queue.get(timeout=0.1) |
| 30 |
if local_exception == END_QUEUE_SENTINEL: |
| 31 |
break |
| 32 |
logger.log(logging.DEBUG, "Setting global exception") |
| 33 |
GLOBAL_EXCEPTION_LOCK.acquire() |
| 34 |
GLOBAL_EXCEPTION = local_exception |
| 35 |
GLOBAL_EXCEPTION_LOCK.release() |
| 36 |
logger.log(logging.DEBUG, "Closing processes") |
| 37 |
for p in process_ids: |
| 38 |
p.terminate() |
| 39 |
logger.log(logging.DEBUG, "Joining processes") |
| 40 |
for p in process_ids: |
| 41 |
p.join() |
| 42 |
|
| 43 |
logger.log(logging.DEBUG, "Interrupting main") |
| 44 |
raise Exception(local_exception) |
| 45 |
except Empty: |
| 46 |
pass |
| 47 |
|
| 48 |
|
| 49 |
def log_listener_process(queue): |
| 50 |
while True: |
| 51 |
try: |
| 52 |
record = queue.get(timeout=0.1) |
| 53 |
queue.task_done() |
| 54 |
if record == END_QUEUE_SENTINEL: # We send this as a sentinel to tell the listener to quit. |
| 55 |
break |
| 56 |
logger = logging.getLogger("azure.datalake.store") |
| 57 |
#logger.handlers.clear() |
| 58 |
logger.handle(record) # No level or filter logic applied - just do it! |
| 59 |
except Empty: # Try again |
| 60 |
pass |
| 61 |
except Exception as e: |
| 62 |
import sys, traceback |
| 63 |
print('Problems in logging') |
| 64 |
traceback.print_exc(file=sys.stderr) |
| 65 |
|
| 66 |
|
| 67 |
def multi_processor_change_acl(adl, path=None, method_name="", acl_spec="", number_of_sub_process=None): |
| 68 |
logger = logging.getLogger("azure.datalake.store") |
| 69 |
|
| 70 |
def launch_processes(number_of_processes): |
| 71 |
if number_of_processes is None: |
| 72 |
number_of_processes = max(2, multiprocessing.cpu_count() - 1) |
| 73 |
process_list = [] |
| 74 |
for i in range(number_of_processes): |
| 75 |
process_list.append(multiprocessing.Process(target=processor, |
| 76 |
args=(adl, file_path_queue, finish_queue_processing_flag, |
| 77 |
method_name, acl_spec, log_queue, exception_queue))) |
| 78 |
process_list[-1].start() |
| 79 |
return process_list |
| 80 |
|
| 81 |
def walk(walk_path): |
| 82 |
try: |
| 83 |
paths = [] |
| 84 |
all_files = adl.ls(path=walk_path, detail=True) |
| 85 |
|
| 86 |
for files in all_files: |
| 87 |
if files['type'] == 'DIRECTORY': |
| 88 |
dir_processed_counter.increment() # A new directory to process |
| 89 |
walk_thread_pool.submit(walk, files['name']) |
| 90 |
|
| 91 |
paths.append((files['name'], files['type'] == 'FILE')) |
| 92 |
|
| 93 |
if len(paths) == QUEUE_BUCKET_SIZE: |
| 94 |
file_path_queue.put(list(paths)) |
| 95 |
paths = [] |
| 96 |
|
| 97 |
if paths != []: |
| 98 |
file_path_queue.put(list(paths)) # For leftover paths < bucket_size |
| 99 |
except FileNotFoundError: |
| 100 |
pass # Continue in case the file was deleted in between |
| 101 |
except Exception: |
| 102 |
import traceback |
| 103 |
logger.exception("Failed to walk for path: " + str(walk_path) + ". Exiting!") |
| 104 |
exception_queue.put(traceback.format_exc()) |
| 105 |
finally: |
| 106 |
dir_processed_counter.decrement() # Processing complete for this directory |
| 107 |
|
| 108 |
# Initialize concurrency primitives |
| 109 |
log_queue = multiprocessing.JoinableQueue() |
| 110 |
exception_queue = multiprocessing.Queue() |
| 111 |
finish_queue_processing_flag = multiprocessing.Event() |
| 112 |
file_path_queue = multiprocessing.JoinableQueue() |
| 113 |
dir_processed_counter = CountUpDownLatch() |
| 114 |
|
| 115 |
# Start relevant threads and processes |
| 116 |
log_listener = threading.Thread(target=log_listener_process, args=(log_queue,)) |
| 117 |
log_listener.start() |
| 118 |
child_processes = launch_processes(number_of_sub_process) |
| 119 |
exception_monitor_thread = threading.Thread(target=monitor_exception, args=(exception_queue, child_processes)) |
| 120 |
exception_monitor_thread.start() |
| 121 |
walk_thread_pool = ThreadPoolExecutor(max_workers=WORKER_THREAD_PER_PROCESS) |
| 122 |
|
| 123 |
# Root directory needs to be explicitly passed |
| 124 |
file_path_queue.put([(path, False)]) |
| 125 |
dir_processed_counter.increment() |
| 126 |
|
| 127 |
# Processing starts here |
| 128 |
walk(path) |
| 129 |
|
| 130 |
if dir_processed_counter.is_zero(): # Done processing all directories. Blocking call. |
| 131 |
walk_thread_pool.shutdown() |
| 132 |
file_path_queue.close() # No new elements to add |
| 133 |
file_path_queue.join() # Wait for operations to be done |
| 134 |
logger.log(logging.DEBUG, "file path queue closed") |
| 135 |
finish_queue_processing_flag.set() # Set flag to break loop of child processes |
| 136 |
for child in child_processes: # Wait for all child process to finish |
| 137 |
logger.log(logging.DEBUG, "Joining process: "+str(child.pid)) |
| 138 |
child.join() |
| 139 |
|
| 140 |
# Cleanup |
| 141 |
logger.log(logging.DEBUG, "Sending exception sentinel") |
| 142 |
exception_queue.put(END_QUEUE_SENTINEL) |
| 143 |
exception_monitor_thread.join() |
| 144 |
logger.log(logging.DEBUG, "Exception monitor thread finished") |
| 145 |
logger.log(logging.DEBUG, "Sending logger sentinel") |
| 146 |
log_queue.put(END_QUEUE_SENTINEL) |
| 147 |
log_queue.join() |
| 148 |
log_queue.close() |
| 149 |
logger.log(logging.DEBUG, "Log queue closed") |
| 150 |
log_listener.join() |
| 151 |
logger.log(logging.DEBUG, "Log thread finished") |
| 152 |
|
| 153 |
|
| 154 |
def processor(adl, file_path_queue, finish_queue_processing_flag, method_name, acl_spec, log_queue, exception_queue): |
| 155 |
logger = logging.getLogger("azure.datalake.store") |
| 156 |
logger.setLevel(logging.DEBUG) |
| 157 |
removed_default_acl_spec = ",".join([x for x in acl_spec.split(',') if not x.lower().startswith("default")]) |
| 158 |
|
| 159 |
try: |
| 160 |
logger.addHandler(logging.handlers.QueueHandler(log_queue)) |
| 161 |
logger.propagate = False # Prevents double logging |
| 162 |
except AttributeError: |
| 163 |
# Python 2 doesn't have Queue Handler. Default to best effort logging. |
| 164 |
pass |
| 165 |
|
| 166 |
try: |
| 167 |
func_table = {"mod_acl": adl.modify_acl_entries, "set_acl": adl.set_acl, "rem_acl": adl.remove_acl_entries} |
| 168 |
function_thread_pool = ThreadPoolExecutor(max_workers=WORKER_THREAD_PER_PROCESS) |
| 169 |
adl_function = func_table[method_name] |
| 170 |
logger.log(logging.DEBUG, "Started processor pid:"+str(os.getpid())) |
| 171 |
|
| 172 |
def func_wrapper(func, path, spec): |
| 173 |
try: |
| 174 |
func(path=path, acl_spec=spec) |
| 175 |
except FileNotFoundError: |
| 176 |
logger.exception("File "+str(path)+" not found") |
| 177 |
# Complete Exception is being logged in the relevant acl method. Don't print exception here |
| 178 |
except Exception as e: |
| 179 |
logger.exception("File " + str(path) + " not set. Exception "+str(e)) |
| 180 |
|
| 181 |
logger.log(logging.DEBUG, "Completed running on path:" + str(path)) |
| 182 |
|
| 183 |
while finish_queue_processing_flag.is_set() == False: |
| 184 |
try: |
| 185 |
file_paths = file_path_queue.get(timeout=0.1) |
| 186 |
file_path_queue.task_done() # Will not be called if empty |
| 187 |
for file_path in file_paths: |
| 188 |
is_file = file_path[1] |
| 189 |
if is_file: |
| 190 |
spec = removed_default_acl_spec |
| 191 |
else: |
| 192 |
spec = acl_spec |
| 193 |
|
| 194 |
logger.log(logging.DEBUG, "Starting on path:" + str(file_path)) |
| 195 |
function_thread_pool.submit(func_wrapper, adl_function, file_path[0], spec) |
| 196 |
except Empty: |
| 197 |
pass |
| 198 |
|
| 199 |
except Exception as e: |
| 200 |
import traceback |
| 201 |
logger.exception("Exception in pid "+str(os.getpid())+"Exception: " + str(e)) |
| 202 |
exception_queue.put(traceback.format_exc()) |
| 203 |
finally: |
| 204 |
function_thread_pool.shutdown() # Blocking call. Will wait till all threads are done executing. |
| 205 |
logger.log(logging.DEBUG, "Finished processor pid: " + str(os.getpid())) |