python/samba: Fix py2/3 relative module import issue
[samba.git] / python / samba / gp_ext_loader.py
1 # Group Policy Client Side Extension Loader
2 # Copyright (C) David Mulder <dmulder@suse.com> 2018
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 import os
18 from samba.gpclass import list_gp_extensions
19 from samba.gpclass import gp_ext
20
21 try:
22     import importlib.util
23
24     def import_file(name, location):
25         spec = importlib.util.spec_from_file_location(name, location)
26         module = importlib.util.module_from_spec(spec)
27         spec.loader.exec_module(module)
28         return module
29 except ImportError:
30     import imp
31
32     def import_file(name, location):
33         return imp.load_source(name, location)
34
35
36 def get_gp_ext_from_module(name, mod):
37     if mod:
38         for k, v in vars(mod).items():
39             if k == name and issubclass(v, gp_ext):
40                 return v
41     return None
42
43
44 def get_gp_client_side_extensions(logger, smb_conf):
45     user_exts = []
46     machine_exts = []
47     gp_exts = list_gp_extensions(smb_conf)
48     for gp_ext in gp_exts.values():
49         module = import_file(gp_ext['ProcessGroupPolicy'], gp_ext['DllName'])
50         ext = get_gp_ext_from_module(gp_ext['ProcessGroupPolicy'], module)
51         if ext and gp_ext['MachinePolicy']:
52             machine_exts.append(ext)
53             logger.info('Loaded machine extension from %s: %s'
54                         % (gp_ext['DllName'], ext.__name__))
55         if ext and gp_ext['UserPolicy']:
56             user_exts.append(ext)
57             logger.info('Loaded user extension from %s: %s'
58                         % (gp_ext['DllName'], ext.__name__))
59     return (machine_exts, user_exts)