blob: 61d0f6e29f4046607ea661361412cdb5a6c61450 [file] [log] [blame]
Neels Hofmeyr3531a192017-03-28 14:30:28 +02001# osmo_gsm_tester: language snippets
2#
3# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
4#
5# Author: Neels Hofmeyr <neels@hofmeyr.de>
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU Affero General Public License as
9# published by the Free Software Foundation, either version 3 of the
10# License, or (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU Affero General Public License for more details.
16#
17# You should have received a copy of the GNU Affero General Public License
18# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20import os
21import sys
22import time
23import fcntl
24import hashlib
25import tempfile
26import shutil
27import atexit
28import threading
29import importlib.util
30import fcntl
31import tty
32import termios
33
34
35class listdict:
36 'a dict of lists { "a": [1, 2, 3], "b": [1, 2] }'
37 def __getattr__(ld, name):
38 if name == 'add':
39 return ld.__getattribute__(name)
40 return ld.__dict__.__getattribute__(name)
41
42 def add(ld, name, item):
43 l = ld.__dict__.get(name)
44 if not l:
45 l = []
46 ld.__dict__[name] = l
47 l.append(item)
48 return l
49
50 def add_dict(ld, d):
51 for k,v in d.items():
52 ld.add(k, v)
53
54 def __setitem__(ld, name, val):
55 return ld.__dict__.__setitem__(name, val)
56
57 def __getitem__(ld, name):
58 return ld.__dict__.__getitem__(name)
59
60 def __str__(ld):
61 return ld.__dict__.__str__()
62
63
64class DictProxy:
65 '''
66 allow accessing dict entries like object members
67 syntactical sugar, adapted from http://stackoverflow.com/a/31569634
68 so that e.g. templates can do ${bts.member} instead of ${bts['member']}
69 '''
70 def __init__(self, obj):
71 self.obj = obj
72
73 def __getitem__(self, key):
74 return dict2obj(self.obj[key])
75
76 def __getattr__(self, key):
77 try:
78 return dict2obj(getattr(self.obj, key))
79 except AttributeError:
80 try:
81 return self[key]
82 except KeyError:
83 raise AttributeError(key)
84
85class ListProxy:
86 'allow nesting for DictProxy'
87 def __init__(self, obj):
88 self.obj = obj
89
90 def __getitem__(self, key):
91 return dict2obj(self.obj[key])
92
93def dict2obj(value):
94 if isinstance(value, dict):
95 return DictProxy(value)
96 if isinstance(value, (tuple, list)):
97 return ListProxy(value)
98 return value
99
100
101class FileLock:
102 def __init__(self, path, owner):
103 self.path = path
104 self.owner = owner
105 self.f = None
106
107 def __enter__(self):
108 if self.f is not None:
109 return
110 self.fd = os.open(self.path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC)
111 fcntl.flock(self.fd, fcntl.LOCK_EX)
112 os.truncate(self.fd, 0)
113 os.write(self.fd, str(self.owner).encode('utf-8'))
114 os.fsync(self.fd)
115
116 def __exit__(self, *exc_info):
117 #fcntl.flock(self.fd, fcntl.LOCK_UN)
118 os.truncate(self.fd, 0)
119 os.fsync(self.fd)
120 os.close(self.fd)
121 self.fd = -1
122
123 def lock(self):
124 self.__enter__()
125
126 def unlock(self):
127 self.__exit__()
128
129
130class Dir():
131 LOCK_FILE = 'lock'
132
133 def __init__(self, path):
134 self.path = path
135 self.lock_path = os.path.join(self.path, Dir.LOCK_FILE)
136
137 def lock(self, origin_id):
138 '''
139 return lock context, usage:
140
141 with my_dir.lock(origin):
142 read_from(my_dir.child('foo.txt'))
143 write_to(my_dir.child('bar.txt'))
144 '''
145 self.mkdir()
146 return FileLock(self.lock_path, origin_id)
147
148 @staticmethod
149 def ensure_abs_dir_exists(*path_elements):
150 l = len(path_elements)
151 if l < 1:
152 raise RuntimeError('Cannot create empty path')
153 if l == 1:
154 path = path_elements[0]
155 else:
156 path = os.path.join(*path_elements)
157 if not os.path.isdir(path):
158 os.makedirs(path)
159
160 def child(self, *rel_path):
161 if not rel_path:
162 return self.path
163 return os.path.join(self.path, *rel_path)
164
165 def mk_parentdir(self, *rel_path):
166 child = self.child(*rel_path)
167 child_parent = os.path.dirname(child)
168 Dir.ensure_abs_dir_exists(child_parent)
169 return child
170
171 def mkdir(self, *rel_path):
172 child = self.child(*rel_path)
173 Dir.ensure_abs_dir_exists(child)
174 return child
175
176 def children(self):
177 return os.listdir(self.path)
178
179 def exists(self, *rel_path):
180 return os.path.exists(self.child(*rel_path))
181
182 def isdir(self, *rel_path):
183 return os.path.isdir(self.child(*rel_path))
184
185 def isfile(self, *rel_path):
186 return os.path.isfile(self.child(*rel_path))
187
188 def new_child(self, *rel_path):
189 attempt = 1
190 prefix, suffix = os.path.splitext(self.child(*rel_path))
191 rel_path_fmt = '%s%%s%s' % (prefix, suffix)
192 while True:
193 path = rel_path_fmt % (('_%d'%attempt) if attempt > 1 else '')
194 if not os.path.exists(path):
195 break
196 attempt += 1
197 continue
198 Dir.ensure_abs_dir_exists(os.path.dirname(path))
199 return path
200
201 def rel_path(self, path):
202 return os.path.relpath(path, self.path)
203
204 def touch(self, *rel_path):
205 touch_file(self.child(*rel_path))
206
207 def new_file(self, *rel_path):
208 path = self.new_child(*rel_path)
209 touch_file(path)
210 return path
211
212 def new_dir(self, *rel_path):
213 path = self.new_child(*rel_path)
214 Dir.ensure_abs_dir_exists(path)
215 return path
216
217 def __str__(self):
218 return self.path
219 def __repr__(self):
220 return self.path
221
222def touch_file(path):
223 with open(path, 'a') as f:
224 f.close()
225
226def is_dict(l):
227 return isinstance(l, dict)
228
229def is_list(l):
230 return isinstance(l, (list, tuple))
231
232
233def dict_add(a, *b, **c):
234 for bb in b:
235 a.update(bb)
236 a.update(c)
237 return a
238
239def _hash_recurse(acc, obj, ignore_keys):
240 if is_dict(obj):
241 for key, val in sorted(obj.items()):
242 if key in ignore_keys:
243 continue
244 _hash_recurse(acc, val, ignore_keys)
245 return
246
247 if is_list(obj):
248 for item in obj:
249 _hash_recurse(acc, item, ignore_keys)
250 return
251
252 acc.update(str(obj).encode('utf-8'))
253
254def hash_obj(obj, *ignore_keys):
255 acc = hashlib.sha1()
256 _hash_recurse(acc, obj, ignore_keys)
257 return acc.hexdigest()
258
259
260def md5(of_content):
261 if isinstance(of_content, str):
262 of_content = of_content.encode('utf-8')
263 return hashlib.md5(of_content).hexdigest()
264
265def md5_of_file(path):
266 with open(path, 'rb') as f:
267 return md5(f.read())
268
269_tempdir = None
270
271def get_tempdir(remove_on_exit=True):
272 global _tempdir
273 if _tempdir is not None:
274 return _tempdir
275 _tempdir = tempfile.mkdtemp()
276 if remove_on_exit:
277 atexit.register(lambda: shutil.rmtree(_tempdir))
278 return _tempdir
279
280
281if hasattr(importlib.util, 'module_from_spec'):
282 def run_python_file(module_name, path):
283 spec = importlib.util.spec_from_file_location(module_name, path)
284 spec.loader.exec_module( importlib.util.module_from_spec(spec) )
285else:
286 from importlib.machinery import SourceFileLoader
287 def run_python_file(module_name, path):
288 SourceFileLoader(module_name, path).load_module()
289
290def msisdn_inc(msisdn_str):
291 'add 1 and preserve leading zeros'
292 return ('%%0%dd' % len(msisdn_str)) % (int(msisdn_str) + 1)
293
294class polling_stdin:
295 def __init__(self, stream):
296 self.stream = stream
297 self.fd = self.stream.fileno()
298 def __enter__(self):
299 self.original_stty = termios.tcgetattr(self.stream)
300 tty.setcbreak(self.stream)
301 self.orig_fl = fcntl.fcntl(self.fd, fcntl.F_GETFL)
302 fcntl.fcntl(self.fd, fcntl.F_SETFL, self.orig_fl | os.O_NONBLOCK)
303 def __exit__(self, *args):
304 fcntl.fcntl(self.fd, fcntl.F_SETFL, self.orig_fl)
305 termios.tcsetattr(self.stream, termios.TCSANOW, self.original_stty)
306
307def input_polling(poll_func, stream=None):
308 if stream is None:
309 stream = sys.stdin
310 unbuffered_stdin = os.fdopen(stream.fileno(), 'rb', buffering=0)
311 try:
312 with polling_stdin(unbuffered_stdin):
313 acc = []
314 while True:
315 poll_func()
316 got = unbuffered_stdin.read(1)
317 if got and len(got):
318 try:
319 # this is hacky: can't deal with multibyte sequences
320 got_str = got.decode('utf-8')
321 except:
322 got_str = '?'
323 acc.append(got_str)
324 sys.__stdout__.write(got_str)
325 sys.__stdout__.flush()
326 if '\n' in got_str:
327 return ''.join(acc)
328 time.sleep(.1)
329 finally:
330 unbuffered_stdin.close()
331
332# vim: expandtab tabstop=4 shiftwidth=4