sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def load_from_environ(): """ Load the SMC URL, API KEY and optional SSL certificate from the environment. Fields are:: SMC_ADDRESS=http://1.1.1.1:8082 SMC_API_KEY=123abc SMC_CLIENT_CERT=path/to/cert SMC_TIMEOUT = 30 (seconds) SMC_API_VERSION = 6.1 (optional - uses latest by default) SMC_DOMAIN = name of domain, Shared is default SMC_EXTRA_ARGS = string in dict format of extra args needed SMC_CLIENT CERT is only checked IF the SMC_URL is an HTTPS url. Example of forcing retry on service unavailable:: os.environ['SMC_EXTRA_ARGS'] = '{"retry_on_busy": "True"}' """ try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse smc_address = os.environ.get('SMC_ADDRESS', '') smc_apikey = os.environ.get('SMC_API_KEY', '') smc_timeout = os.environ.get('SMC_TIMEOUT', None) api_version = os.environ.get('SMC_API_VERSION', None) domain = os.environ.get('SMC_DOMAIN', None) smc_extra_args = os.environ.get('SMC_EXTRA_ARGS', '') if not smc_apikey or not smc_address: raise ConfigLoadError( 'If loading from environment variables, you must provide values ' 'SMC_ADDRESS and SMC_API_KEY.') config_dict = {} if smc_extra_args: try: args_as_dict = json.loads(smc_extra_args) config_dict.update(args_as_dict) except ValueError: pass config_dict.update(smc_apikey=smc_apikey) config_dict.update(timeout=smc_timeout) config_dict.update(api_version=api_version) config_dict.update(domain=domain) url = urlparse(smc_address) config_dict.update(smc_address=url.hostname) port = url.port if not port: port = '8082' config_dict.update(smc_port=port) if url.scheme == 'https': config_dict.update(smc_ssl=True) ssl_cert = os.environ.get('SMC_CLIENT_CERT', None) if ssl_cert: # Enable cert validation config_dict.update(verify_ssl=True) config_dict.update(ssl_cert_file=ssl_cert) # Else http return transform_login(config_dict)
Load the SMC URL, API KEY and optional SSL certificate from the environment. Fields are:: SMC_ADDRESS=http://1.1.1.1:8082 SMC_API_KEY=123abc SMC_CLIENT_CERT=path/to/cert SMC_TIMEOUT = 30 (seconds) SMC_API_VERSION = 6.1 (optional - uses latest by default) SMC_DOMAIN = name of domain, Shared is default SMC_EXTRA_ARGS = string in dict format of extra args needed SMC_CLIENT CERT is only checked IF the SMC_URL is an HTTPS url. Example of forcing retry on service unavailable:: os.environ['SMC_EXTRA_ARGS'] = '{"retry_on_busy": "True"}'
entailment
def load_from_file(alt_filepath=None): """ Attempt to read the SMC configuration from a dot(.) file in the users home directory. The order in which credentials are parsed is: - Passing credentials as parameters to the session login - Shared credential file (~/.smcrc) - Environment variables :param alt_filepath: Specify a different file name for the configuration file. This should be fully qualified and include the name of the configuration file to read. Configuration file should look like:: [smc] smc_address=172.18.1.150 smc_apikey=xxxxxxxxxxxxxxxxxxx api_version=6.1 smc_port=8082 smc_ssl=True verify_ssl=True retry_on_busy=True ssl_cert_file='/Users/davidlepage/home/mycacert.pem' :param str smc_address: IP of the SMC Server :param str smc_apikey: obtained from creating an API Client in SMC :param str api_version: Which version to use (default: latest) :param int smc_port: port to use for SMC, (default: 8082) :param bool smc_ssl: Whether to use SSL (default: False) :param bool verify_ssl: Verify client cert (default: False) :param bool retry_on_busy: Retry CRUD operation if service is unavailable (default: False) :param str ssl_cert_file: Full path to client pem (default: None) The only settings that are required are smc_address and smc_apikey. Setting verify_ssl to True (default) validates the client cert for SSL connections and requires the ssl_cert_file path to the cacert.pem. If not given, verify will default back to False. FQDN will be constructed from the information above. """ required = ['smc_address', 'smc_apikey'] bool_type = ['smc_ssl', 'verify_ssl', 'retry_on_busy'] # boolean option flag option_names = ['smc_port', 'api_version', 'smc_ssl', 'verify_ssl', 'ssl_cert_file', 'retry_on_busy', 'timeout', 'domain'] parser = configparser.SafeConfigParser(defaults={ 'smc_port': '8082', 'api_version': None, 'smc_ssl': 'false', 'verify_ssl': 'false', 'ssl_cert_file': None, 'timeout': None, 'domain': None}, allow_no_value=True) path = '~/.smcrc' if alt_filepath is not None: full_path = alt_filepath else: ex_path = os.path.expandvars(path) full_path = os.path.expanduser(ex_path) section = 'smc' config_dict = {} try: with io.open(full_path, 'rt', encoding='UTF-8') as f: parser.readfp(f) # Get required settings, if not found it will raise err for name in required: config_dict[name] = parser.get(section, name) for name in option_names: if parser.has_option(section, name): if name in bool_type: config_dict[name] = parser.getboolean(section, name) else: # str config_dict[name] = parser.get(section, name) except configparser.NoOptionError as e: raise ConfigLoadError('Failed loading credentials from configuration ' 'file: {}; {}'.format(path, e)) except (configparser.NoSectionError, configparser.MissingSectionHeaderError) as e: raise ConfigLoadError('Failed loading credential file from: {}, check the ' 'path and verify contents are correct.'.format(path, e)) except IOError as e: raise ConfigLoadError( 'Failed loading configuration file: {}'.format(e)) return transform_login(config_dict)
Attempt to read the SMC configuration from a dot(.) file in the users home directory. The order in which credentials are parsed is: - Passing credentials as parameters to the session login - Shared credential file (~/.smcrc) - Environment variables :param alt_filepath: Specify a different file name for the configuration file. This should be fully qualified and include the name of the configuration file to read. Configuration file should look like:: [smc] smc_address=172.18.1.150 smc_apikey=xxxxxxxxxxxxxxxxxxx api_version=6.1 smc_port=8082 smc_ssl=True verify_ssl=True retry_on_busy=True ssl_cert_file='/Users/davidlepage/home/mycacert.pem' :param str smc_address: IP of the SMC Server :param str smc_apikey: obtained from creating an API Client in SMC :param str api_version: Which version to use (default: latest) :param int smc_port: port to use for SMC, (default: 8082) :param bool smc_ssl: Whether to use SSL (default: False) :param bool verify_ssl: Verify client cert (default: False) :param bool retry_on_busy: Retry CRUD operation if service is unavailable (default: False) :param str ssl_cert_file: Full path to client pem (default: None) The only settings that are required are smc_address and smc_apikey. Setting verify_ssl to True (default) validates the client cert for SSL connections and requires the ssl_cert_file path to the cacert.pem. If not given, verify will default back to False. FQDN will be constructed from the information above.
entailment
def transform_login(config): """ Parse login data as dict. Called from load_from_file and also can be used when collecting information from other sources as well. :param dict data: data representing the valid key/value pairs from smcrc :return: dict dict of settings that can be sent into session.login """ verify = True if config.pop('smc_ssl', None): scheme = 'https' verify = config.pop('ssl_cert_file', None) if config.pop('verify_ssl', None): # Get cert path to verify if not verify: # Setting omitted or already False verify = False else: verify = False else: scheme = 'http' config.pop('verify_ssl', None) config.pop('ssl_cert_file', None) verify = False transformed = {} url = '{}://{}:{}'.format( scheme, config.pop('smc_address', None), config.pop('smc_port', None)) timeout = config.pop('timeout', None) if timeout: try: timeout = int(timeout) except ValueError: timeout = None api_version = config.pop('api_version', None) if api_version: try: float(api_version) except ValueError: api_version = None transformed.update( url=url, api_key=config.pop('smc_apikey', None), api_version=api_version, verify=verify, timeout=timeout, domain=config.pop('domain', None)) if config: transformed.update(kwargs=config) # Any remaining args return transformed
Parse login data as dict. Called from load_from_file and also can be used when collecting information from other sources as well. :param dict data: data representing the valid key/value pairs from smcrc :return: dict dict of settings that can be sent into session.login
entailment
def within_ipv4_network(self, field, values): """ This filter adds specified networks to a filter to check for inclusion. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: network definitions, in cidr format, i.e: 1.1.1.0/24. """ v = ['ipv4_net("%s")' % net for net in values] self.update_filter('{} IN union({})'.format(field, ','.join(v)))
This filter adds specified networks to a filter to check for inclusion. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: network definitions, in cidr format, i.e: 1.1.1.0/24.
entailment
def within_ipv4_range(self, field, values): """ Add an IP range network filter for relevant address fields. Range (between) filters allow only one range be provided. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: IP range values. Values would be a list of IP's separated by a '-', i.e. ['1.1.1.1-1.1.1.254'] """ v = ['ipv4("%s")' % part for iprange in values for part in iprange.split('-')] self.update_filter('{} IN range({})'.format(field, ','.join(v)))
Add an IP range network filter for relevant address fields. Range (between) filters allow only one range be provided. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: IP range values. Values would be a list of IP's separated by a '-', i.e. ['1.1.1.1-1.1.1.254']
entailment
def exact_ipv4_match(self, field, values): """ An exact IPv4 address match on relevant address fields. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: value/s to add. If more than a single value is provided, the query is modified to use UNION vs. == :param bool complex: A complex filter is one which requires AND'ing or OR'ing values. Set to return the filter before committing. """ if len(values) > 1: v = ['ipv4("%s")' % ip for ip in values] value='{} IN union({})'.format(field, ','.join(v)) else: value='{} == ipv4("{}")'.format(field, values[0]) self.update_filter(value)
An exact IPv4 address match on relevant address fields. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: value/s to add. If more than a single value is provided, the query is modified to use UNION vs. == :param bool complex: A complex filter is one which requires AND'ing or OR'ing values. Set to return the filter before committing.
entailment
def download(self, timeout=5, wait_for_finish=False): """ Download Package or Engine Update :param int timeout: timeout between queries :raises TaskRunFailed: failure during task status :rtype: TaskOperationPoller """ return Task.execute(self, 'download', timeout=timeout, wait_for_finish=wait_for_finish)
Download Package or Engine Update :param int timeout: timeout between queries :raises TaskRunFailed: failure during task status :rtype: TaskOperationPoller
entailment
def activate(self, resource=None, timeout=3, wait_for_finish=False): """ Activate this package on the SMC :param list resource: node href's to activate on. Resource is only required for software upgrades :param int timeout: timeout between queries :raises TaskRunFailed: failure during activation (downloading, etc) :rtype: TaskOperationPoller """ return Task.execute(self, 'activate', json={'resource': resource}, timeout=timeout, wait_for_finish=wait_for_finish)
Activate this package on the SMC :param list resource: node href's to activate on. Resource is only required for software upgrades :param int timeout: timeout between queries :raises TaskRunFailed: failure during activation (downloading, etc) :rtype: TaskOperationPoller
entailment
def all(self): """ Return all entries :rtype: list(dict) """ attribute = self._attr[0] return self.profile.data.get(attribute, [])
Return all entries :rtype: list(dict)
entailment
def create(cls, name, sandbox_data_center, portal_username=None, comment=None): """ Create a Sandbox Service element """ json = { 'name': name, 'sandbox_data_center': element_resolver(sandbox_data_center), 'portal_username': portal_username if portal_username else '', 'comment': comment} return ElementCreator(cls, json)
Create a Sandbox Service element
entailment
def available_api_versions(base_url, timeout=10, verify=True): """ Get all available API versions for this SMC :return version numbers :rtype: list """ try: r = requests.get('%s/api' % base_url, timeout=timeout, verify=verify) # no session required if r.status_code == 200: j = json.loads(r.text) versions = [] for version in j['version']: versions.append(version['rel']) return versions raise SMCConnectionError( 'Invalid status received while getting entry points from SMC. ' 'Status code received %s. Reason: %s' % (r.status_code, r.reason)) except requests.exceptions.RequestException as e: raise SMCConnectionError(e)
Get all available API versions for this SMC :return version numbers :rtype: list
entailment
def get_api_version(base_url, api_version=None, timeout=10, verify=True): """ Get the API version specified or resolve the latest version :return api version :rtype: float """ versions = available_api_versions(base_url, timeout, verify) newest_version = max([float(i) for i in versions]) if api_version is None: # Use latest api_version = newest_version else: if api_version not in versions: api_version = newest_version return api_version
Get the API version specified or resolve the latest version :return api version :rtype: float
entailment
def create(cls, sessions=None): """ A session manager will be mounted to the SMCRequest class through this classmethod. If there is already an existing SessionManager, that is returned instead. :param list sessions: a list of Session objects :rtype: SessionManager """ manager = getattr(SMCRequest, '_session_manager') if manager is not None: return manager manager = SessionManager(sessions) manager.mount() return manager
A session manager will be mounted to the SMCRequest class through this classmethod. If there is already an existing SessionManager, that is returned instead. :param list sessions: a list of Session objects :rtype: SessionManager
entailment
def get_default_session(self): """ The default session is nothing more than the first session added into the session handler pool. This will likely change in the future but for now each session identifies the domain and also manages domain switching within a single session. :rtype: Session """ if self._sessions: return self.get_session(next(iter(self._sessions))) return self.get_session()
The default session is nothing more than the first session added into the session handler pool. This will likely change in the future but for now each session identifies the domain and also manages domain switching within a single session. :rtype: Session
entailment
def _register(self, session): """ Register a session """ if session.session_id: self._sessions[session.name] = session
Register a session
entailment
def _deregister(self, session): """ Deregister a session. """ if session in self: self._sessions.pop(self._get_session_key(session), None)
Deregister a session.
entailment
def manager(self): """ Return the session manager for this session :rtype: SessionManager """ manager = SMCRequest._session_manager if not self._manager \ else self._manager if not manager: raise SessionManagerNotFound('A session manager was not found. ' 'This is an initialization error binding the SessionManager. ') return manager
Return the session manager for this session :rtype: SessionManager
entailment
def session_id(self): """ The session ID in header type format. Can be inserted into a connection if necessary using:: {'Cookie': session.session_id} :rtype: str """ return None if not self.session or 'JSESSIONID' not in \ self.session.cookies else 'JSESSIONID={}'.format( self.session.cookies['JSESSIONID'])
The session ID in header type format. Can be inserted into a connection if necessary using:: {'Cookie': session.session_id} :rtype: str
entailment
def name(self): """ Return the administrator name for this session. Can be None if the session has not yet been established. .. note:: The administrator name was introduced in SMC version 6.4. Previous versions will show the unique session identifier for this session. :rtype: str """ if self.session: # protect cached property from being set before session try: return self.current_user.name except AttributeError: # TODO: Catch ConnectionError? No session pass return hash(self)
Return the administrator name for this session. Can be None if the session has not yet been established. .. note:: The administrator name was introduced in SMC version 6.4. Previous versions will show the unique session identifier for this session. :rtype: str
entailment
def current_user(self): """ .. versionadded:: 0.6.0 Requires SMC version >= 6.4 Return the currently logged on API Client user element. :raises UnsupportedEntryPoint: Current user is only supported with SMC version >= 6.4 :rtype: Element """ if self.session: try: response = self.session.get(self.entry_points.get('current_user')) if response.status_code in (200, 201): admin_href=response.json().get('value') request = SMCRequest(href=admin_href) smcresult = send_request(self, 'get', request) return ElementFactory(admin_href, smcresult) except UnsupportedEntryPoint: pass
.. versionadded:: 0.6.0 Requires SMC version >= 6.4 Return the currently logged on API Client user element. :raises UnsupportedEntryPoint: Current user is only supported with SMC version >= 6.4 :rtype: Element
entailment
def login(self, url=None, api_key=None, login=None, pwd=None, api_version=None, timeout=None, verify=True, alt_filepath=None, domain=None, **kwargs): """ Login to SMC API and retrieve a valid session. Sessions use a pool connection manager to provide dynamic scalability during times of increased load. Each session is managed by a global session manager making it possible to have more than one session per interpreter. An example login and logout session:: from smc import session session.login(url='http://1.1.1.1:8082', api_key='SomeSMCG3ener@t3dPwd') .....do stuff..... session.logout() :param str url: ip of SMC management server :param str api_key: API key created for api client in SMC :param str login: Administrator user in SMC that has privilege to SMC API. :param str pwd: Password for user login. :param api_version (optional): specify api version :param int timeout: (optional): specify a timeout for initial connect; (default 10) :param str|boolean verify: verify SSL connections using cert (default: verify=True) You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs :param str alt_filepath: If using .smcrc, alternate path+filename :param str domain: domain to log in to. If domains are not configured, this field will be ignored and api client logged in to 'Shared Domain'. :param bool retry_on_busy: pass as kwarg with boolean if you want to add retries if the SMC returns HTTP 503 error during operation. You can also optionally customize this behavior and call :meth:`.set_retry_on_busy` :raises ConfigLoadError: loading cfg from ~.smcrc fails For SSL connections, you can disable validation of the SMC SSL certificate by setting verify=False, however this is not a recommended practice. If you want to use the SSL certificate generated and used by the SMC API server for validation, set verify='path_to_my_dot_pem'. It is also recommended that your certificate has subjectAltName defined per RFC 2818 If SSL warnings are thrown in debug output, see: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings Logout should be called to remove the session immediately from the SMC server. .. note:: As of SMC 6.4 it is possible to give a standard Administrative user access to the SMC API. It is still possible to use an API Client by providing the api_key in the login call. """ params = {} if not url or (not api_key and not (login and pwd)): try: # First try load from file params = load_from_file(alt_filepath) if alt_filepath\ is not None else load_from_file() logger.debug('Read config data from file: %s', params) except ConfigLoadError: # Last ditch effort, try to load from environment params = load_from_environ() logger.debug('Read config data from environ: %s', params) params = params or dict( url=url, api_key=api_key, login=login, pwd=pwd, api_version=api_version, verify=verify, timeout=timeout, domain=domain, kwargs=kwargs or {}) # Check to see this session is already logged in. If so, return. # The session object represents a single connection. Log out to # re-use the same session object or get_session() from the # SessionManager to track multiple sessions. if self.manager and (self.session and self in self.manager): logger.info('An attempt to log in occurred when a session already ' 'exists, bypassing login for session: %s' % self) return self._params = {k: v for k, v in params.items() if v is not None} verify_ssl = self._params.get('verify', True) # Determine and set the API version we will use. self._params.update( api_version=get_api_version( self.url, self.api_version, self.timeout, verify_ssl)) extra_args = self._params.get('kwargs', {}) # Retries configured retry_on_busy = extra_args.pop('retry_on_busy', False) request = self._build_auth_request(verify_ssl, **extra_args) # This will raise if session login fails... self._session = self._get_session(request) self.session.verify = verify_ssl if retry_on_busy: self.set_retry_on_busy() # Load entry points load_entry_points(self) # Put session in manager self.manager._register(self) logger.debug('Login succeeded for admin: %s in domain: %s, session: %s', self.name, self.domain, self.session_id)
Login to SMC API and retrieve a valid session. Sessions use a pool connection manager to provide dynamic scalability during times of increased load. Each session is managed by a global session manager making it possible to have more than one session per interpreter. An example login and logout session:: from smc import session session.login(url='http://1.1.1.1:8082', api_key='SomeSMCG3ener@t3dPwd') .....do stuff..... session.logout() :param str url: ip of SMC management server :param str api_key: API key created for api client in SMC :param str login: Administrator user in SMC that has privilege to SMC API. :param str pwd: Password for user login. :param api_version (optional): specify api version :param int timeout: (optional): specify a timeout for initial connect; (default 10) :param str|boolean verify: verify SSL connections using cert (default: verify=True) You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs :param str alt_filepath: If using .smcrc, alternate path+filename :param str domain: domain to log in to. If domains are not configured, this field will be ignored and api client logged in to 'Shared Domain'. :param bool retry_on_busy: pass as kwarg with boolean if you want to add retries if the SMC returns HTTP 503 error during operation. You can also optionally customize this behavior and call :meth:`.set_retry_on_busy` :raises ConfigLoadError: loading cfg from ~.smcrc fails For SSL connections, you can disable validation of the SMC SSL certificate by setting verify=False, however this is not a recommended practice. If you want to use the SSL certificate generated and used by the SMC API server for validation, set verify='path_to_my_dot_pem'. It is also recommended that your certificate has subjectAltName defined per RFC 2818 If SSL warnings are thrown in debug output, see: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings Logout should be called to remove the session immediately from the SMC server. .. note:: As of SMC 6.4 it is possible to give a standard Administrative user access to the SMC API. It is still possible to use an API Client by providing the api_key in the login call.
entailment
def _build_auth_request(self, verify=False, **kwargs): """ Build the authentication request to SMC """ json = { 'domain': self.domain } credential = self.credential params = {} if credential.provider_name.startswith('lms'): params = dict( login=credential._login, pwd=credential._pwd) else: json.update(authenticationkey=credential._api_key) if kwargs: json.update(**kwargs) self._extra_args.update(**kwargs) # Store in case we need to rebuild later request = dict( url=self.credential.get_provider_entry_point(self.url, self.api_version), json=json, params=params, headers={'content-type': 'application/json'}, verify=verify) return request
Build the authentication request to SMC
entailment
def _get_session(self, request): """ Authenticate the request dict :param dict request: request dict built from user input :raises SMCConnectionError: failure to connect :return: python requests session :rtype: requests.Session """ _session = requests.session() # empty session response = _session.post(**request) logger.info('Using SMC API version: %s', self.api_version) if response.status_code != 200: raise SMCConnectionError( 'Login failed, HTTP status code: %s and reason: %s' % ( response.status_code, response.reason)) return _session
Authenticate the request dict :param dict request: request dict built from user input :raises SMCConnectionError: failure to connect :return: python requests session :rtype: requests.Session
entailment
def logout(self): """ Logout session from SMC :return: None """ if not self.session: self.manager._deregister(self) return try: r = self.session.put(self.entry_points.get('logout')) if r.status_code == 204: logger.info('Logged out admin: %s of domain: %s successfully', self.name, self.domain) else: logger.error('Logout status was unexpected. Received response ' 'with status code: %s', (r.status_code)) except requests.exceptions.SSLError as e: logger.error('SSL exception thrown during logout: %s', e) except requests.exceptions.ConnectionError as e: logger.error('Connection error on logout: %s', e) finally: self.entry_points.clear() self.manager._deregister(self) self._session = None try: delattr(self, 'current_user') except AttributeError: pass logger.debug('Call counters: %s' % counters)
Logout session from SMC :return: None
entailment
def refresh(self): """ Refresh session on 401. This is called automatically if your existing session times out and resends the operation/s which returned the error. :raises SMCConnectionError: Problem re-authenticating using existing api credentials """ if self.session and self.session_id: # Did session timeout? logger.info('Session timed out, will try obtaining a new session using ' 'previously saved credential information.') self.logout() # Force log out session just in case return self.login(**self.copy()) raise SMCConnectionError('Session expired and attempted refresh failed.')
Refresh session on 401. This is called automatically if your existing session times out and resends the operation/s which returned the error. :raises SMCConnectionError: Problem re-authenticating using existing api credentials
entailment
def switch_domain(self, domain): """ Switch from one domain to another. You can call session.login() with a domain key value to log directly into the domain of choice or alternatively switch from domain to domain. The user must have permissions to the domain or unauthorized will be returned. In addition, when switching domains, you will be logged out of the current domain to close the connection pool associated with the previous session. This prevents potentially excessive open connections to SMC :: session.login() # Log in to 'Shared Domain' ... session.switch_domain('MyDomain') :raises SMCConnectionError: Error logging in to specified domain. This typically means the domain either doesn't exist or the user does not have privileges to that domain. """ if self.domain != domain: if self in self.manager: # Exit current domain self.logout() logger.info('Switching to domain: %r and creating new session', domain) params = self.copy() params.update(domain=domain) self.login(**params)
Switch from one domain to another. You can call session.login() with a domain key value to log directly into the domain of choice or alternatively switch from domain to domain. The user must have permissions to the domain or unauthorized will be returned. In addition, when switching domains, you will be logged out of the current domain to close the connection pool associated with the previous session. This prevents potentially excessive open connections to SMC :: session.login() # Log in to 'Shared Domain' ... session.switch_domain('MyDomain') :raises SMCConnectionError: Error logging in to specified domain. This typically means the domain either doesn't exist or the user does not have privileges to that domain.
entailment
def set_retry_on_busy(self, total=5, backoff_factor=0.1, status_forcelist=None, **kwargs): """ Mount a custom retry object on the current session that allows service level retries when the SMC might reply with a Service Unavailable (503) message. This can be possible in larger environments with higher database activity. You can all this on the existing session, or provide as a dict to the login constructor. :param int total: total retries :param float backoff_factor: when to retry :param list status_forcelist: list of HTTP error codes to retry on :param list method_whitelist: list of methods to apply retries for, GET, POST and PUT by default :return: None """ if self.session: from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry method_whitelist = kwargs.pop('method_whitelist', []) or ['GET', 'POST', 'PUT'] status_forcelist = frozenset(status_forcelist) if status_forcelist else frozenset([503]) retry = Retry( total=total, backoff_factor=backoff_factor, status_forcelist=status_forcelist, method_whitelist=method_whitelist) for proto_str in ('http://', 'https://'): self.session.mount(proto_str, HTTPAdapter(max_retries=retry)) logger.debug('Mounting retry object to HTTP session: %s' % retry)
Mount a custom retry object on the current session that allows service level retries when the SMC might reply with a Service Unavailable (503) message. This can be possible in larger environments with higher database activity. You can all this on the existing session, or provide as a dict to the login constructor. :param int total: total retries :param float backoff_factor: when to retry :param list status_forcelist: list of HTTP error codes to retry on :param list method_whitelist: list of methods to apply retries for, GET, POST and PUT by default :return: None
entailment
def _get_log_schema(self): """ Get the log schema for this SMC version. :return: dict """ if self.session and self.session_id: schema = '{}/{}/monitoring/log/schemas'.format(self.url, self.api_version) response = self.session.get( url=schema, headers={'cookie': self.session_id, 'content-type': 'application/json'}) if response.status_code in (200, 201): return response.json()
Get the log schema for this SMC version. :return: dict
entailment
def has_credentials(self): """ Does this session have valid credentials :rtype: bool """ return all([ getattr(self, '_%s' % field, None) is not None for field in self.CredentialMap.get(self.provider_name)])
Does this session have valid credentials :rtype: bool
entailment
def add(self, data): """ Add a single entry to field. Entries can be added to a rule using the href of the element or by loading the element directly. Element should be of type :py:mod:`smc.elements.network`. After modifying rule, call :py:meth:`~.save`. Example of adding entry by element:: policy = FirewallPolicy('policy') for rule in policy.fw_ipv4_nat_rules.all(): if rule.name == 'therule': rule.sources.add(Host('myhost')) rule.save() .. note:: If submitting type Element and the element cannot be found, it will be skipped. :param data: entry to add :type data: Element or str """ if self.is_none or self.is_any: self.clear() self.data[self.typeof] = [] try: self.get(self.typeof).append(element_resolver(data)) except ElementNotFound: pass
Add a single entry to field. Entries can be added to a rule using the href of the element or by loading the element directly. Element should be of type :py:mod:`smc.elements.network`. After modifying rule, call :py:meth:`~.save`. Example of adding entry by element:: policy = FirewallPolicy('policy') for rule in policy.fw_ipv4_nat_rules.all(): if rule.name == 'therule': rule.sources.add(Host('myhost')) rule.save() .. note:: If submitting type Element and the element cannot be found, it will be skipped. :param data: entry to add :type data: Element or str
entailment
def add_many(self, data): """ Add multiple entries to field. Entries should be list format. Entries can be of types relavant to the field type. For example, for source and destination fields, elements may be of type :py:mod:`smc.elements.network` or be the elements direct href, or a combination of both. Add several entries to existing rule:: policy = FirewallPolicy('policy') for rule in policy.fw_ipv4_nat_rules.all(): if rule.name == 'therule': rule.sources.add_many([Host('myhost'), 'http://1.1.1.1/hosts/12345']) rule.save() :param list data: list of sources .. note:: If submitting type Element and the element cannot be found, it will be skipped. """ assert isinstance(data, list), "Incorrect format. Expecting list." if self.is_none or self.is_any: self.clear() self.data[self.typeof] = [] data = element_resolver(data, do_raise=False) self.data[self.typeof] = data
Add multiple entries to field. Entries should be list format. Entries can be of types relavant to the field type. For example, for source and destination fields, elements may be of type :py:mod:`smc.elements.network` or be the elements direct href, or a combination of both. Add several entries to existing rule:: policy = FirewallPolicy('policy') for rule in policy.fw_ipv4_nat_rules.all(): if rule.name == 'therule': rule.sources.add_many([Host('myhost'), 'http://1.1.1.1/hosts/12345']) rule.save() :param list data: list of sources .. note:: If submitting type Element and the element cannot be found, it will be skipped.
entailment
def update_field(self, elements): """ Update the field with a list of provided values but only if the values are different. Return a boolean indicating whether a change was made indicating whether `save` should be called. If the field is currently set to any or none, then no comparison is made and field is updated. :param list elements: list of elements in href or Element format to compare to existing field :rtype: bool """ changed = False if isinstance(elements, list): if self.is_any or self.is_none: self.add_many(elements) changed = True else: _elements = element_resolver(elements, do_raise=False) if set(self.all_as_href()) ^ set(_elements): self.data[self.typeof] = _elements changed = True if changed and self.rule and (isinstance(self, (Source, Destination)) and \ self.rule.typeof in ('fw_ipv4_nat_rule', 'fw_ipv6_nat_rule')): # Modify NAT cell if necessary self.rule._update_nat_field(self) return changed
Update the field with a list of provided values but only if the values are different. Return a boolean indicating whether a change was made indicating whether `save` should be called. If the field is currently set to any or none, then no comparison is made and field is updated. :param list elements: list of elements in href or Element format to compare to existing field :rtype: bool
entailment
def all_as_href(self): """ Return all elements without resolving to :class:`smc.elements.network` or :class:`smc.elements.service`. Just raw representation as href. :return: elements in href form :rtype: list """ if not self.is_any and not self.is_none: return [element for element in self.get(self.typeof)] return []
Return all elements without resolving to :class:`smc.elements.network` or :class:`smc.elements.service`. Just raw representation as href. :return: elements in href form :rtype: list
entailment
def all(self): """ Return all destinations for this rule. Elements returned are of the object type for the given element for further introspection. Search the fields in rule:: for sources in rule.sources.all(): print('My source: %s' % sources) :return: elements by resolved object type :rtype: list(Element) """ if not self.is_any and not self.is_none: return [Element.from_href(href) for href in self.get(self.typeof)] return []
Return all destinations for this rule. Elements returned are of the object type for the given element for further introspection. Search the fields in rule:: for sources in rule.sources.all(): print('My source: %s' % sources) :return: elements by resolved object type :rtype: list(Element)
entailment
def create(cls, name, user=None, network_element=None, domain_name=None, zone=None, executable=None): """ Create a match expression :param str name: name of match expression :param str user: name of user or user group :param Element network_element: valid network element type, i.e. host, network, etc :param DomainName domain_name: domain name network element :param Zone zone: zone to use :param str executable: name of executable or group :raises ElementNotFound: specified object does not exist :return: instance with meta :rtype: MatchExpression """ ref_list = [] if user: pass if network_element: ref_list.append(network_element.href) if domain_name: ref_list.append(domain_name.href) if zone: ref_list.append(zone.href) if executable: pass json = {'name': name, 'ref': ref_list} return ElementCreator(cls, json)
Create a match expression :param str name: name of match expression :param str user: name of user or user group :param Element network_element: valid network element type, i.e. host, network, etc :param DomainName domain_name: domain name network element :param Zone zone: zone to use :param str executable: name of executable or group :raises ElementNotFound: specified object does not exist :return: instance with meta :rtype: MatchExpression
entailment
def http_proxy(self, proxy, proxy_port, user=None, password=None): """ .. versionadded:: 0.5.7 Requires SMC and engine version >= 6.4 Set http proxy settings for Antivirus updates. :param str proxy: proxy IP address :param str,int proxy_port: proxy port :param str user: optional user for authentication """ self.update( antivirus_http_proxy=proxy, antivirus_proxy_port=proxy_port, antivirus_proxy_user=user if user else '', antivirus_proxy_password=password if password else '', antivirus_http_proxy_enabled=True)
.. versionadded:: 0.5.7 Requires SMC and engine version >= 6.4 Set http proxy settings for Antivirus updates. :param str proxy: proxy IP address :param str,int proxy_port: proxy port :param str user: optional user for authentication
entailment
def enable(self): """ Enable antivirus on the engine """ self.update(antivirus_enabled=True, virus_mirror='update.nai.com/Products/CommonUpdater' if \ not self.get('virus_mirror') else self.virus_mirror, antivirus_update_time=self.antivirus_update_time if \ self.get('antivirus_update_time') else 21600000)
Enable antivirus on the engine
entailment
def enable(self, http_proxy=None): """ Enable URL Filtering on the engine. If proxy servers are needed, provide a list of HTTPProxy elements. :param http_proxy: list of proxies for GTI connections :type http_proxy: list(str,HttpProxy) """ self.update(ts_enabled=True, http_proxy=get_proxy(http_proxy))
Enable URL Filtering on the engine. If proxy servers are needed, provide a list of HTTPProxy elements. :param http_proxy: list of proxies for GTI connections :type http_proxy: list(str,HttpProxy)
entailment
def status(self): """ Status of sandbox on this engine :rtype: bool """ if 'sandbox_type' in self.engine.data: if self.engine.sandbox_type == 'none': return False return True return False
Status of sandbox on this engine :rtype: bool
entailment
def disable(self): """ Disable the sandbox on this engine. """ self.engine.data.update(sandbox_type='none') self.pop('cloud_sandbox_settings', None) #pre-6.3 self.pop('sandbox_settings', None)
Disable the sandbox on this engine.
entailment
def enable(self, license_key, license_token, sandbox_type='cloud_sandbox', service='Automatic', http_proxy=None, sandbox_data_center='Automatic'): """ Enable sandbox on this engine. Provide a valid license key and license token obtained from your engine licensing. Requires SMC version >= 6.3. .. note:: Cloud sandbox is a feature that requires an engine license. :param str license_key: license key for specific engine :param str license_token: license token for specific engine :param str sandbox_type: 'local_sandbox' or 'cloud_sandbox' :param str,SandboxService service: a sandbox service element from SMC. The service defines which location the engine is in and which data centers to use. The default is to use the 'US Data Centers' profile if undefined. :param str,SandboxDataCenter sandbox_data_center: sandbox data center to use if the service specified does not exist. Requires SMC >= 6.4.3 :return: None """ service = element_resolver(SandboxService(service), do_raise=False) or \ element_resolver(SandboxService.create(name=service, sandbox_data_center=SandboxDataCenter(sandbox_data_center))) self.update(sandbox_license_key=license_key, sandbox_license_token=license_token, sandbox_service=service, http_proxy=get_proxy(http_proxy)) self.engine.data.setdefault('sandbox_settings', {}).update(self.data) self.engine.data.update(sandbox_type=sandbox_type)
Enable sandbox on this engine. Provide a valid license key and license token obtained from your engine licensing. Requires SMC version >= 6.3. .. note:: Cloud sandbox is a feature that requires an engine license. :param str license_key: license key for specific engine :param str license_token: license token for specific engine :param str sandbox_type: 'local_sandbox' or 'cloud_sandbox' :param str,SandboxService service: a sandbox service element from SMC. The service defines which location the engine is in and which data centers to use. The default is to use the 'US Data Centers' profile if undefined. :param str,SandboxDataCenter sandbox_data_center: sandbox data center to use if the service specified does not exist. Requires SMC >= 6.4.3 :return: None
entailment
def add_tls_credential(self, credentials): """ Add a list of TLSServerCredential to this engine. TLSServerCredentials can be in element form or can also be the href for the element. :param credentials: list of pre-created TLSServerCredentials :type credentials: list(str,TLSServerCredential) :return: None """ for cred in credentials: href = element_resolver(cred) if href not in self.engine.server_credential: self.engine.server_credential.append(href)
Add a list of TLSServerCredential to this engine. TLSServerCredentials can be in element form or can also be the href for the element. :param credentials: list of pre-created TLSServerCredentials :type credentials: list(str,TLSServerCredential) :return: None
entailment
def remove_tls_credential(self, credentials): """ Remove a list of TLSServerCredentials on this engine. :param credentials: list of credentials to remove from the engine :type credentials: list(str,TLSServerCredential) :return: None """ for cred in credentials: href = element_resolver(cred) if href in self.engine.server_credential: self.engine.server_credential.remove(href)
Remove a list of TLSServerCredentials on this engine. :param credentials: list of credentials to remove from the engine :type credentials: list(str,TLSServerCredential) :return: None
entailment
def policy_validation_settings(**kwargs): """ Set policy validation settings. This is used when policy based tasks are created and `validate_policy` is set to True. The following kwargs can be overridden in the create constructor. :param bool configuration_validation_for_alert_chain: default False :param bool duplicate_rule_check_settings: default False :param bool empty_rule_check_settings: default True :param bool emtpy_rule_check_settings_for_alert: default False :param bool general_check_settings: default True :param bool nat_modification_check_settings: default True :param bool non_supported_feature: default True :param bool routing_modification_check: default False :param bool unreachable_rule_check_settings: default False :param bool vpn_validation_check_settings: default True :return: dict of validation settings """ validation_settings = { 'configuration_validation_for_alert_chain': False, 'duplicate_rule_check_settings': False, 'empty_rule_check_settings': True, 'empty_rule_check_settings_for_alert': False, 'general_check_settings': True, 'nat_modification_check_settings': True, 'non_supported_feature': True, 'routing_modification_check': False, 'unreachable_rule_check_settings': False, 'vpn_validation_check_settings': True} for key, value in kwargs.items(): validation_settings[key] = value return {'validation_settings': validation_settings}
Set policy validation settings. This is used when policy based tasks are created and `validate_policy` is set to True. The following kwargs can be overridden in the create constructor. :param bool configuration_validation_for_alert_chain: default False :param bool duplicate_rule_check_settings: default False :param bool empty_rule_check_settings: default True :param bool emtpy_rule_check_settings_for_alert: default False :param bool general_check_settings: default True :param bool nat_modification_check_settings: default True :param bool non_supported_feature: default True :param bool routing_modification_check: default False :param bool unreachable_rule_check_settings: default False :param bool vpn_validation_check_settings: default True :return: dict of validation settings
entailment
def log_target_types(all_logs=False, **kwargs): """ Log targets for log tasks. A log target defines the log types that will be affected by the operation. For example, when creating a DeleteLogTask, you can specify which log types are deleted. :param bool for_alert_event_log: alert events traces (default: False) :param bool for_alert_log: alerts (default: False) :param bool for_fw_log: FW logs (default: False) :param bool for_ips_log: IPS logs (default: False) :param bool for_ips_recording: any IPS pcaps (default: False) :param bool for_l2fw_log: layer 2 FW logs (default: False) :param bool for_third_party_log: any 3rd party logs (default: False) :return: dict of log targets """ log_types = { 'for_alert_event_log': False, 'for_alert_log': False, 'for_audit_log': False, 'for_fw_log': False, 'for_ips_log': False, 'for_ips_recording_log': False, 'for_l2fw_log': False, 'for_third_party_log': False} if all_logs: for key in log_types.keys(): log_types[key] = True else: for key, value in kwargs.items(): log_types[key] = value return log_types
Log targets for log tasks. A log target defines the log types that will be affected by the operation. For example, when creating a DeleteLogTask, you can specify which log types are deleted. :param bool for_alert_event_log: alert events traces (default: False) :param bool for_alert_log: alerts (default: False) :param bool for_fw_log: FW logs (default: False) :param bool for_ips_log: IPS logs (default: False) :param bool for_ips_recording: any IPS pcaps (default: False) :param bool for_l2fw_log: layer 2 FW logs (default: False) :param bool for_third_party_log: any 3rd party logs (default: False) :return: dict of log targets
entailment
def activate(self): """ If a task is suspended, this will re-activate the task. Usually it's best to check for activated before running this:: task = RefreshPolicyTask('mytask') for scheduler in task.task_schedule: if scheduler.activated: scheduler.suspend() else: scheduler.activate() """ if 'activate' in self.data.links: self.make_request( ActionCommandFailed, method='update', etag=self.etag, resource='activate') self._del_cache() else: raise ActionCommandFailed('Task is already activated. To ' 'suspend, call suspend() on this task schedule')
If a task is suspended, this will re-activate the task. Usually it's best to check for activated before running this:: task = RefreshPolicyTask('mytask') for scheduler in task.task_schedule: if scheduler.activated: scheduler.suspend() else: scheduler.activate()
entailment
def add_schedule(self, name, activation_date, day_period='one_time', final_action='ALERT_FAILURE', activated=True, minute_period='one_time', day_mask=None, repeat_until_date=None, comment=None): """ Add a schedule to an existing task. :param str name: name for this schedule :param int activation_date: when to start this task. Activation date should be a UTC time represented in milliseconds. :param str day_period: when this task should be run. Valid options: 'one_time', 'daily', 'weekly', 'monthly', 'yearly'. If 'daily' is selected, you can also provide a value for 'minute_period'. (default: 'one_time') :param str minute_period: only required if day_period is set to 'daily'. Valid options: 'each_quarter' (15 min), 'each_half' (30 minutes), or 'hourly', 'one_time' (default: 'one_time') :param int day_mask: If the task day_period=weekly, then specify the day or days for repeating. Day masks are: sun=1, mon=2, tue=4, wed=8, thu=16, fri=32, sat=64. To repeat for instance every Monday, Wednesday and Friday, the value must be 2 + 8 + 32 = 42 :param str final_action: what type of action to perform after the scheduled task runs. Options are: 'ALERT_FAILURE', 'ALERT', or 'NO_ACTION' (default: ALERT_FAILURE) :param bool activated: whether to activate the schedule (default: True) :param str repeat_until_date: if this is anything but a one time task run, you can specify the date when this task should end. The format is the same as the `activation_date` param. :param str comment: optional comment :raises ActionCommandFailed: failed adding schedule :return: None """ json = { 'name': name, 'activation_date': activation_date, 'day_period': day_period, 'day_mask': day_mask, 'activated': activated, 'final_action': final_action, 'minute_period': minute_period, 'repeat_until_date': repeat_until_date if repeat_until_date else None, 'comment': comment} if 'daily' in day_period: minute_period = minute_period if minute_period != 'one_time' else 'hourly' json['minute_period'] = minute_period return self.make_request( ActionCommandFailed, method='create', resource='task_schedule', json=json)
Add a schedule to an existing task. :param str name: name for this schedule :param int activation_date: when to start this task. Activation date should be a UTC time represented in milliseconds. :param str day_period: when this task should be run. Valid options: 'one_time', 'daily', 'weekly', 'monthly', 'yearly'. If 'daily' is selected, you can also provide a value for 'minute_period'. (default: 'one_time') :param str minute_period: only required if day_period is set to 'daily'. Valid options: 'each_quarter' (15 min), 'each_half' (30 minutes), or 'hourly', 'one_time' (default: 'one_time') :param int day_mask: If the task day_period=weekly, then specify the day or days for repeating. Day masks are: sun=1, mon=2, tue=4, wed=8, thu=16, fri=32, sat=64. To repeat for instance every Monday, Wednesday and Friday, the value must be 2 + 8 + 32 = 42 :param str final_action: what type of action to perform after the scheduled task runs. Options are: 'ALERT_FAILURE', 'ALERT', or 'NO_ACTION' (default: ALERT_FAILURE) :param bool activated: whether to activate the schedule (default: True) :param str repeat_until_date: if this is anything but a one time task run, you can specify the date when this task should end. The format is the same as the `activation_date` param. :param str comment: optional comment :raises ActionCommandFailed: failed adding schedule :return: None
entailment
def create(cls, name, engines, comment=None, validate_policy=True, **kwargs): """ Create a refresh policy task associated with specific engines. A policy refresh task does not require a policy be specified. The policy used in the refresh will be the policy already assigned to the engine. :param str name: name of this task :param engines: list of Engines for the task :type engines: list(Engine) :param str comment: optional comment :param bool validate_policy: validate the policy before upload. If set to true, validation kwargs can also be provided if customization is required, otherwise default validation settings are used. :param kwargs: see :func:`~policy_validation_settings` for keyword arguments and default values. :raises ElementNotFound: engine specified does not exist :raises CreateElementFailed: failure to create the task :return: the task :rtype: RefreshPolicyTask """ json = { 'resources': [engine.href for engine in engines], 'name': name, 'comment': comment} if validate_policy: json.update(policy_validation_settings(**kwargs)) return ElementCreator(cls, json)
Create a refresh policy task associated with specific engines. A policy refresh task does not require a policy be specified. The policy used in the refresh will be the policy already assigned to the engine. :param str name: name of this task :param engines: list of Engines for the task :type engines: list(Engine) :param str comment: optional comment :param bool validate_policy: validate the policy before upload. If set to true, validation kwargs can also be provided if customization is required, otherwise default validation settings are used. :param kwargs: see :func:`~policy_validation_settings` for keyword arguments and default values. :raises ElementNotFound: engine specified does not exist :raises CreateElementFailed: failure to create the task :return: the task :rtype: RefreshPolicyTask
entailment
def create(cls, name, engines, policy=None, comment=None, **kwargs): """ Create a new validate policy task. If a policy is not specified, the engines existing policy will be validated. Override default validation settings as kwargs. :param str name: name of task :param engines: list of engines to validate :type engines: list(Engine) :param Policy policy: policy to validate. Uses the engines assigned policy if none specified. :param kwargs: see :func:`~policy_validation_settings` for keyword arguments and default values. :raises ElementNotFound: engine or policy specified does not exist :raises CreateElementFailed: failure to create the task :return: the task :rtype: ValidatePolicyTask """ json = { 'name': name, 'resources': [eng.href for eng in engines], 'policy': policy.href if policy is not None else policy, 'comment': comment} if kwargs: json.update(policy_validation_settings(**kwargs)) return ElementCreator(cls, json)
Create a new validate policy task. If a policy is not specified, the engines existing policy will be validated. Override default validation settings as kwargs. :param str name: name of task :param engines: list of engines to validate :type engines: list(Engine) :param Policy policy: policy to validate. Uses the engines assigned policy if none specified. :param kwargs: see :func:`~policy_validation_settings` for keyword arguments and default values. :raises ElementNotFound: engine or policy specified does not exist :raises CreateElementFailed: failure to create the task :return: the task :rtype: ValidatePolicyTask
entailment
def create(cls, name, master_engines, comment=None): """ Create a refresh task for master engines. :param str name: name of task :param master_engines: list of master engines for this task :type master_engines: list(MasterEngine) :param str comment: optional comment :raises CreateElementFailed: failed to create the task :return: the task :rtype: RefreshMasterEnginePolicyTask """ json = { 'name': name, 'comment': comment, 'resources': [eng.href for eng in master_engines if isinstance(eng, MasterEngine)]} return ElementCreator(cls, json)
Create a refresh task for master engines. :param str name: name of task :param master_engines: list of master engines for this task :type master_engines: list(MasterEngine) :param str comment: optional comment :raises CreateElementFailed: failed to create the task :return: the task :rtype: RefreshMasterEnginePolicyTask
entailment
def create(cls, name, servers=None, time_range='yesterday', all_logs=False, filter_for_delete=None, comment=None, **kwargs): """ Create a new delete log task. Provide True to all_logs to delete all log types. Otherwise provide kwargs to specify each log by type of interest. :param str name: name for this task :param servers: servers to back up. Servers must be instances of management servers or log servers. If no value is provided, all servers are backed up. :type servers: list(ManagementServer or LogServer) :param str time_range: specify a time range for the deletion. Valid options are 'yesterday', 'last_full_week_sun_sat', 'last_full_week_mon_sun', 'last_full_month' (default 'yesterday') :param FilterExpression filter_for_delete: optional filter for deleting. (default: FilterExpression('Match All') :param bool all_logs: if True, all log types will be deleted. If this is True, kwargs are ignored (default: False) :param kwargs: see :func:`~log_target_types` for keyword arguments and default values. :raises ElementNotFound: specified servers were not found :raises CreateElementFailed: failure to create the task :return: the task :rtype: DeleteLogTask """ if not servers: servers = [svr.href for svr in ManagementServer.objects.all()] servers.extend([svr.href for svr in LogServer.objects.all()]) else: servers = [svr.href for svr in servers] filter_for_delete = filter_for_delete.href if filter_for_delete else \ FilterExpression('Match All').href json = { 'name': name, 'resources': servers, 'time_limit_type': time_range, 'start_time': 0, 'end_time': 0, 'file_format': 'unknown', 'filter_for_delete': filter_for_delete, 'comment': comment} json.update(**log_target_types(all_logs, **kwargs)) return ElementCreator(cls, json)
Create a new delete log task. Provide True to all_logs to delete all log types. Otherwise provide kwargs to specify each log by type of interest. :param str name: name for this task :param servers: servers to back up. Servers must be instances of management servers or log servers. If no value is provided, all servers are backed up. :type servers: list(ManagementServer or LogServer) :param str time_range: specify a time range for the deletion. Valid options are 'yesterday', 'last_full_week_sun_sat', 'last_full_week_mon_sun', 'last_full_month' (default 'yesterday') :param FilterExpression filter_for_delete: optional filter for deleting. (default: FilterExpression('Match All') :param bool all_logs: if True, all log types will be deleted. If this is True, kwargs are ignored (default: False) :param kwargs: see :func:`~log_target_types` for keyword arguments and default values. :raises ElementNotFound: specified servers were not found :raises CreateElementFailed: failure to create the task :return: the task :rtype: DeleteLogTask
entailment
def create(cls, name, servers, backup_log_data=False, encrypt_password=None, comment=None): """ Create a new server backup task. This task provides the ability to backup individual or all management and log servers under SMC management. :param str name: name of task :param servers: servers to back up. Servers must be instances of management servers or log servers. If no value is provided all servers are backed up. :type servers: list(ManagementServer or LogServer) :param bool backup_log_data: Should the log files be backed up. This field is only relevant if a Log Server is backed up. :param str encrypt_password: Provide an encrypt password if you want this backup to be encrypted. :param str comment: optional comment :raises ElementNotFound: specified servers were not found :raises CreateElementFailed: failure to create the task :return: the task :rtype: ServerBackupTask """ if not servers: servers = [svr.href for svr in ManagementServer.objects.all()] servers.extend([svr.href for svr in LogServer.objects.all()]) else: servers = [svr.href for svr in servers] json = { 'resources': servers, 'name': name, 'password': encrypt_password if encrypt_password else None, 'log_data_must_be_saved': backup_log_data, 'comment': comment} return ElementCreator(cls, json)
Create a new server backup task. This task provides the ability to backup individual or all management and log servers under SMC management. :param str name: name of task :param servers: servers to back up. Servers must be instances of management servers or log servers. If no value is provided all servers are backed up. :type servers: list(ManagementServer or LogServer) :param bool backup_log_data: Should the log files be backed up. This field is only relevant if a Log Server is backed up. :param str encrypt_password: Provide an encrypt password if you want this backup to be encrypted. :param str comment: optional comment :raises ElementNotFound: specified servers were not found :raises CreateElementFailed: failure to create the task :return: the task :rtype: ServerBackupTask
entailment
def create(cls, name, engines, include_core_files=False, include_slapcat_output=False, comment=None): """ Create an sginfo task. :param str name: name of task :param engines: list of engines to apply the sginfo task :type engines: list(Engine) :param bool include_core_files: include core files in the sginfo backup (default: False) :param bool include_slapcat_output: include output from a slapcat command in output (default: False) :raises ElementNotFound: engine not found :raises CreateElementFailed: create the task failed :return: the task :rtype: SGInfoTask """ json = { 'name': name, 'comment': comment, 'resources': [engine.href for engine in engines], 'include_core_files': include_core_files, 'include_slapcat_output': include_slapcat_output} return ElementCreator(cls, json)
Create an sginfo task. :param str name: name of task :param engines: list of engines to apply the sginfo task :type engines: list(Engine) :param bool include_core_files: include core files in the sginfo backup (default: False) :param bool include_slapcat_output: include output from a slapcat command in output (default: False) :raises ElementNotFound: engine not found :raises CreateElementFailed: create the task failed :return: the task :rtype: SGInfoTask
entailment
def send_request(user_session, method, request): """ Send request to SMC :param Session user_session: session object :param str method: method for request :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult """ if user_session.session: session = user_session.session # requests session try: method = method.upper() if method else '' if method == GET: if request.filename: # File download request return file_download(user_session, request) response = session.get( request.href, params=request.params, headers=request.headers, timeout=user_session.timeout) response.encoding = 'utf-8' counters.update(read=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 204, 304): raise SMCOperationFailure(response) elif method == POST: if request.files: # File upload request return file_upload(user_session, method, request) response = session.post( request.href, data=json.dumps(request.json, cls=CacheEncoder), headers=request.headers, params=request.params) response.encoding = 'utf-8' counters.update(create=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 201, 202): # 202 is asynchronous response with follower link raise SMCOperationFailure(response) elif method == PUT: if request.files: # File upload request return file_upload(user_session, method, request) # Etag should be set in request object request.headers.update(Etag=request.etag) response = session.put( request.href, data=json.dumps(request.json, cls=CacheEncoder), params=request.params, headers=request.headers) counters.update(update=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code != 200: raise SMCOperationFailure(response) elif method == DELETE: response = session.delete( request.href, headers=request.headers) counters.update(delete=1) # Conflict (409) if ETag is not current if response.status_code in (409,): req = session.get(request.href) etag = req.headers.get('ETag') response = session.delete( request.href, headers={'if-match': etag}) response.encoding = 'utf-8' if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 204): raise SMCOperationFailure(response) else: # Unsupported method return SMCResult(msg='Unsupported method: %s' % method, user_session=user_session) except SMCOperationFailure as error: if error.code in (401,): user_session.refresh() return send_request(user_session, method, request) raise error except requests.exceptions.RequestException as e: raise SMCConnectionError('Connection problem to SMC, ensure the API ' 'service is running and host is correct: %s, exiting.' % e) else: return SMCResult(response, user_session=user_session) else: raise SMCConnectionError('No session found. Please login to continue')
Send request to SMC :param Session user_session: session object :param str method: method for request :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult
entailment
def file_download(user_session, request): """ Called when GET request specifies a filename to retrieve. :param Session user_session: session object :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult """ logger.debug('Download file: %s', vars(request)) response = user_session.session.get( request.href, params=request.params, headers=request.headers, stream=True) if response.status_code == 200: logger.debug('Streaming to file... Content length: %s', len(response.content)) try: path = os.path.abspath(request.filename) logger.debug('Operation: %s, saving to file: %s', request.href, path) with open(path, "wb") as handle: for chunk in response.iter_content(chunk_size=1024): if chunk: handle.write(chunk) handle.flush() except IOError as e: raise IOError('Error attempting to save to file: {}'.format(e)) result = SMCResult(response, user_session=user_session) result.content = path return result else: raise SMCOperationFailure(response)
Called when GET request specifies a filename to retrieve. :param Session user_session: session object :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult
entailment
def file_upload(user_session, method, request): """ Perform a file upload PUT/POST to SMC. Request should have the files attribute set which will be an open handle to the file that will be binary transfer. :param Session user_session: session object :param str method: method to use, could be put or post :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult """ logger.debug('Upload: %s', vars(request)) http_command = getattr(user_session.session, method.lower()) try: response = http_command( request.href, params=request.params, files=request.files) except AttributeError: raise TypeError('File specified in request was not readable: %s' % request.files) else: if response.status_code in (200, 201, 202, 204): logger.debug('Success sending file in elapsed time: %s', response.elapsed) return SMCResult(response, user_session=user_session) raise SMCOperationFailure(response)
Perform a file upload PUT/POST to SMC. Request should have the files attribute set which will be an open handle to the file that will be binary transfer. :param Session user_session: session object :param str method: method to use, could be put or post :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult
entailment
def rename(self, name): """ Rename this node :param str name: new name for node """ self.update(name='{} node {}'.format(name, self.nodeid))
Rename this node :param str name: new name for node
entailment
def _create(cls, name, node_type, nodeid=1, loopback_ndi=None): """ Create the node/s for the engine. This isn't called directly, instead it is used when engine.create() is called :param str name: name of node :param str node_type: based on engine type specified :param int nodeid: used to identify which node :param list LoopbackInterface loopback_ndi: optional loopback interface for node. """ loopback = loopback_ndi if loopback_ndi else [] node = {node_type: { 'activate_test': True, 'disabled': False, 'loopback_node_dedicated_interface': loopback, 'name': name + ' node ' + str(nodeid), 'nodeid': nodeid} } return node
Create the node/s for the engine. This isn't called directly, instead it is used when engine.create() is called :param str name: name of node :param str node_type: based on engine type specified :param int nodeid: used to identify which node :param list LoopbackInterface loopback_ndi: optional loopback interface for node.
entailment
def loopback_interface(self): """ Loopback interfaces for this node. This will return empty if the engine is not a layer 3 firewall type:: >>> engine = Engine('dingo') >>> for node in engine.nodes: ... for loopback in node.loopback_interface: ... loopback ... LoopbackInterface(address=172.20.1.1, nodeid=1, rank=1) LoopbackInterface(address=172.31.1.1, nodeid=1, rank=2) LoopbackInterface(address=2.2.2.2, nodeid=1, rank=3) :rtype: list(LoopbackInterface) """ for lb in self.data.get('loopback_node_dedicated_interface', []): yield LoopbackInterface(lb, self._engine)
Loopback interfaces for this node. This will return empty if the engine is not a layer 3 firewall type:: >>> engine = Engine('dingo') >>> for node in engine.nodes: ... for loopback in node.loopback_interface: ... loopback ... LoopbackInterface(address=172.20.1.1, nodeid=1, rank=1) LoopbackInterface(address=172.31.1.1, nodeid=1, rank=2) LoopbackInterface(address=2.2.2.2, nodeid=1, rank=3) :rtype: list(LoopbackInterface)
entailment
def bind_license(self, license_item_id=None): """ Auto bind license, uses dynamic if POS is not found :param str license_item_id: license id :raises LicenseError: binding license failed, possibly no licenses :return: None """ params = {'license_item_id': license_item_id} self.make_request( LicenseError, method='create', resource='bind', params=params)
Auto bind license, uses dynamic if POS is not found :param str license_item_id: license id :raises LicenseError: binding license failed, possibly no licenses :return: None
entailment
def initial_contact(self, enable_ssh=True, time_zone=None, keyboard=None, install_on_server=None, filename=None, as_base64=False): """ Allows to save the initial contact for for the specified node :param bool enable_ssh: flag to know if we allow the ssh daemon on the specified node :param str time_zone: optional time zone to set on the specified node :param str keyboard: optional keyboard to set on the specified node :param bool install_on_server: optional flag to know if the generated configuration needs to be installed on SMC Install server (POS is needed) :param str filename: filename to save initial_contact to :param bool as_base64: return the initial config in base 64 format. Useful for cloud based engine deployments as userdata :raises NodeCommandFailed: IOError handling initial configuration data :return: initial contact text information :rtype: str """ result = self.make_request( NodeCommandFailed, method='create', raw_result=True, resource='initial_contact', params={'enable_ssh': enable_ssh}) if result.content: if as_base64: result.content = b64encode(result.content) if filename: try: save_to_file(filename, result.content) except IOError as e: raise NodeCommandFailed( 'Error occurred when attempting to save initial ' 'contact to file: {}'.format(e)) return result.content
Allows to save the initial contact for for the specified node :param bool enable_ssh: flag to know if we allow the ssh daemon on the specified node :param str time_zone: optional time zone to set on the specified node :param str keyboard: optional keyboard to set on the specified node :param bool install_on_server: optional flag to know if the generated configuration needs to be installed on SMC Install server (POS is needed) :param str filename: filename to save initial_contact to :param bool as_base64: return the initial config in base 64 format. Useful for cloud based engine deployments as userdata :raises NodeCommandFailed: IOError handling initial configuration data :return: initial contact text information :rtype: str
entailment
def interface_status(self): """ Obtain the interface status for this node. This will return an iterable that provides information about the existing interfaces. Retrieve a single interface status:: >>> node = engine.nodes[0] >>> node Node(name=ngf-1065) >>> node.interface_status <smc.core.node.InterfaceStatus object at 0x103b2f310> >>> node.interface_status.get(0) InterfaceStatus(aggregate_is_active=False, capability=u'Normal Interface', flow_control=u'AutoNeg: off Rx: off Tx: off', interface_id=0, mtu=1500, name=u'eth0_0', port=u'Copper', speed_duplex=u'1000 Mb/s / Full / Automatic', status=u'Up') Or iterate and get all interfaces:: >>> for stat in node.interface_status: ... stat ... InterfaceStatus(aggregate_is_active=False, capability=u'Normal Interface', ... ... :raises NodeCommandFailed: failure to retrieve current status :rtype: InterfaceStatus """ result = self.make_request( NodeCommandFailed, resource='appliance_status') return InterfaceStatus(result.get('interface_statuses', []))
Obtain the interface status for this node. This will return an iterable that provides information about the existing interfaces. Retrieve a single interface status:: >>> node = engine.nodes[0] >>> node Node(name=ngf-1065) >>> node.interface_status <smc.core.node.InterfaceStatus object at 0x103b2f310> >>> node.interface_status.get(0) InterfaceStatus(aggregate_is_active=False, capability=u'Normal Interface', flow_control=u'AutoNeg: off Rx: off Tx: off', interface_id=0, mtu=1500, name=u'eth0_0', port=u'Copper', speed_duplex=u'1000 Mb/s / Full / Automatic', status=u'Up') Or iterate and get all interfaces:: >>> for stat in node.interface_status: ... stat ... InterfaceStatus(aggregate_is_active=False, capability=u'Normal Interface', ... ... :raises NodeCommandFailed: failure to retrieve current status :rtype: InterfaceStatus
entailment
def hardware_status(self): """ Obtain hardware statistics for various areas of this node. See :class:`~HardwareStatus` for usage. :raises NodeCommandFailed: failure to retrieve current status :rtype: HardwareStatus """ result = self.make_request( NodeCommandFailed, resource='appliance_status') return HardwareStatus(result.get('hardware_statuses', []))
Obtain hardware statistics for various areas of this node. See :class:`~HardwareStatus` for usage. :raises NodeCommandFailed: failure to retrieve current status :rtype: HardwareStatus
entailment
def go_online(self, comment=None): """ Executes a Go-Online operation on the specified node typically done when the node has already been forced offline via :func:`go_offline` :param str comment: (optional) comment to audit :raises NodeCommandFailed: online not available :return: None """ self.make_request( NodeCommandFailed, method='update', resource='go_online', params={'comment': comment})
Executes a Go-Online operation on the specified node typically done when the node has already been forced offline via :func:`go_offline` :param str comment: (optional) comment to audit :raises NodeCommandFailed: online not available :return: None
entailment
def go_offline(self, comment=None): """ Executes a Go-Offline operation on the specified node :param str comment: optional comment to audit :raises NodeCommandFailed: offline not available :return: None """ self.make_request( NodeCommandFailed, method='update', resource='go_offline', params={'comment': comment})
Executes a Go-Offline operation on the specified node :param str comment: optional comment to audit :raises NodeCommandFailed: offline not available :return: None
entailment
def go_standby(self, comment=None): """ Executes a Go-Standby operation on the specified node. To get the status of the current node/s, run :func:`status` :param str comment: optional comment to audit :raises NodeCommandFailed: engine cannot go standby :return: None """ self.make_request( NodeCommandFailed, method='update', resource='go_standby', params={'comment': comment})
Executes a Go-Standby operation on the specified node. To get the status of the current node/s, run :func:`status` :param str comment: optional comment to audit :raises NodeCommandFailed: engine cannot go standby :return: None
entailment
def lock_online(self, comment=None): """ Executes a Lock-Online operation on the specified node :param str comment: comment for audit :raises NodeCommandFailed: cannot lock online :return: None """ self.make_request( NodeCommandFailed, method='update', resource='lock_online', params={'comment': comment})
Executes a Lock-Online operation on the specified node :param str comment: comment for audit :raises NodeCommandFailed: cannot lock online :return: None
entailment
def lock_offline(self, comment=None): """ Executes a Lock-Offline operation on the specified node Bring back online by running :func:`go_online`. :param str comment: comment for audit :raises NodeCommandFailed: lock offline failed :return: None """ self.make_request( NodeCommandFailed, method='update', resource='lock_offline', params={'comment': comment})
Executes a Lock-Offline operation on the specified node Bring back online by running :func:`go_online`. :param str comment: comment for audit :raises NodeCommandFailed: lock offline failed :return: None
entailment
def reset_user_db(self, comment=None): """ Executes a Send Reset LDAP User DB Request operation on this node. :param str comment: comment to audit :raises NodeCommandFailed: failure resetting db :return: None """ self.make_request( NodeCommandFailed, method='update', resource='reset_user_db', params={'comment': comment})
Executes a Send Reset LDAP User DB Request operation on this node. :param str comment: comment to audit :raises NodeCommandFailed: failure resetting db :return: None
entailment
def debug(self, filter_enabled=False): """ View all debug settings for this node. This will return a debug object. View the debug object repr to identify settings to enable or disable and submit the object to :meth:`set_debug` to enable settings. Add filter_enabled=True argument to see only enabled settings :param bool filter_enabled: returns all enabled diagnostics :raises NodeCommandFailed: failure getting diagnostics :rtype: Debug .. seealso:: :class:`~Debug` for example usage """ params = {'filter_enabled': filter_enabled} result = self.make_request( NodeCommandFailed, resource='diagnostic', params=params) return Debug(result.get('diagnostics'))
View all debug settings for this node. This will return a debug object. View the debug object repr to identify settings to enable or disable and submit the object to :meth:`set_debug` to enable settings. Add filter_enabled=True argument to see only enabled settings :param bool filter_enabled: returns all enabled diagnostics :raises NodeCommandFailed: failure getting diagnostics :rtype: Debug .. seealso:: :class:`~Debug` for example usage
entailment
def set_debug(self, debug): """ Set the debug settings for this node. This should be a modified :class:`~Debug` instance. This will take effect immediately on the specified node. :param Debug debug: debug object with specified settings :raises NodeCommandFailed: fail to communicate with node :return: None .. seealso:: :class:`~Debug` for example usage """ self.make_request( NodeCommandFailed, method='create', resource='send_diagnostic', json=debug.serialize())
Set the debug settings for this node. This should be a modified :class:`~Debug` instance. This will take effect immediately on the specified node. :param Debug debug: debug object with specified settings :raises NodeCommandFailed: fail to communicate with node :return: None .. seealso:: :class:`~Debug` for example usage
entailment
def reboot(self, comment=None): """ Send reboot command to this node. :param str comment: comment to audit :raises NodeCommandFailed: reboot failed with reason :return: None """ self.make_request( NodeCommandFailed, method='update', resource='reboot', params={'comment': comment})
Send reboot command to this node. :param str comment: comment to audit :raises NodeCommandFailed: reboot failed with reason :return: None
entailment
def sginfo(self, include_core_files=False, include_slapcat_output=False, filename='sginfo.gz'): """ Get the SG Info of the specified node. Optionally provide a filename, otherwise default to 'sginfo.gz'. Once you run gzip -d <filename>, the inner contents will be in .tar format. :param include_core_files: flag to include or not core files :param include_slapcat_output: flag to include or not slapcat output :raises NodeCommandFailed: failed getting sginfo with reason :return: string path of download location :rtype: str """ params = { 'include_core_files': include_core_files, 'include_slapcat_output': include_slapcat_output} result = self.make_request( NodeCommandFailed, raw_result=True, resource='sginfo', filename=filename, params=params) return result.content
Get the SG Info of the specified node. Optionally provide a filename, otherwise default to 'sginfo.gz'. Once you run gzip -d <filename>, the inner contents will be in .tar format. :param include_core_files: flag to include or not core files :param include_slapcat_output: flag to include or not slapcat output :raises NodeCommandFailed: failed getting sginfo with reason :return: string path of download location :rtype: str
entailment
def ssh(self, enable=True, comment=None): """ Enable or disable SSH :param bool enable: enable or disable SSH daemon :param str comment: optional comment for audit :raises NodeCommandFailed: cannot enable SSH daemon :return: None """ self.make_request( NodeCommandFailed, method='update', resource='ssh', params={'enable': enable, 'comment': comment})
Enable or disable SSH :param bool enable: enable or disable SSH daemon :param str comment: optional comment for audit :raises NodeCommandFailed: cannot enable SSH daemon :return: None
entailment
def change_ssh_pwd(self, pwd=None, comment=None): """ Executes a change SSH password operation on the specified node :param str pwd: changed password value :param str comment: optional comment for audit log :raises NodeCommandFailed: cannot change ssh password :return: None """ self.make_request( NodeCommandFailed, method='update', resource='change_ssh_pwd', params={'comment': comment}, json={'value': pwd})
Executes a change SSH password operation on the specified node :param str pwd: changed password value :param str comment: optional comment for audit log :raises NodeCommandFailed: cannot change ssh password :return: None
entailment
def logging_subsystem(self): """ A collection of logging subsystem statuses :rtype: Status """ for item in self: if item.name.startswith('Logging'): for s in item_status(item): yield s
A collection of logging subsystem statuses :rtype: Status
entailment
def filesystem(self): """ A collection of filesystem related statuses :rtype: Status """ for item in self: if item.name.startswith('File System'): for s in item_status(item): yield s
A collection of filesystem related statuses :rtype: Status
entailment
def delete(self, location_name): """ Remove a given location by location name. This operation is performed only if the given location is valid, and if so, `update` is called automatically. :param str location: location name or location ref :raises UpdateElementFailed: failed to update element with reason :rtype: bool """ updated = False location_ref = location_helper(location_name, search_only=True) if location_ref in self: self._cas[:] = [loc for loc in self if loc.location_ref != location_ref] self.update() updated = True return updated
Remove a given location by location name. This operation is performed only if the given location is valid, and if so, `update` is called automatically. :param str location: location name or location ref :raises UpdateElementFailed: failed to update element with reason :rtype: bool
entailment
def update_or_create(self, location, contact_address, with_status=False, **kw): """ Update an existing contact address or create if the location does not exist. :param str location: name of the location, the location will be added if it doesn't exist :param str contact_address: contact address IP. Can be the string 'dynamic' if this should be a dynamic contact address (i.e. on DHCP interface) :param bool with_status: if set to True, a 3-tuple is returned with (Element, modified, created), where the second and third tuple items are booleans indicating the status :raises UpdateElementFailed: failed to update element with reason :rtype: ContactAddressNode """ updated, created = False, False location_ref = location_helper(location) if location_ref in self: for ca in self: if ca.location_ref == location_ref: ca.update( address=contact_address if 'dynamic' not in contact_address\ else 'First DHCP Interface ip', dynamic='true' if 'dynamic' in contact_address else 'false') updated = True else: self.data.setdefault('contact_addresses', []).append( dict(address=contact_address if 'dynamic' not in contact_address\ else 'First DHCP Interface ip', dynamic='true' if 'dynamic' in contact_address else 'false', location_ref=location_ref)) created = True if updated or created: self.update() if with_status: return self, updated, created return self
Update an existing contact address or create if the location does not exist. :param str location: name of the location, the location will be added if it doesn't exist :param str contact_address: contact address IP. Can be the string 'dynamic' if this should be a dynamic contact address (i.e. on DHCP interface) :param bool with_status: if set to True, a 3-tuple is returned with (Element, modified, created), where the second and third tuple items are booleans indicating the status :raises UpdateElementFailed: failed to update element with reason :rtype: ContactAddressNode
entailment
def get(self, interface_id, interface_ip=None): """ Get will return a list of interface references based on the specified interface id. Multiple references can be returned if a single interface has multiple IP addresses assigned. :return: If interface_ip is provided, a single ContactAddressNode element is returned if found. Otherwise a list will be returned with all contact address nodes for the given interface_id. """ interfaces = [] for interface in iter(self): if interface.interface_id == str(interface_id): if interface_ip: if interface.interface_ip == interface_ip: return interface else: interfaces.append(interface) return interfaces
Get will return a list of interface references based on the specified interface id. Multiple references can be returned if a single interface has multiple IP addresses assigned. :return: If interface_ip is provided, a single ContactAddressNode element is returned if found. Otherwise a list will be returned with all contact address nodes for the given interface_id.
entailment
def change_interface_id(self, interface_id): """ Generic change interface ID for VLAN interfaces that are not Inline Interfaces (non-VLAN sub interfaces do not have an interface_id field). :param str, int interface_id: interface ID value """ _, second = self.nicid.split('.') self.update(nicid='{}.{}'.format(str(interface_id), second))
Generic change interface ID for VLAN interfaces that are not Inline Interfaces (non-VLAN sub interfaces do not have an interface_id field). :param str, int interface_id: interface ID value
entailment
def change_vlan_id(self, vlan_id): """ Change a VLAN id :param str vlan_id: new vlan """ first, _ = self.nicid.split('.') self.update(nicid='{}.{}'.format(first, str(vlan_id)))
Change a VLAN id :param str vlan_id: new vlan
entailment
def vlan_id(self): """ VLAN ID for this interface, if any :return: VLAN identifier :rtype: str """ nicid = self.nicid if nicid: v = nicid.split('.') if len(v) > 1: return nicid.split('.')[1]
VLAN ID for this interface, if any :return: VLAN identifier :rtype: str
entailment
def create(cls, interface_id, logical_interface_ref, second_interface_id=None, zone_ref=None, **kwargs): """ :param str interface_id: two interfaces, i.e. '1-2', '4-5', '7-10', etc :param str logical_ref: logical interface reference :param str zone_ref: reference to zone, set on second inline pair :rtype: dict """ data = {'inspect_unspecified_vlans': True, 'nicid': '{}-{}'.format(str(interface_id), str(second_interface_id)) if second_interface_id else str(interface_id), 'logical_interface_ref': logical_interface_ref, 'zone_ref': zone_ref} for k, v in kwargs.items(): data.update({k: v}) return cls(data)
:param str interface_id: two interfaces, i.e. '1-2', '4-5', '7-10', etc :param str logical_ref: logical interface reference :param str zone_ref: reference to zone, set on second inline pair :rtype: dict
entailment
def change_vlan_id(self, vlan_id): """ Change a VLAN id for an inline interface. :param str vlan_id: New VLAN id. Can be in format '1-2' or a single numerical value. If in '1-2' format, this specifies the vlan ID for the first inline interface and the rightmost for the second. :return: None """ first, second = self.nicid.split('-') firstintf = first.split('.')[0] secondintf = second.split('.')[0] newvlan = str(vlan_id).split('-') self.update(nicid='{}.{}-{}.{}'.format( firstintf, newvlan[0], secondintf, newvlan[-1]))
Change a VLAN id for an inline interface. :param str vlan_id: New VLAN id. Can be in format '1-2' or a single numerical value. If in '1-2' format, this specifies the vlan ID for the first inline interface and the rightmost for the second. :return: None
entailment
def change_interface_id(self, newid): """ Change the inline interface ID. The current format is nicid='1-2', where '1' is the top level interface ID (first), and '2' is the second interface in the pair. Consider the existing nicid in case this is a VLAN. :param str newid: string defining new pair, i.e. '3-4' :return: None """ try: newleft, newright = newid.split('-') except ValueError: raise EngineCommandFailed('You must provide two parts when changing ' 'the interface ID on an inline interface, i.e. 1-2.') first, second = self.nicid.split('-') if '.' in first and '.' in second: firstvlan = first.split('.')[-1] secondvlan = second.split('.')[-1] self.update(nicid='{}.{}-{}.{}'.format( newleft, firstvlan, newright, secondvlan)) else: # Top level interface or no VLANs self.update(nicid=newid)
Change the inline interface ID. The current format is nicid='1-2', where '1' is the top level interface ID (first), and '2' is the second interface in the pair. Consider the existing nicid in case this is a VLAN. :param str newid: string defining new pair, i.e. '3-4' :return: None
entailment
def vlan_id(self): """ VLAN ID for this interface, if any :return: VLAN identifier :rtype: str """ nicids = self.nicid.split('-') if nicids: u = [] for vlan in nicids: if vlan.split('.')[-1] not in u: u.append(vlan.split('.')[-1]) return '-'.join(u)
VLAN ID for this interface, if any :return: VLAN identifier :rtype: str
entailment
def create(cls, interface_id, logical_interface_ref, **kw): """ :param int interface_id: the interface id :param str logical_ref: logical interface reference, must be unique from inline intfs :rtype: dict """ data = {'inspect_unspecified_vlans': True, 'logical_interface_ref': logical_interface_ref, 'nicid': str(interface_id)} if 'reset_interface_nicid' in kw: data.update(reset_interface_nicid=kw.get('reset_interface_nicid')) return cls(data)
:param int interface_id: the interface id :param str logical_ref: logical interface reference, must be unique from inline intfs :rtype: dict
entailment
def create(cls, interface_id, address, network_value, nodeid=1, **kwargs): """ :param int interface_id: interface id :param str address: ip address of the interface :param str network_value: network/netmask, i.e. x.x.x.x/24 :param int nodeid: for clusters, used to identify the node number :rtype: dict """ data = {'address': address, 'network_value': network_value, 'nicid': str(interface_id), 'auth_request': False, 'backup_heartbeat': False, 'nodeid': nodeid, 'outgoing': False, 'primary_mgt': False, 'primary_heartbeat': False} for k, v in kwargs.items(): data.update({k: v}) return cls(data)
:param int interface_id: interface id :param str address: ip address of the interface :param str network_value: network/netmask, i.e. x.x.x.x/24 :param int nodeid: for clusters, used to identify the node number :rtype: dict
entailment
def create(cls, interface_id, address=None, network_value=None, nodeid=1, **kw): """ :param int interface_id: interface id :param str address: address of this interface :param str network_value: network of this interface in cidr x.x.x.x/24 :param int nodeid: if a cluster, identifies which node this is for :rtype: dict """ data = {'address': address, 'auth_request': False, 'auth_request_source': False, 'primary_heartbeat': False, 'backup_heartbeat': False, 'backup_mgt': False, 'dynamic': False, 'network_value': network_value, 'nicid': str(interface_id), 'nodeid': nodeid, 'outgoing': False, 'primary_mgt': False} for k, v in kw.items(): data.update({k: v}) if 'dynamic' in kw and kw['dynamic'] is not None: for key in ('address', 'network_value'): data.pop(key, None) if data['primary_mgt']: # Have to set auth_request to a different interface for DHCP data['auth_request'] = False if data.get('dynamic_index', None) is None: data['dynamic_index'] = 1 elif data.get('automatic_default_route') is None: data.update(automatic_default_route=True) return cls(data)
:param int interface_id: interface id :param str address: address of this interface :param str network_value: network of this interface in cidr x.x.x.x/24 :param int nodeid: if a cluster, identifies which node this is for :rtype: dict
entailment
def create(cls, address, ospf_area=None, **kwargs): """ Create a loopback interface. Uses parent constructor :rtype: LoopbackClusterInterface """ return super(LoopbackClusterInterface, cls).create( address=address, network_value='{}/32'.format(address), interface_id='Loopback Interface', ospfv2_area_ref=ospf_area, **kwargs)
Create a loopback interface. Uses parent constructor :rtype: LoopbackClusterInterface
entailment
def delete(self): """ Delete a loopback cluster virtual interface from this engine. Changes to the engine configuration are done immediately. You can find cluster virtual loopbacks by iterating at the engine level:: for loopbacks in engine.loopback_interface: ... :raises UpdateElementFailed: failure to delete loopback interface :return: None """ self._engine.data[self.typeof] = \ [loopback for loopback in self._engine.data.get(self.typeof, []) if loopback.get('address') != self.address] self._engine.update()
Delete a loopback cluster virtual interface from this engine. Changes to the engine configuration are done immediately. You can find cluster virtual loopbacks by iterating at the engine level:: for loopbacks in engine.loopback_interface: ... :raises UpdateElementFailed: failure to delete loopback interface :return: None
entailment
def add_cvi_loopback(self, address, ospf_area=None, **kw): """ Add a loopback interface as a cluster virtual loopback. This enables the loopback to 'float' between cluster members. Changes are committed immediately. :param str address: ip address for loopback :param int rank: rank of this entry :param str,Element ospf_area: optional ospf_area to add to loopback :raises UpdateElementFailed: failure to save loopback address :return: None """ lb = self.create(address, ospf_area, **kw) if self.typeof in self._engine.data: self._engine.data[self.typeof].append(lb.data) else: self._engine.data[self.typeof] = [lb.data] self._engine.update()
Add a loopback interface as a cluster virtual loopback. This enables the loopback to 'float' between cluster members. Changes are committed immediately. :param str address: ip address for loopback :param int rank: rank of this entry :param str,Element ospf_area: optional ospf_area to add to loopback :raises UpdateElementFailed: failure to save loopback address :return: None
entailment
def add_single(self, address, rank=1, nodeid=1, ospf_area=None, **kwargs): """ Add a single loopback interface to this engine. This is used for single or virtual FW engines. :param str address: ip address for loopback :param int nodeid: nodeid to apply. Default to 1 for single FW :param str, Element ospf_area: ospf area href or element :raises UpdateElementFailed: failure to create loopback address :return: None """ lb = self.create(address, rank, nodeid, ospf_area, **kwargs) self._engine.nodes[0].data[self.typeof].append(lb.data) self._engine.update()
Add a single loopback interface to this engine. This is used for single or virtual FW engines. :param str address: ip address for loopback :param int nodeid: nodeid to apply. Default to 1 for single FW :param str, Element ospf_area: ospf area href or element :raises UpdateElementFailed: failure to create loopback address :return: None
entailment
def delete(self): """ Delete a loopback interface from this engine. Changes to the engine configuration are done immediately. A simple way to obtain an existing loopback is to iterate the loopbacks or to get by address:: lb = engine.loopback_interface.get('127.0.0.10') lb.delete() .. warning:: When deleting a loopback assigned to a node on a cluster all loopbacks with the same rank will also be removed. :raises UpdateElementFailed: failure to delete loopback interface :return: None """ nodes = [] for node in self._engine.nodes: node.data[self.typeof] = \ [lb for lb in node.loopback_node_dedicated_interface if lb.get('rank') != self.rank] nodes.append({node.type: node.data}) self._engine.data['nodes'] = nodes self._engine.update()
Delete a loopback interface from this engine. Changes to the engine configuration are done immediately. A simple way to obtain an existing loopback is to iterate the loopbacks or to get by address:: lb = engine.loopback_interface.get('127.0.0.10') lb.delete() .. warning:: When deleting a loopback assigned to a node on a cluster all loopbacks with the same rank will also be removed. :raises UpdateElementFailed: failure to delete loopback interface :return: None
entailment
def create(cls, name, address, base_dn, bind_user_id=None, bind_password=None, port=389, protocol='ldap', tls_profile=None, tls_identity=None, domain_controller=None, supported_method=None, timeout=10, max_search_result=0, page_size=0, internet_auth_service_enabled=False, **kwargs): """ Create an AD server element using basic settings. You can also provide additional kwargs documented in the class description:: ActiveDirectoryServer.create(name='somedirectory', address='10.10.10.10', base_dn='dc=domain,dc=net', bind_user_id='cn=admin,cn=users,dc=domain,dc=net', bind_password='somecrazypassword') Configure NPS along with Active Directory:: ActiveDirectoryServer.create(name='somedirectory5', address='10.10.10.10', base_dn='dc=lepages,dc=net', internet_auth_service_enabled=True, retries=3, auth_ipaddress='10.10.10.15', auth_port=1900, shared_secret='123456') :param str name: name of AD element for display :param str address: address of AD server :param str base_dn: base DN for which to retrieve users, format is 'dc=domain,dc=com' :param str bind_user_id: bind user ID credentials, fully qualified. Format is 'cn=admin,cn=users,dc=domain,dc=com'. If not provided, anonymous bind is used :param str bind_password: bind password, required if bind_user_id set :param int port: LDAP bind port, (default: 389) :param str protocol: Which LDAP protocol to use, options 'ldap/ldaps/ldap_tls'. If ldaps or ldap_tls is used, you must provide a tls_profile element (default: ldap) :param str,TLSProfile tls_profile by element of str href. Used when protocol is set to ldaps or ldap_tls :param str,TLSIdentity tls_identity: check server identity when establishing TLS connection :param list(DomainController) domain_controller: list of domain controller objects to add an additional domain controllers for AD communication :param list(AuthenticationMethod) supported_method: authentication services allowed for this resource :param int timeout: The time (in seconds) that components wait for the server to reply :param int max_search_result: The maximum number of LDAP entries that are returned in an LDAP response (default: 0 for no limit) :param int page_size: The maximum number of LDAP entries that are returned on each page of the LDAP response. (default: 0 for no limit) :param bool internet_auth_service_enabled: whether to attach an NPS service to this AD controller (default: False). If setting to true, provide kwargs values for auth_ipaddress, auth_port and shared_secret :raises CreateElementFailed: failed creating element :rtype: ActiveDirectoryServer """ json={'name': name, 'address': address, 'base_dn': base_dn, 'bind_user_id': bind_user_id, 'bind_password': bind_password, 'port': port, 'protocol': protocol, 'timeout': timeout, 'domain_controller': domain_controller or [], 'max_search_result': max_search_result, 'page_size': page_size, 'internet_auth_service_enabled': internet_auth_service_enabled, 'supported_method': element_resolver(supported_method) or []} for obj_class in ('group_object_class', 'user_object_class'): json[obj_class] = kwargs.pop(obj_class, []) if protocol in ('ldaps', 'ldap_tls'): if not tls_profile: raise CreateElementFailed('You must provide a TLS Profile when TLS ' 'connections are configured to the AD controller.') json.update(tls_profile_ref=element_resolver(tls_profile), tls_identity=tls_identity) if internet_auth_service_enabled: ias = {'auth_port': kwargs.pop('auth_port', 1812), 'auth_ipaddress': kwargs.pop('auth_ipaddress', ''), 'shared_secret': kwargs.pop('shared_secret'), 'retries': kwargs.pop('retries', 2)} json.update(ias) json.update(kwargs) return ElementCreator(cls, json)
Create an AD server element using basic settings. You can also provide additional kwargs documented in the class description:: ActiveDirectoryServer.create(name='somedirectory', address='10.10.10.10', base_dn='dc=domain,dc=net', bind_user_id='cn=admin,cn=users,dc=domain,dc=net', bind_password='somecrazypassword') Configure NPS along with Active Directory:: ActiveDirectoryServer.create(name='somedirectory5', address='10.10.10.10', base_dn='dc=lepages,dc=net', internet_auth_service_enabled=True, retries=3, auth_ipaddress='10.10.10.15', auth_port=1900, shared_secret='123456') :param str name: name of AD element for display :param str address: address of AD server :param str base_dn: base DN for which to retrieve users, format is 'dc=domain,dc=com' :param str bind_user_id: bind user ID credentials, fully qualified. Format is 'cn=admin,cn=users,dc=domain,dc=com'. If not provided, anonymous bind is used :param str bind_password: bind password, required if bind_user_id set :param int port: LDAP bind port, (default: 389) :param str protocol: Which LDAP protocol to use, options 'ldap/ldaps/ldap_tls'. If ldaps or ldap_tls is used, you must provide a tls_profile element (default: ldap) :param str,TLSProfile tls_profile by element of str href. Used when protocol is set to ldaps or ldap_tls :param str,TLSIdentity tls_identity: check server identity when establishing TLS connection :param list(DomainController) domain_controller: list of domain controller objects to add an additional domain controllers for AD communication :param list(AuthenticationMethod) supported_method: authentication services allowed for this resource :param int timeout: The time (in seconds) that components wait for the server to reply :param int max_search_result: The maximum number of LDAP entries that are returned in an LDAP response (default: 0 for no limit) :param int page_size: The maximum number of LDAP entries that are returned on each page of the LDAP response. (default: 0 for no limit) :param bool internet_auth_service_enabled: whether to attach an NPS service to this AD controller (default: False). If setting to true, provide kwargs values for auth_ipaddress, auth_port and shared_secret :raises CreateElementFailed: failed creating element :rtype: ActiveDirectoryServer
entailment
def update_or_create(cls, with_status=False, **kwargs): """ Update or create active directory configuration. :param dict kwargs: kwargs to satisfy the `create` constructor arguments if the element doesn't exist or attributes to change :raises CreateElementFailed: failed creating element :return: element instance by type or 3-tuple if with_status set """ element, updated, created = super(ActiveDirectoryServer, cls).update_or_create( defer_update=True, **kwargs) if not created: domain_controller = kwargs.pop('domain_controller', []) if domain_controller: current_dc_list = element.domain_controller for dc in domain_controller: if dc not in current_dc_list: element.data.setdefault('domain_controller', []).append(dc.data) updated = True if updated: element.update() if with_status: return element, updated, created return element
Update or create active directory configuration. :param dict kwargs: kwargs to satisfy the `create` constructor arguments if the element doesn't exist or attributes to change :raises CreateElementFailed: failed creating element :return: element instance by type or 3-tuple if with_status set
entailment
def create(cls, name, entries=None, comment=None, **kw): """ Create an Access List Entry. Depending on the access list type you are creating (IPAccessList, IPv6AccessList, IPPrefixList, IPv6PrefixList, CommunityAccessList, ExtendedCommunityAccessList), entries will define a dict of the valid attributes for that ACL type. Each class has a defined list of attributes documented in it's class. You can optionally leave entries blank and use the :meth:`~add_entry` method after creating the list container. :param str name: name of IP Access List :param list entries: access control entry :param kw: optional keywords that might be necessary to create the ACL (see specific Access Control List documentation for options) :raises CreateElementFailed: cannot create element :return: The access list based on type """ access_list_entry = [] if entries: for entry in entries: access_list_entry.append( {'{}_entry'.format(cls.typeof): entry}) json = {'name': name, 'entries': access_list_entry, 'comment': comment} json.update(kw) return ElementCreator(cls, json)
Create an Access List Entry. Depending on the access list type you are creating (IPAccessList, IPv6AccessList, IPPrefixList, IPv6PrefixList, CommunityAccessList, ExtendedCommunityAccessList), entries will define a dict of the valid attributes for that ACL type. Each class has a defined list of attributes documented in it's class. You can optionally leave entries blank and use the :meth:`~add_entry` method after creating the list container. :param str name: name of IP Access List :param list entries: access control entry :param kw: optional keywords that might be necessary to create the ACL (see specific Access Control List documentation for options) :raises CreateElementFailed: cannot create element :return: The access list based on type
entailment
def add_entry(self, **kw): """ Add an entry to an AccessList. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failure to modify with reason :return: None """ self.data.setdefault('entries', []).append( {'{}_entry'.format(self.typeof): kw})
Add an entry to an AccessList. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failure to modify with reason :return: None
entailment
def remove_entry(self, **field_value): """ Remove an AccessList entry by field specified. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failed to modify with reason :return: None """ field, value = next(iter(field_value.items())) self.data['entries'][:] = [entry for entry in self.data.get('entries') if entry.get('{}_entry'.format(self.typeof)) .get(field) != str(value)]
Remove an AccessList entry by field specified. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failed to modify with reason :return: None
entailment