Debian Codegraph @

azure/datalake/store/utils.py

raw
1 # -*- coding: utf-8 -*-
2 # coding=utf-8
3 # --------------------------------------------------------------------------
4 # Copyright (c) Microsoft Corporation. All rights reserved.
5 # Licensed under the MIT License. See License.txt in the project root for
6 # license information.
7 # --------------------------------------------------------------------------
8
9 import array
10 from hashlib import md5
11 import os
12 import platform
13 import sys
14 import threading
15
16 PY2 = sys.version_info.major == 2
17
18 WIN = platform.system() == 'Windows'
19
20 if WIN:
21 datadir = os.path.join(os.environ['APPDATA'], 'azure-datalake-store')
22 else:
23 datadir = os.sep.join([os.path.expanduser("~"), '.config', 'azure-datalake-store'])
24
25 try:
26 os.makedirs(datadir)
27 except:
28 pass
29
30 def ensure_writable(b):
31 if PY2 and isinstance(b, array.array):
32 return b.tostring()
33 return b
34
35
36 def write_stdout(data):
37 """ Write bytes or strings to standard output
38 """
39 try:
40 sys.stdout.buffer.write(data)
41 except AttributeError:
42 sys.stdout.write(data.decode('ascii', 'replace'))
43
44
45 def read_block(f, offset, length, delimiter=None):
46 """ Read a block of bytes from a file
47
48 Parameters
49 ----------
50 fn: file object
51 a file object that supports seek, tell and read.
52 offset: int
53 Byte offset to start read
54 length: int
55 Maximum number of bytes to read
56 delimiter: bytes (optional)
57 Ensure reading stops at delimiter bytestring
58
59 If using the ``delimiter=`` keyword argument we ensure that the read
60 stops at or before the delimiter boundaries that follow the location
61 ``offset + length``. For ADL, if no delimiter is found and the data
62 requested is > 4MB an exception is raised, since a single record cannot
63 exceed 4MB and be guaranteed to land contiguously in ADL.
64 The bytestring returned WILL include the
65 terminating delimiter string.
66
67 Examples
68 --------
69
70 >>> from io import BytesIO # doctest: +SKIP
71 >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP
72 >>> read_block(f, 0, 13) # doctest: +SKIP
73 b'Alice, 100\\nBo'
74
75 >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP
76 b'Alice, 100\\n'
77
78 >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP
79 b'\\nCharlie, 300'
80 >>> f = BytesIO(bytearray(2**22)) # doctest: +SKIP
81 >>> read_block(f,0,2**22, delimiter=b'\\n') # doctest: +SKIP
82 IndexError: No delimiter found within max record size of 4MB.
83 Transfer without specifying a delimiter (as binary) instead.
84 """
85 f.seek(offset)
86 bytes = f.read(length)
87 if delimiter:
88 # max record size is 4MB
89 max_record = 2**22
90 if length > max_record:
91 raise IndexError('Records larger than ' + str(max_record) + ' bytes are not supported. The length requested was: ' + str(length) + 'bytes')
92 # get the last index of the delimiter if it exists
93 try:
94 last_delim_index = len(bytes) -1 - bytes[::-1].index(delimiter)
95 # this ensures the length includes all of the last delimiter (in the event that it is more than one character)
96 length = last_delim_index + len(delimiter)
97 return bytes[0:length]
98 except ValueError:
99 # TODO: Before delimters can be supported through the ADLUploader logic, the number of chunks being uploaded
100 # needs to be visible to this method, since it needs to throw if:
101 # 1. We cannot find a delimiter in <= 4MB of data
102 # 2. If the remaining size is less than 4MB but there are multiple chunks that need to be stitched together,
103 # since the delimiter could be split across chunks.
104 # 3. If delimiters are specified, there must be logic during segment determination that ensures all chunks
105 # terminate at the end of a record (on a new line), even if that makes the chunk < 256MB.
106 if length >= max_record:
107 raise IndexError('No delimiter found within max record size of ' + str(max_record) + ' bytes. Transfer without specifying a delimiter (as binary) instead.')
108
109 return bytes
110
111 def tokenize(*args, **kwargs):
112 """ Deterministic token
113
114 >>> tokenize('Hello') == tokenize('Hello')
115 True
116 """
117 if kwargs:
118 args = args + (kwargs,)
119 return md5(str(tuple(args)).encode()).hexdigest()
120
121
122 def commonprefix(paths):
123 """ Find common directory for all paths
124
125 Python's ``os.path.commonprefix`` will not return a valid directory path in
126 some cases, so we wrote this convenience method.
127
128 Examples
129 --------
130
131 >>> # os.path.commonprefix returns '/disk1/foo'
132 >>> commonprefix(['/disk1/foobar', '/disk1/foobaz'])
133 '/disk1'
134
135 >>> commonprefix(['a/b/c', 'a/b/d', 'a/c/d'])
136 'a'
137
138 >>> commonprefix(['a/b/c', 'd/e/f', 'g/h/i'])
139 ''
140 """
141 return os.path.dirname(os.path.commonprefix(paths))
142
143
144 def clamp(n, smallest, largest):
145 """ Limit a value to a given range
146
147 This is equivalent to smallest <= n <= largest.
148
149 Examples
150 --------
151
152 >>> clamp(0, 1, 100)
153 1
154
155 >>> clamp(42, 2, 128)
156 42
157
158 >>> clamp(1024, 1, 32)
159 32
160 """
161 return max(smallest, min(n, largest))
162
163
164 class CountUpDownLatch:
165 """CountUpDownLatch provides a thread safe implementation of Up Down latch
166 """
167 def __init__(self):
168 self.lock = threading.Condition()
169 self.val = 0
170 self.total = 0
171
172 def increment(self):
173 self.lock.acquire()
174 self.val += 1
175 self.total += 1
176 self.lock.release()
177
178 def decrement(self):
179 self.lock.acquire()
180 self.val -= 1
181 if self.val <= 0:
182 self.lock.notify_all()
183 self.lock.release()
184
185 def total_processed(self):
186 self.lock.acquire()
187 temp = self.total
188 self.lock.release()
189 return temp
190
191 def is_zero(self):
192 self.lock.acquire()
193 while self.val > 0:
194 self.lock.wait()
195 self.lock.release()
196 return True