"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "src/fuglu/mixins.py" between
fuglu-0.10.8.tar.gz and fuglu-1.0.0.tar.gz

About: FuGlu is a mail scanning daemon for Postfix written in Python. It acts as a glue application between the MTA and spam checkers and antivirus software.

mixins.py  (fuglu-0.10.8):mixins.py  (fuglu-1.0.0)
skipping to change at line 19 skipping to change at line 19
# #
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# #
# #
import time
import typing as tp
from typing import Dict, Optional from typing import Dict, Optional
from configparser import RawConfigParser, _UNSET from configparser import RawConfigParser, _UNSET
class ConfigWrapper: class ConfigWrapper(object):
"""Wrap a RawConfigParser object defining default values by a dict""" """Wrap a RawConfigParser object defining default values by a dict"""
def __init__(self, config: RawConfigParser, defaultdict: Optional[Dict] = No ne): def __init__(self, config: RawConfigParser, defaultdict: Optional[Dict] = No ne):
self._config = config self._config = config
self._defaultdict = defaultdict self._defaultdict = defaultdict
def _get_fallback(self, option, **kwargs): def _get_fallback(self, option, **kwargs):
"""Extract fallback argument from parameters, set fallback from defaults """ """Extract fallback argument from parameters, set fallback from defaults """
if 'fallback' in kwargs: if 'fallback' in kwargs:
fallback = kwargs.pop('fallback') fallback = kwargs.pop('fallback')
else: else:
skipping to change at line 85 skipping to change at line 87
class dictionary. class dictionary.
""" """
if fallback == _UNSET: if fallback == _UNSET:
fallback = self._get_fallback(option, **kwargs) fallback = self._get_fallback(option, **kwargs)
if isinstance(fallback, str): if isinstance(fallback, str):
# convert using RawConfigParser method # convert using RawConfigParser method
fallback = self._config._convert_to_boolean(fallback) fallback = self._config._convert_to_boolean(fallback)
return self._config.getboolean(section, option, fallback=fallback, **kwa rgs) return self._config.getboolean(section, option, fallback=fallback, **kwa rgs)
def getlist(self, section: str, option: str, fallback=_UNSET, **kwargs):
"""
Wraps FuConfigParser.getlist with default fallback from internal
class dictionary.
"""
#from .shared import FuConfigParser
#self._config: FuConfigParser
if fallback == _UNSET:
fallback = self._get_fallback(option, **kwargs)
return self._config.getlist(section, option, fallback=fallback, **kwargs
)
def __getattr__(self, name): def __getattr__(self, name):
""" """
Delegate to RawConfigParser. Delegate to RawConfigParser.
""" """
return getattr(self._config, name) return getattr(self._config, name)
class DefConfigMixin: class DefConfigMixin(object):
def __init__(self, config): def __init__(self, config):
self._config = ConfigWrapper(config, None) self._config = ConfigWrapper(config, None)
self._rawconfig = config self._rawconfig = config
@property @property
def config(self): def config(self):
try: try:
if self._config._defaultdict is not self.requiredvars: if self._config._defaultdict is not self.requiredvars:
self._config._defaultdict = self.requiredvars self._config._defaultdict = self.requiredvars
except AttributeError: except AttributeError:
pass pass
return self._config return self._config
@config.setter @config.setter
def config(self, newconfig: RawConfigParser): def config(self, newconfig: RawConfigParser):
if self._rawconfig is not newconfig: if self._rawconfig is not newconfig:
self._config = ConfigWrapper(newconfig, None) self._config = ConfigWrapper(newconfig, None)
class SimpleTimeoutMixin(object):
"""Simple timeout mixin for given tags"""
def __init__(self):
self._stimedict = {}
self._stimehit = {}
def stimeout_set_timer(self, name: str, timeout: float):
if timeout:
now = time.time()
self._stimedict[name] = (now + timeout, now, timeout)
def stimeout_continue(self, name: str):
timeout_end, timeout_start, timeout_duration = self._stimedict.get(name,
(0, 0, 0))
if timeout_end and time.time() > timeout_end:
self._stimehit[name] = True
return False
else:
return True
def stimeout_string(self, name: str):
timeout_end, timeout_start, timeout_duration = self._stimedict.get(name,
(0, 0, 0))
if timeout_duration:
return f"timeout(real/limit) = {(time.time()-timeout_start):.1f}/{ti
meout_duration:.1f} [s]"
else:
return "no timeout"
class ReturnOverrideMixin(object):
def __init__(self, config, section: tp.Optional[str] = None):
super().__init__(config, section=section)
self._overrideaction = -1
self._milt_overrideaction = b"undefined"
self._overridemessage = None
@property
def overrideaction(self):
"""get override-action which will be returned instead of 'real' plugin o
utput"""
if isinstance(self._overrideaction, int) and self._overrideaction < 0:
# setup return code override if given in config
self._overrideaction = None
try:
overrideaction = self.config.get(self.section, 'overrideaction')
except Exception:
overrideaction = None
try:
overridemessage = self.config.get(self.section, 'overridemessage
')
overridemessage = overridemessage.strip()
except Exception:
overridemessage = None
if overrideaction:
from fuglu.shared import string_to_actioncode
# import here to prevent circular dependency
self._overrideaction = string_to_actioncode(overrideaction, self
.config)
if overridemessage:
self._overridemessage = overridemessage
return self._overrideaction
@property
def milter_overrideaction(self):
if isinstance(self._milt_overrideaction, bytes) and self._milt_overridea
ction == b"undefined":
self._milt_overrideaction = None
from fuglu.mshared import retcode2milter
if self.overrideaction is not None:
self._milt_overrideaction = retcode2milter.get(self.overrideacti
on)
return self._milt_overrideaction
def _check_apply_override(self,
out: tp.Optional[tp.Union[int, tp.Tuple[int, str]]
] = None,
suspectid: str = "<>") -> tp.Optional[tp.Union[int
, tp.Tuple[int, str]]]:
"""Run examine method of plugin + additional pre/post calculations"""
from fuglu.shared import actioncode_to_string
# import here to prevent circular dependency
if isinstance(out, tuple):
ret, msg = out
else:
ret = out
msg = None
if self.overrideaction is not None:
if ret is not None and ret != self.overrideaction:
plugin_return = actioncode_to_string(ret)
plugin_msg = msg if msg else ""
override_return = actioncode_to_string(self.overrideaction)
override_msg = self._overridemessage if self._overridemessage el
se ""
self._logger().warning(f"{suspectid} overrideaction: "
f"plugin={plugin_return}/msg={plugin_msg}
, "
f"override={override_return}/msg={overrid
e_msg}")
ret = self.overrideaction
msg = self._overridemessage
if msg is not None:
return ret, msg
else:
return ret
def _check_apply_override_milter(self,
out: tp.Optional[tp.Union[int, tp.Tuple[int
, str]]] = None,
suspectid: str = "<>") -> tp.Union[bytes, t
p.Tuple[bytes, str]]:
from fuglu.connectors.milterconnector import RETCODE2STR
# import here to prevent circular dependency
if isinstance(out, tuple):
ret, msg = out
else:
ret = out
msg = None
if self.milter_overrideaction is not None:
if ret is not None and ret != self.milter_overrideaction:
plugin_return = RETCODE2STR.get(ret)
plugin_msg = msg if msg else ""
override_return = RETCODE2STR.get(self.milter_overrideaction)
override_msg = self._overridemessage if self._overridemessage el
se ""
self._logger().warning(f"{suspectid} overrideaction: "
f"plugin={plugin_return}/msg={plugin_msg}
, "
f"override={override_return}/msg={overrid
e_msg}")
ret = self.milter_overrideaction
msg = self._overridemessage
if msg is not None:
return ret, msg
else:
return ret
 End of changes. 5 change blocks. 
2 lines changed or deleted 16 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)