Fix portability issue

The use of the "resource" module now prevents oslo.rootwrap from
being imported on Windows.

Although oslo.rootwrap is not effectively used on Windows, it's
important for it to at least be importable, since it's widely
used throughout OpenStack projects without having platform checks
in place.

This change checks if the "resource" module is avaialble before
attempting to use it.

Change-Id: I2391315f77718a3c9eb9fc8c03a6882237f33548
Closes-Bug: #1804639
This commit is contained in:
Lucian Petrut 2018-11-22 13:14:37 +02:00
parent 7e79f319a8
commit 8f148f5e9e
1 changed files with 23 additions and 16 deletions

View File

@ -33,7 +33,6 @@
from __future__ import print_function
import logging
import resource
import sys
from oslo_rootwrap import subprocess
@ -41,6 +40,12 @@ from oslo_rootwrap import wrapper
from six import moves
try:
# This isn't available on all platforms (e.g. Windows).
import resource
except ImportError:
resource = None
RC_UNAUTHORIZED = 99
RC_NOCOMMAND = 98
RC_BADCONFIG = 97
@ -85,21 +90,23 @@ def main(run_daemon=False):
_exit_error(execname, "Incorrect configuration file: %s" % configfile,
RC_BADCONFIG, log=False)
# When use close_fds=True on Python 2.x, we spend significant time
# in closing fds up to current soft ulimit, which could be large.
# Lower our ulimit to a reasonable value to regain performance.
fd_limits = resource.getrlimit(resource.RLIMIT_NOFILE)
sensible_fd_limit = min(config.rlimit_nofile, fd_limits[0])
if (fd_limits[0] > sensible_fd_limit):
# Unfortunately this inherits to our children, so allow them to
# re-raise by passing through the hard limit unmodified
resource.setrlimit(
resource.RLIMIT_NOFILE, (sensible_fd_limit, fd_limits[1]))
# This is set on import to the hard ulimit. if its defined we
# already have imported it, so we need to update it to the new limit
if (hasattr(subprocess, 'MAXFD') and
subprocess.MAXFD > sensible_fd_limit):
subprocess.MAXFD = sensible_fd_limit
if resource:
# When use close_fds=True on Python 2.x, we spend significant time
# in closing fds up to current soft ulimit, which could be large.
# Lower our ulimit to a reasonable value to regain performance.
fd_limits = resource.getrlimit(resource.RLIMIT_NOFILE)
sensible_fd_limit = min(config.rlimit_nofile, fd_limits[0])
if (fd_limits[0] > sensible_fd_limit):
# Unfortunately this inherits to our children, so allow them to
# re-raise by passing through the hard limit unmodified
resource.setrlimit(
resource.RLIMIT_NOFILE, (sensible_fd_limit, fd_limits[1]))
# This is set on import to the hard ulimit. if its defined we
# already have imported it, so we need to update it to the new
# limit.
if (hasattr(subprocess, 'MAXFD') and
subprocess.MAXFD > sensible_fd_limit):
subprocess.MAXFD = sensible_fd_limit
if config.use_syslog:
wrapper.setup_syslog(execname,