|
| 1 | +from ...zerotier.converters import ZeroTier as BaseZeroTier |
| 2 | +from ..schema import schema |
| 3 | +from .base import OpenWrtConverter |
| 4 | + |
| 5 | + |
| 6 | +class ZeroTier(OpenWrtConverter, BaseZeroTier): |
| 7 | + _uci_types = ['zerotier'] |
| 8 | + _schema = schema['properties']['zerotier']['items'] |
| 9 | + |
| 10 | + def __intermediate_vpn(self, vpn): |
| 11 | + nwid_ifnames = vpn.get('networks', []) |
| 12 | + files = self.netjson.get('files', []) |
| 13 | + self.netjson['files'] = self.__get_zt_ifname_files(vpn, files) |
| 14 | + vpn.update( |
| 15 | + { |
| 16 | + '.name': self._get_uci_name(vpn.pop('name')), |
| 17 | + '.type': 'zerotier', |
| 18 | + 'config_path': vpn.get('config_path', '/etc/openwisp/zerotier'), |
| 19 | + 'copy_config_path': vpn.get('copy_config_path', '1'), |
| 20 | + 'join': [networks.get('id', '') for networks in nwid_ifnames], |
| 21 | + 'enabled': not vpn.pop('disabled', False), |
| 22 | + } |
| 23 | + ) |
| 24 | + del vpn['networks'] |
| 25 | + return super().__intermediate_vpn(vpn, remove=['']) |
| 26 | + |
| 27 | + def __netjson_vpn(self, vpn): |
| 28 | + nwids = vpn.pop('join') |
| 29 | + vpn['name'] = vpn.pop('.name') |
| 30 | + vpn['networks'] = [{"id": nwid, "ifname": f"owzt{nwid[-6:]}"} for nwid in nwids] |
| 31 | + # 'disabled' defaults to False in OpenWRT |
| 32 | + vpn['disabled'] = vpn.pop('enabled', '0') == '0' |
| 33 | + del vpn['.type'] |
| 34 | + return super().__netjson_vpn(vpn) |
| 35 | + |
| 36 | + def __get_zt_ifname_files(self, vpn, files): |
| 37 | + config_path = vpn.get('config_path', '/etc/openwisp/zerotier') |
| 38 | + nwid_ifnames = vpn.get('networks', []) |
| 39 | + zt_file_contents = '# network_id=interface_name\n' |
| 40 | + |
| 41 | + for networks in nwid_ifnames: |
| 42 | + nwid = networks.get('id', '') |
| 43 | + ifname = networks.get('ifname') |
| 44 | + zt_file_contents += f"{nwid}={ifname}\n" |
| 45 | + |
| 46 | + zt_interface_map = { |
| 47 | + 'path': f"{config_path}/devicemap", |
| 48 | + 'mode': '0644', |
| 49 | + 'contents': zt_file_contents, |
| 50 | + } |
| 51 | + |
| 52 | + if not files: |
| 53 | + return [zt_interface_map] |
| 54 | + updated_files = [] |
| 55 | + for file in files: |
| 56 | + if file.get('path') == zt_interface_map.get('path'): |
| 57 | + zt_interface_map['contents'] += '\n' + file['contents'] |
| 58 | + else: |
| 59 | + updated_files.append(file) |
| 60 | + if zt_interface_map.get('contents'): |
| 61 | + updated_files.append(zt_interface_map) |
| 62 | + return updated_files |
0 commit comments