|
| 1 | +import logging |
| 2 | +import subprocess |
| 3 | +import tempfile |
| 4 | +from contextlib import contextmanager |
| 5 | +from urllib.parse import quote, urlunparse, urlparse |
| 6 | + |
| 7 | +from django import forms |
| 8 | +from django.conf import settings |
| 9 | +from django.utils.translation import gettext as _ |
| 10 | + |
| 11 | +from netbox.registry import registry |
| 12 | +from .choices import DataSourceTypeChoices |
| 13 | +from .exceptions import SyncError |
| 14 | + |
| 15 | +__all__ = ( |
| 16 | + 'LocalBackend', |
| 17 | + 'GitBackend', |
| 18 | +) |
| 19 | + |
| 20 | +logger = logging.getLogger('netbox.data_backends') |
| 21 | + |
| 22 | + |
| 23 | +def register_backend(name): |
| 24 | + """ |
| 25 | + Decorator for registering a DataBackend class. |
| 26 | + """ |
| 27 | + def _wrapper(cls): |
| 28 | + registry['data_backends'][name] = cls |
| 29 | + return cls |
| 30 | + |
| 31 | + return _wrapper |
| 32 | + |
| 33 | + |
| 34 | +class DataBackend: |
| 35 | + parameters = {} |
| 36 | + |
| 37 | + def __init__(self, url, **kwargs): |
| 38 | + self.url = url |
| 39 | + self.params = kwargs |
| 40 | + |
| 41 | + @property |
| 42 | + def url_scheme(self): |
| 43 | + return urlparse(self.url).scheme.lower() |
| 44 | + |
| 45 | + @contextmanager |
| 46 | + def fetch(self): |
| 47 | + raise NotImplemented() |
| 48 | + |
| 49 | + |
| 50 | +@register_backend(DataSourceTypeChoices.LOCAL) |
| 51 | +class LocalBackend(DataBackend): |
| 52 | + |
| 53 | + @contextmanager |
| 54 | + def fetch(self): |
| 55 | + logger.debug(f"Data source type is local; skipping fetch") |
| 56 | + local_path = urlparse(self.url).path # Strip file:// scheme |
| 57 | + |
| 58 | + yield local_path |
| 59 | + |
| 60 | + |
| 61 | +@register_backend(DataSourceTypeChoices.GIT) |
| 62 | +class GitBackend(DataBackend): |
| 63 | + parameters = { |
| 64 | + 'username': forms.CharField( |
| 65 | + required=False, |
| 66 | + label=_('Username'), |
| 67 | + widget=forms.TextInput(attrs={'class': 'form-control'}) |
| 68 | + ), |
| 69 | + 'password': forms.CharField( |
| 70 | + required=False, |
| 71 | + label=_('Password'), |
| 72 | + widget=forms.TextInput(attrs={'class': 'form-control'}) |
| 73 | + ), |
| 74 | + 'branch': forms.CharField( |
| 75 | + required=False, |
| 76 | + label=_('Branch'), |
| 77 | + widget=forms.TextInput(attrs={'class': 'form-control'}) |
| 78 | + ) |
| 79 | + } |
| 80 | + |
| 81 | + @contextmanager |
| 82 | + def fetch(self): |
| 83 | + local_path = tempfile.TemporaryDirectory() |
| 84 | + |
| 85 | + # Add authentication credentials to URL (if specified) |
| 86 | + username = self.params.get('username') |
| 87 | + password = self.params.get('password') |
| 88 | + if username and password: |
| 89 | + url_components = list(urlparse(self.url)) |
| 90 | + # Prepend username & password to netloc |
| 91 | + url_components[1] = quote(f'{username}@{password}:') + url_components[1] |
| 92 | + url = urlunparse(url_components) |
| 93 | + else: |
| 94 | + url = self.url |
| 95 | + |
| 96 | + # Compile git arguments |
| 97 | + args = ['git', 'clone', '--depth', '1'] |
| 98 | + if branch := self.params.get('branch'): |
| 99 | + args.extend(['--branch', branch]) |
| 100 | + args.extend([url, local_path.name]) |
| 101 | + |
| 102 | + # Prep environment variables |
| 103 | + env_vars = {} |
| 104 | + if settings.HTTP_PROXIES and self.url_scheme in ('http', 'https'): |
| 105 | + env_vars['http_proxy'] = settings.HTTP_PROXIES.get(self.url_scheme) |
| 106 | + |
| 107 | + logger.debug(f"Cloning git repo: {' '.join(args)}") |
| 108 | + try: |
| 109 | + subprocess.run(args, check=True, capture_output=True, env=env_vars) |
| 110 | + except subprocess.CalledProcessError as e: |
| 111 | + raise SyncError( |
| 112 | + f"Fetching remote data failed: {e.stderr}" |
| 113 | + ) |
| 114 | + |
| 115 | + yield local_path.name |
| 116 | + |
| 117 | + local_path.cleanup() |
0 commit comments