class NetmikoFileTransferForm(NetmikoForm): form_type = HiddenField(default="netmiko_file_transfer_service") source_file = StringField(validators=[InputRequired()], substitution=True) destination_file = StringField(validators=[InputRequired()], substitution=True) file_system = StringField() direction = SelectField(choices=(("put", "Upload"), ("get", "Download"))) disable_md5 = BooleanField() inline_transfer = BooleanField() overwrite_file = BooleanField() groups = { "Main Parameters": { "commands": [ "source_file", "destination_file", "file_system", "direction", "disable_md5", "inline_transfer", "overwrite_file", ], "default": "expanded", }, **NetmikoForm.groups, }
class GenericFileTransferForm(ServiceForm): form_type = HiddenField(default="generic_file_transfer_service") direction = SelectField(choices=(("get", "Get"), ("put", "Put"))) protocol = SelectField(choices=(("scp", "SCP"), ("sftp", "SFTP"))) source_file = StringField(validators=[InputRequired()], substitution=True) destination_file = StringField(validators=[InputRequired()], substitution=True) missing_host_key_policy = BooleanField() load_known_host_keys = BooleanField() source_file_includes_globbing = BooleanField( "Source file includes glob pattern") max_transfer_size = IntegerField(default=2**30) window_size = IntegerField(default=2**30) timeout = FloatField(default=10.0) credentials = SelectField( "Credentials", choices=( ("device", "Device Credentials"), ("user", "User Credentials"), ("custom", "Custom Credentials"), ), ) custom_username = StringField("Custom Username", substitution=True) custom_password = PasswordField("Custom Password", substitution=True) def validate(self): valid_form = super().validate() invalid_direction = (self.source_file_includes_globbing.data and self.direction.data == "get") if invalid_direction: self.direction.errors.append( "Globbing only works with the 'PUT' direction") return valid_form and not invalid_direction
class NetmikoValidationForm(NetmikoForm): form_type = HiddenField(default="netmiko_validation_service") command = StringField(substitution=True) use_textfsm = BooleanField("Use TextFSM", default=False) expect_string = StringField(substitution=True, help="netmiko/expect_string") config_mode_command = StringField(help="netmiko/config_mode_command") auto_find_prompt = BooleanField(default=True, help="netmiko/auto_find_prompt") strip_prompt = BooleanField(default=True, help="netmiko/strip_prompt") strip_command = BooleanField(default=True, help="netmiko/strip_command") groups = { "Main Parameters": { "commands": ["command"], "default": "expanded" }, **NetmikoForm.groups, "Advanced Netmiko Parameters": { "commands": [ "use_textfsm", "expect_string", "config_mode_command", "auto_find_prompt", "strip_prompt", "strip_command", ], "default": "hidden", }, }
class ConnectionForm(ServiceForm): form_type = HiddenField(default="connection") get_request_allowed = False abstract_service = True credentials = SelectField( "Credentials", choices=( ("device", "Device Credentials"), ("user", "User Credentials"), ("custom", "Custom Credentials"), ), ) custom_username = StringField("Custom Username", substitution=True) custom_password = PasswordField("Custom Password", substitution=True) start_new_connection = BooleanField("Start New Connection") connection_name = StringField("Connection Name", default="default") close_connection = BooleanField("Close Connection") groups = { "Connection Parameters": { "commands": [ "credentials", "custom_username", "custom_password", "start_new_connection", "connection_name", "close_connection", ], "default": "expanded", } }
class NetmikoConfigurationForm(NetmikoForm): form_type = HiddenField(default="netmiko_configuration_service") config_mode = BooleanField("Config mode", default=True) content = StringField(widget=TextArea(), render_kw={"rows": 5}, substitution=True) commit_configuration = BooleanField() exit_config_mode = BooleanField(default=True) strip_prompt = BooleanField() strip_command = BooleanField() config_mode_command = StringField(help="netmiko/config_mode_command") groups = { "Main Parameters": { "commands": [ "content", "commit_configuration", "exit_config_mode", "config_mode_command", ], "default": "expanded", }, **NetmikoForm.groups, "Advanced Netmiko Parameters": { "commands": ["strip_prompt", "strip_command"], "default": "hidden", }, }
class GitForm(ServiceForm): form_type = HiddenField(default="git_service") git_repository = StringField("Path to Local Git Repository") relative_path = BooleanField("Path is relative to eNMS folder") pull = BooleanField("Git Pull") add_commit = BooleanField("Do 'git add' and commit") commit_message = StringField("Commit Message") push = BooleanField("Git Push")
class DatabaseMigrationsForm(BaseForm): template = "database_migration" form_type = HiddenField(default="database_migration") empty_database_before_import = BooleanField("Empty Database before Import") skip_pool_update = BooleanField("Skip the Pool update after Import", default="checked") export_private_properties = BooleanField("Include private properties", default="checked") export_choices = vs.dualize(db.import_export_models) import_export_types = SelectMultipleField("Instances to migrate", choices=export_choices)
def form_init(cls): cls.models = ("device", "link", "service", "user") for model in cls.models: setattr(cls, f"{model}_properties", vs.properties["filtering"][model]) for property in vs.properties["filtering"][model]: setattr(cls, f"{model}_{property}", StringField(property)) setattr(cls, f"{model}_{property}_invert", BooleanField(property)) vs.form_properties["pool"][f"{model}_{property}_match"] = { "type": "list" } vs.form_properties["pool"][f"{model}_{property}_invert"] = { "type": "bool" } setattr( cls, f"{model}_{property}_match", SelectField(choices=( ("inclusion", "Inclusion"), ("equality", "Equality"), ("regex", "Regular Expression"), ("empty", "Empty"), )), )
class ScrapliForm(ConnectionForm): form_type = HiddenField(default="scrapli_service") commands = StringField(substitution=True, widget=TextArea(), render_kw={"rows": 5}) is_configuration = BooleanField() driver = SelectField(choices=vs.dualize(vs.scrapli_drivers)) transport = SelectField(choices=vs.dualize(("system", "paramiko", "ssh2"))) use_device_driver = BooleanField(default=True) groups = { "Main Parameters": { "commands": [ "commands", "is_configuration", "driver", "transport", "use_device_driver", ], "default": "expanded", }, **ConnectionForm.groups, }
class PoolForm(BaseForm): template = "pool" form_type = HiddenField(default="pool") id = HiddenField() name = StringField("Name", [InputRequired()]) admin_only = BooleanField("Pool visible to admin users only") access_groups = StringField("Groups") description = StringField("Description") manually_defined = BooleanField( "Manually defined (won't be automatically updated)") @classmethod def form_init(cls): cls.models = ("device", "link", "service", "user") for model in cls.models: setattr(cls, f"{model}_properties", vs.properties["filtering"][model]) for property in vs.properties["filtering"][model]: setattr(cls, f"{model}_{property}", StringField(property)) setattr(cls, f"{model}_{property}_invert", BooleanField(property)) vs.form_properties["pool"][f"{model}_{property}_match"] = { "type": "list" } vs.form_properties["pool"][f"{model}_{property}_invert"] = { "type": "bool" } setattr( cls, f"{model}_{property}_match", SelectField(choices=( ("inclusion", "Inclusion"), ("equality", "Equality"), ("regex", "Regular Expression"), ("empty", "Empty"), )), )
class ScrapliNetconfForm(ConnectionForm): form_type = HiddenField(default="scrapli_netconf_service") command = SelectField(choices=( ("get", "Get"), ("rpc", "RPC"), ("get_config", "Get Configuration"), ("edit_config", "Edit Configuration"), ("delete_config", "Delete Configuration"), ("commit", "Commit Configuration"), ("discard", "Discard Configuration"), ("lock", "Lock"), ("unlock", "Unlock"), )) target = SelectField(choices=( ("running", "Running Configuration"), ("startup", "Startup Configuration"), ("candidate", "Candidate Configuration"), )) content = StringField(substitution=True, widget=TextArea(), render_kw={"rows": 5}) commit_config = BooleanField("Commit After Editing Configuration") strip_namespaces = BooleanField("Strip Namespaces from returned XML") groups = { "Main Parameters": { "commands": [ "command", "target", "content", "commit_config", "strip_namespaces", ], "default": "expanded", }, **ConnectionForm.groups, }
class UserForm(RbacForm): form_type = HiddenField(default="user") groups = StringField("Groups") theme = SelectField( "Theme", choices=[(theme, values["name"]) for theme, values in vs.themes["themes"].items()], ) authentication = SelectField( "Authentication", choices=[(method, values["display_name"]) for method, values in vs.settings["authentication"]["methods"].items()], ) password = PasswordField("Password") is_admin = BooleanField(default=False)
class WorkflowForm(ServiceForm): form_type = HiddenField(default="workflow") close_connection = BooleanField(default=False) run_method = SelectField( "Run Method", choices=( ("per_device", "Run the workflow device by device"), ( "per_service_with_workflow_targets", "Run the workflow service by service using workflow targets", ), ( "per_service_with_service_targets", "Run the workflow service by service using service targets", ), ), ) superworkflow = InstanceField("Superworkflow")
class NapalmForm(ConnectionForm): form_type = HiddenField(default="napalm") get_request_allowed = False abstract_service = True driver = SelectField(choices=vs.napalm_drivers) use_device_driver = BooleanField( default=True, help="common/use_device_driver", ) timeout = IntegerField(default=10) optional_args = DictField() groups = { "Napalm Parameters": { "commands": ["driver", "use_device_driver", "timeout", "optional_args"], "default": "expanded", }, **ConnectionForm.groups, }
class DataBackupForm(NetmikoForm): form_type = HiddenField(default="netmiko_backup_service") property = SelectField( "Configuration Property to Update", choices=list(vs.configuration_properties.items()), ) commands = FieldList(FormField(CommandsForm), min_entries=12) replacements = FieldList(FormField(ReplacementForm), min_entries=12) add_header = BooleanField("Add header for each ommand", default=True) groups = { "Target property and commands": { "commands": ["property", "add_header", "commands"], "default": "expanded", }, "Search Response & Replace": { "commands": ["replacements"], "default": "expanded", }, **NetmikoForm.groups, }
class AnsiblePlaybookForm(ServiceForm): form_type = HiddenField(default="ansible_playbook_service") playbook_path = SelectField("Playbook Path", validate_choice=False) arguments = StringField( "Arguments (Ansible command line options)", substitution=True, help="ansible/arguments", ) pass_device_properties = BooleanField( "Pass Device Inventory Properties (to be used " "in the playbook as {{name}} or {{ip_address}})") credentials = SelectField( "Credentials", choices=( ("device", "Device Credentials"), ("user", "User Credentials"), ), ) options = DictField( "Options (passed to ansible as -e extra args)", substitution=True, help="ansible/options", )
class SettingsForm(BaseForm): form_type = HiddenField(default="settings_panel") action = "eNMS.administration.saveSettings" settings = JsonField("Settings") write_changes = BooleanField("Write changes back to 'settings.json' file")
class ServiceForm(BaseForm): template = "service" form_type = HiddenField(default="service") get_request_allowed = False id = HiddenField() name = StringField("Name") type = StringField("Service Type") access_groups = StringField("Groups") shared = BooleanField("Shared") scoped_name = StringField("Scoped Name", [InputRequired()]) description = StringField("Description") device_query = StringField("Device Query", python=True, widget=TextArea(), render_kw={"rows": 2}) device_query_property = SelectField("Query Property Type", choices=(("name", "Name"), ("ip_address", "IP address"))) target_devices = MultipleInstanceField("Devices", model="device") disable_result_creation = BooleanField("Save only failed results") target_pools = MultipleInstanceField("Pools", model="pool") update_target_pools = BooleanField("Update target pools before running") update_pools_after_running = BooleanField("Update pools after running") workflows = MultipleInstanceField("Workflows", model="workflow") owners = MultipleInstanceField("Owners", model="user") owners_access = SelectMultipleStringField( "Owners Access", choices=[("run", "Run"), ("edit", "Edit")], ) waiting_time = IntegerField( "Time to Wait before next service is started (in seconds)", default=0) priority = IntegerField("Priority", default=1) send_notification = BooleanField("Send a notification") send_notification_method = SelectField( "Notification Method", choices=(("mail", "Mail"), ("slack", "Slack"), ("mattermost", "Mattermost")), ) notification_header = StringField(widget=TextArea(), render_kw={"rows": 5}, substitution=True) include_device_results = BooleanField("Include Device Results") include_link_in_summary = BooleanField("Include Result Link in Summary") display_only_failed_nodes = BooleanField("Display only Failed Devices") mail_recipient = StringField("Mail Recipients (separated by comma)") reply_to = StringField("Reply-to Email Address") number_of_retries = IntegerField("Number of retries", default=0) time_between_retries = IntegerField("Time between retries (in seconds)", default=10) max_number_of_retries = IntegerField("Maximum number of retries", default=100) credential_type = SelectField( "Type of Credentials", choices=( ("any", "Any"), ("read-write", "Read Write"), ("read-only", "Read Only"), ), ) maximum_runs = IntegerField("Maximum number of runs", default=1) skip_query = StringField("Skip Query (Python)", python=True, widget=TextArea(), render_kw={"rows": 2}) skip_value = SelectField( "Skip Value", choices=( ("success", "Success"), ("failure", "Failure"), ("discard", "Discard"), ), ) vendor = StringField("Vendor") operating_system = StringField("Operating System") iteration_values = StringField("Iteration Values", python=True) initial_payload = DictField() mandatory_parametrization = BooleanField("Parameterized Form is Mandatory") parameterized_form = StringField( type="code", python=True, widget=TextArea(), default="\n".join(vs.automation["parameterized_form"]), ) iteration_variable_name = StringField("Iteration Variable Name", default="iteration_value") iteration_devices = StringField("Iteration Devices", python=True) iteration_devices_property = SelectField( "Iteration Devices Property", choices=(("name", "Name"), ("ip_address", "IP address")), ) preprocessing = StringField(type="code", python=True, widget=TextArea()) postprocessing = StringField(type="code", python=True, widget=TextArea()) postprocessing_mode = SelectField(choices=( ("success", "Run on success only"), ("failure", "Run on failure only"), ("always", "Always run"), )) default_access = SelectField(choices=( ("creator", "Role Based (Creator)"), ("public", "Public (All users)"), ("admin", "Admin (Admins only"), )) log_level = SelectField( "Logging", choices=((0, "Disable logging"), *enumerate(vs.log_levels, 1)), default=1, ) multiprocessing = BooleanField("Multiprocessing") max_processes = IntegerField("Maximum number of processes", default=15) validation_condition = SelectField(choices=( ("none", "No validation"), ("success", "Run on success only"), ("failure", "Run on failure only"), ("always", "Always run"), )) conversion_method = SelectField(choices=( ("none", "No conversion"), ("text", "Text"), ("json", "Json dictionary"), ("xml", "XML dictionary"), )) validation_method = SelectField( "Validation Method", choices=( ("text", "Validation by text match"), ("dict_included", "Validation by dictionary inclusion"), ("dict_equal", "Validation by dictionary equality"), ), ) validation_section = StringField("Section to Validate", default="results['result']") content_match = StringField("Content Match", widget=TextArea(), render_kw={"rows": 8}, substitution=True) content_match_regex = BooleanField( '"Content Match" is a regular expression') dict_match = DictField("Dictionary to Match Against", substitution=True) negative_logic = BooleanField("Negative logic") delete_spaces_before_matching = BooleanField( "Delete Spaces before Matching") run_method = SelectField( "Run Method", choices=( ("per_device", "Run the service once per device"), ("once", "Run the service once"), ), ) def validate(self): valid_form = super().validate() no_recipient_error = (self.send_notification.data and self.send_notification_method.data == "mail" and not self.mail_recipient.data) if no_recipient_error: self.mail_recipient.errors.append( "Please add at least one recipient for the mail notification.") forbidden_name_error = self.scoped_name.data in ("Start", "End", "Placeholder") if forbidden_name_error: self.name.errors.append("This name is not allowed.") conversion_validation_mismatch = self.validation_condition.data != "none" and ( self.conversion_method.data == "text" and "dict" in self.validation_method.data or self.conversion_method.data in ("xml", "json") and "dict" not in self.validation_method.data) if conversion_validation_mismatch: self.conversion_method.errors.append( f"The conversion method is set to {self.conversion_method.data}" f" and the validation method to {self.validation_method.data} :" " these do not match.") empty_validation = self.validation_condition.data != "none" and ( self.validation_method.data == "text" and not self.content_match.data or self.validation_method.data == "dict_included" and self.dict_match.data == "{}") if empty_validation: self.content_match.errors.append( f"The validation method is set to '{self.validation_method.data}'" f" and the matching value is empty: these do no match.") too_many_threads_error = (self.max_processes.data > vs.settings["automation"]["max_process"]) if too_many_threads_error: self.max_processes.errors.append( "The number of threads used for multiprocessing must be " f"less than {vs.settings['automation']['max_process']}.") shared_service_error = not self.shared.data and len( self.workflows.data) > 1 if shared_service_error: self.shared.errors.append( "The 'shared' property is unticked, but the service belongs" " to more than one workflow: this is incompatible.") return (valid_form and not conversion_validation_mismatch and not empty_validation and not forbidden_name_error and not no_recipient_error and not shared_service_error and not too_many_threads_error)
class ExcelImportForm(BaseForm): template = "topology_import" form_type = HiddenField(default="excel_import") replace = BooleanField("Replace Existing Topology")
class ExampleForm(ServiceForm): # Each service model must have an corresponding form. # The purpose of a form is twofold: # - Define how the service is displayed in the UI # - Check for each field that the user input is valid. # A service cannot be created/updated until all fields are validated. # The following line is mandatory: the default value must point # to the service. form_type = HiddenField(default="example_service") # string1 is defined as a "SelectField": it will be displayed as a # drop-down list in the UI. string1 = SelectField( choices=[("cisco", "Cisco"), ("juniper", "Juniper"), ("arista", "Arista")] ) # String2 is a StringField, which is displayed as a standard textbox. # The "InputRequired" validator is used: this field is mandatory. string2 = StringField("String 2 (required)", [InputRequired()]) # The main address length must be comprised between 7 and 25 characters mail_address = StringField("Mail address", [Length(min=7, max=25)]) # This IP address validator will ensure the user input is a valid IPv4 address. # If it isn't, you can set the error message to be displayed in the GUI. ip_address = StringField( "IP address", [ IPAddress( ipv4=True, message="Please enter an IPv4 address for the IP address field", ) ], ) # MAC address validator mac_address = StringField("MAC address", [MacAddress()]) # The NumberRange validator will ensure the user input is an integer # between 3 and 8. number_in_range = IntegerField("Number in range", [NumberRange(min=3, max=8)]) # The Regexp field will ensure the user input matches the regular expression. regex = StringField("Regular expression", [Regexp(r".*")]) # URL validation, with or without TLD. url = StringField( "URL", [ URL( require_tld=True, message="An URL with TLD is required for the url field", ) ], ) # The NoneOf validator lets you define forbidden value for a field. exclusion_field = StringField( "Exclusion field", [ NoneOf( ("a", "b", "c"), message=( "'a', 'b', and 'c' are not valid " "inputs for the exclusion field" ), ) ], ) an_integer = IntegerField() a_float = FloatField() # If validator the user input is more complex, you can create a python function # to implement the validation mechanism. # Here, the custom_integer field will be validated by the "validate_custom_integer" # function below. # That function will check that the custom integer value is superior to the product # of "an_integer" and "a_float". # You must raise a "ValidationError" when the validation fails. custom_integer = IntegerField("Custom Integer") # A SelectMultipleField will be displayed as a drop-down list that allows # multiple selection. a_list = SelectMultipleField( choices=[("value1", "Value 1"), ("value2", "Value 2"), ("value3", "Value 3")] ) a_dict = DictField() # A BooleanField is displayed as a check box. boolean1 = BooleanField() boolean2 = BooleanField("Boolean N°1") def validate_custom_integer(self, field): product = self.an_integer.data * self.a_float.data if field.data > product: raise ValidationError( "Custom integer must be less than the " "product of 'An integer' and 'A float'" )
class NetmikoForm(ConnectionForm): form_type = HiddenField(default="netmiko") abstract_service = True driver = SelectField(choices=vs.netmiko_drivers) use_device_driver = BooleanField( default=True, help="common/use_device_driver", ) enable_mode = BooleanField("Enable mode (run in enable mode or as root)", default=True) config_mode = BooleanField( "Config mode (See Advanced Parameters to override the config mode command)", default=False, ) fast_cli = BooleanField() timeout = FloatField(default=10.0) delay_factor = FloatField( ("Delay Factor (Changing from default of 1" " will nullify Netmiko Timeout setting)"), default=1.0, ) global_delay_factor = FloatField( ("Global Delay Factor (Changing from default of 1" " will nullify Netmiko Timeout setting)"), default=1.0, ) jump_on_connect = BooleanField( "Jump to remote device on connect", default=False, help="netmiko/jump_on_connect", ) jump_command = StringField( label="Command that jumps to device", default="ssh jump_server_IP", substitution=True, help="netmiko/jump_command", ) jump_username = StringField(label="Device username", substitution=True, help="netmiko/jump_username") jump_password = PasswordField(label="Device password", substitution=True, help="netmiko/jump_password") exit_command = StringField( label="Command to exit device back to original device", default="exit", substitution=True, help="netmiko/exit_command", ) expect_username_prompt = StringField( "Expected username prompt", default="username:"******"netmiko/expect_username_prompt", ) expect_password_prompt = StringField( "Expected password prompt", default="password", substitution=True, help="netmiko/expect_password_prompt", ) expect_prompt = StringField( "Expected prompt after login", default="admin.*$", substitution=True, help="netmiko/expect_prompt", ) groups = { "Netmiko Parameters": { "commands": [ "driver", "use_device_driver", "enable_mode", "config_mode", "fast_cli", "timeout", "delay_factor", "global_delay_factor", ], "default": "expanded", }, **ConnectionForm.groups, "Jump on connect Parameters": { "commands": [ "jump_on_connect", "jump_command", "expect_username_prompt", "jump_username", "expect_password_prompt", "jump_password", "expect_prompt", "exit_command", ], "default": "hidden", }, }
class NetconfForm(ConnectionForm): form_type = HiddenField(default="netconf_service") nc_type = SelectField( choices=( ("get_config", "Get Full Config"), ("get_filtered_config", "Get"), ("push_config", "Edit Config"), ("copy_config", "Copy Config"), ("rpc", "Dispatch"), ), label="NETCONF Operation", ) xml_filter = StringField(label="XML Filter", widget=TextArea(), render_kw={"rows": 5}, substitution=True) target = SelectField( choices=( ("running", "Running"), ("candidate", "Candidate"), ("startup", "Startup"), ), label="Target Config", ) default_operation = SelectField( choices=( ("merge", "Merge"), ("replace", "Replace"), ("None", "None"), ), label="Default config operation", validate_choice=False, ) test_option = SelectField( choices=( ("test-then-set", "Test, then set"), ("set", "Set"), ("None", "None"), ), label="Config test option", validate_choice=False, ) error_option = SelectField( choices=( ("stop-on-error", "Stop on error"), ("continue-on-error", "Continue on error"), ("rollback-on-error", "Rollback on error"), ("None", "None"), ), label="Error option", validate_choice=False, ) lock = BooleanField(label="Lock target") unlock = BooleanField(label="Unlock target") copy_source = SelectField( choices=( ("running", "Running"), ("candidate", "Candidate"), ("startup", "Startup"), ("source_url", "Source URL"), ), label="Copy Source", validate_choice=False, ) source_url = StringField( label="Copy source URL", widget=TextArea(), render_kw={"rows": 1}, substitution=True, ) copy_destination = SelectField( choices=( ("running", "Running"), ("candidate", "Candidate"), ("startup", "Startup"), ("destination_url", "Destination URL"), ), label="Copy Destination", validate_choice=False, ) destination_url = StringField( label="Copy destination URL", widget=TextArea(), render_kw={"rows": 1}, substitution=True, ) commit_conf = BooleanField(label="Commit") timeout = IntegerField(default=15) xml_conversion = BooleanField(label="Convert XML result to dictionary", default=True) @classmethod def form_init(cls): parameters = { "get_config": ["target", "xml_conversion"], "get_filtered_config": [ "target", "xml_filter", "xml_conversion", ], "push_config": [ "target", "xml_filter", "default_operation", "test_option", "error_option", "lock", "unlock", "commit_conf", "xml_conversion", ], "copy_config": [ "copy_source", "source_url", "copy_destination", "destination_url", "commit_conf", "xml_conversion", ], "rpc": ["xml_filter", "xml_conversion"], } list_parameters = list(set(sum(parameters.values(), []))) cls.groups = { "NETCONF Parameters": { "commands": ["nc_type"] + list_parameters, "default": "expanded", }, **ConnectionForm.groups, } cls.input_data = HiddenField( "", default=dumps({ "fields": list_parameters, "netconf_type": parameters }), )