Skip to content

Commit c7635b6

Browse files
committed
Close (almost) all file handles
What's remaining are tests and file serving in WSGI app. The WGSI app use is probably fine but also not a problem for us currently.
1 parent 12f1349 commit c7635b6

File tree

20 files changed

+94
-85
lines changed

20 files changed

+94
-85
lines changed

pulsar/client/action_mapper.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,8 @@ def from_dict(cls, action_dict):
446446
return RemoteCopyAction(source=action_dict["source"])
447447

448448
def write_to_path(self, path):
449-
copy_to_path(open(self.path, "rb"), path)
449+
with open(self.path, "rb") as f:
450+
copy_to_path(f, path)
450451

451452
def write_from_path(self, pulsar_path):
452453
destination = self.path
@@ -534,7 +535,8 @@ def write_to_path(self, path):
534535
object_store_id=object_store_ref["object_store_id"],
535536
)
536537
filename = self.object_store.get_filename(dataset_object)
537-
copy_to_path(open(filename, 'rb'), path)
538+
with open(filename, "rb") as f:
539+
copy_to_path(f, path)
538540

539541
def write_from_path(self, pulsar_path):
540542
raise NotImplementedError("Writing raw files to object store not supported at this time.")
@@ -660,7 +662,8 @@ def from_dict(cls, action_dict):
660662
return MessageAction(contents=action_dict["contents"])
661663

662664
def write_to_path(self, path):
663-
open(path, "w").write(self.contents)
665+
with open(path, "w") as f:
666+
f.write(self.contents)
664667

665668

666669
DICTIFIABLE_ACTION_CLASSES = [

pulsar/client/staging/up.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -579,11 +579,8 @@ def _read(path):
579579
Utility method to quickly read small files (config files and tool
580580
wrappers) into memory as bytes.
581581
"""
582-
input = open(path, encoding="utf-8")
583-
try:
582+
with open(path, encoding="utf-8") as input:
584583
return input.read()
585-
finally:
586-
input.close()
587584

588585

589586
__all__ = ['submit_job']

pulsar/client/transport/curl.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,16 @@ def __init__(self, timeout=None, **kwrgs):
3333

3434
def execute(self, url, method=None, data=None, input_path=None, output_path=None):
3535
buf = _open_output(output_path)
36+
input_fh = None
3637
try:
3738
c = _new_curl_object_for_url(url)
3839
c.setopt(c.WRITEFUNCTION, buf.write)
3940
if method:
4041
c.setopt(c.CUSTOMREQUEST, method)
4142
if input_path:
43+
input_fh = open(input_path, "rb")
4244
c.setopt(c.UPLOAD, 1)
43-
c.setopt(c.READFUNCTION, open(input_path, 'rb').read)
45+
c.setopt(c.READFUNCTION, input_fh.read)
4446
filesize = os.path.getsize(input_path)
4547
c.setopt(c.INFILESIZE, filesize)
4648
if data:
@@ -61,6 +63,8 @@ def execute(self, url, method=None, data=None, input_path=None, output_path=None
6163
return buf.getvalue()
6264
finally:
6365
buf.close()
66+
if input_fh:
67+
input_fh.close()
6468

6569

6670
def post_file(url, path):

pulsar/client/transport/poster.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,10 @@
2626
def post_file(url, path):
2727
__ensure_poster()
2828
try:
29-
datagen, headers = poster.encode.multipart_encode({"file": open(path, "rb")})
30-
request = Request(url, datagen, headers)
31-
return urlopen(request).read()
29+
with open(path, "rb") as fh:
30+
datagen, headers = poster.encode.multipart_encode({"file": fh})
31+
request = Request(url, datagen, headers)
32+
return urlopen(request).read()
3233
except Exception:
3334
log.exception("Problem with poster post of [%s]" % path)
3435
raise

pulsar/client/transport/requests.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@ def post_file(url, path):
2121
raise ImportError(REQUESTS_TOOLBELT_UNAVAILABLE_MESSAGE)
2222

2323
__ensure_requests()
24-
m = requests_toolbelt.MultipartEncoder(
25-
fields={'file': ('filename', open(path, 'rb'))}
26-
)
27-
requests.post(url, data=m, headers={'Content-Type': m.content_type})
24+
with open(path, "rb") as f:
25+
m = requests_toolbelt.MultipartEncoder(
26+
fields={'file': ('filename', f)}
27+
)
28+
requests.post(url, data=m, headers={'Content-Type': m.content_type})
2829

2930

3031
def get_file(url, path):

pulsar/client/util.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -40,19 +40,16 @@ def copy_to_path(object, path):
4040
"""
4141
Copy file-like object to path.
4242
"""
43-
output = open(path, 'wb')
44-
_copy_and_close(object, output)
43+
with open(path, 'wb') as output:
44+
_copy(object, output)
4545

4646

47-
def _copy_and_close(object, output):
48-
try:
49-
while True:
50-
buffer = object.read(BUFFER_SIZE)
51-
if not buffer:
52-
break
53-
output.write(buffer)
54-
finally:
55-
output.close()
47+
def _copy(object, output):
48+
while True:
49+
buffer = object.read(BUFFER_SIZE)
50+
if not buffer:
51+
break
52+
output.write(buffer)
5653

5754

5855
# Variant of base64 compat layer inspired by BSD code from Bcfg2
@@ -283,10 +280,12 @@ def __contains__(self, item):
283280
return exists(self.__path(item))
284281

285282
def __setitem__(self, key, value):
286-
open(self.__path(key), 'w').write(json.dumps(value))
283+
with open(self.__path(key), "w") as f:
284+
f.write(json.dumps(value))
287285

288286
def __getitem__(self, key):
289-
return json.loads(open(self.__path(key)).read())
287+
with open(self.__path(key)) as f:
288+
return json.loads(f.read())
290289

291290
def __delitem__(self, key):
292291
try:

pulsar/manager_factory.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ def build_managers(app, conf):
5252

5353
def _populate_manager_descriptions_from_ini(manager_descriptions, job_managers_config):
5454
config = configparser.ConfigParser()
55-
config.readfp(open(job_managers_config))
55+
with open(job_managers_config) as config_fh:
56+
config.read_file(config_fh)
5657
for section in config.sections():
5758
if not section.startswith(MANAGER_PREFIX):
5859
continue

pulsar/managers/base/__init__.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,8 @@ def _check_execution(self, job_id, tool_id, command_line):
186186
for file in self._list_dir(tool_files_dir):
187187
if os.path.isdir(join(tool_files_dir, file)):
188188
continue
189-
contents = open(join(tool_files_dir, file)).read()
189+
with open(join(tool_files_dir, file)) as fh:
190+
contents = fh.read()
190191
log.debug("job_id: {} - checking tool file {}".format(job_id, file))
191192
authorization.authorize_tool_file(basename(file), contents)
192193
config_files_dir = job_directory.configs_directory()
@@ -255,28 +256,21 @@ def calculate_path(self, remote_path, input_type):
255256

256257
def read_file(self, name, size=-1, default=None):
257258
path = self._job_file(name)
258-
job_file = None
259259
try:
260-
job_file = open(path, 'rb')
261-
return job_file.read(size)
260+
with open(path, 'rb') as job_file:
261+
return job_file.read(size)
262262
except Exception:
263263
if default is not None:
264264
return default
265265
else:
266266
raise
267-
finally:
268-
if job_file:
269-
job_file.close()
270267

271268
def write_file(self, name, contents):
272269
path = self._job_file(name)
273-
job_file = open(path, 'wb')
274-
try:
275-
if isinstance(contents, str):
276-
contents = contents.encode("UTF-8")
270+
if isinstance(contents, str):
271+
contents = contents.encode("UTF-8")
272+
with open(path, "wb") as job_file:
277273
job_file.write(contents)
278-
finally:
279-
job_file.close()
280274
return path
281275

282276
def remove_file(self, name):

pulsar/managers/queued_condor.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ def launch(self, job_id, command_line, submit_params={}, dependencies_descriptio
4141
setup_params=setup_params
4242
)
4343
log_path = self.__condor_user_log(job_id)
44-
open(log_path, 'w') # Touch log file
44+
with open(log_path, "w"):
45+
# Touch log file
46+
pass
4547

4648
submit_params.update(self.submission_params)
4749
build_submit_params = dict(

pulsar/managers/queued_external_drmaa.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ def launch(self, job_id, command_line, submit_params={}, dependencies_descriptio
4444
submit_params=submit_params,
4545
setup_params=setup_params,
4646
)
47-
print(open(attributes['remoteCommand']).read())
47+
with open(attributes["remoteCommand"]) as fh:
48+
print(fh.read())
4849
job_attributes_file = self._write_job_file(job_id, 'jt.json', dumps(attributes))
4950
user = submit_params.get('user', None)
5051
log.info("Submit as user %s" % user)

0 commit comments

Comments
 (0)