Пример #1
0
    def save_device(self, uuid=None, export_format="json"):
        """
        Saves the specified device in the specified export format to the repository
        :param uuid: The UUID of the device to be saved
        :param export_format: The export format (e.g. "json")
        :return: True if save is successful, False otherwise
        """
        if export_format not in ["json"]:
            return False
        if uuid is None:
            return False

        # Find the device that needs to be exported
        device = self.find_device_by_uuid(device_uuid=uuid)
        if not device:
            print("Failed to locate device with UUID " + str(uuid) +
                  " for export")
            return False

        directory = self.REPOSITORY_FOLDER_NAME + "/" + str(uuid)
        filename = "device-" + str(uuid) + "." + export_format

        # Creating folder for device
        if not os.path.exists(directory):
            os.makedirs(directory)

        if export_format == "json":
            header_json = {}
            header_json["metadata"] = [
                export.generate_json_metadata_header(file_type="device",
                                                     device=device)
            ]
            device_json = {}
            device_json["easyucs"] = header_json
            device_json["device"] = {}

            device_json["device"]["target"] = device.target
            device_json["device"]["username"] = device.username
            device_json["device"]["password"] = device.password

            # Calculate hash of entire JSON file and adding it to header before exporting
            device_json = export.insert_json_metadata_hash(
                json_content=device_json)

            print("Exporting device " + str(device.uuid) + " to file: " +
                  directory + "/" + filename)
            with open(directory + '/' + filename, 'w') as device_json_file:
                json.dump(device_json, device_json_file, indent=3)
            device_json_file.close()
            return True
Пример #2
0
    def export_device(self,
                      export_format="json",
                      directory=None,
                      filename=None):
        """
        Exports a device using the specified export format to a file
        :param export_format: Export format. Currently only supports JSON
        :param directory: Directory to store the export file
        :param filename: Name of the export file
        :return: True if export is successful, False otherwise
        """
        if export_format not in ["json"] or filename is None:
            return False
        if directory is None:
            directory = "."

        if export_format == "json":
            header_json = {}
            header_json["metadata"] = [
                export.generate_json_metadata_header(file_type="device",
                                                     device=self)
            ]
            device_json = {}
            device_json["easyucs"] = header_json
            device_json["device"] = {}

            device_json["device"]["target"] = self.target
            device_json["device"]["username"] = self.username
            device_json["device"]["password"] = self.password

            # Calculate hash of entire JSON file and adding it to header before exporting
            device_json = export.insert_json_metadata_hash(
                json_content=device_json)

            self.logger(message="Exporting device " + str(self.uuid) +
                        " to file: " + directory + "/" + filename)
            with open(directory + '/' + filename, 'w') as device_json_file:
                json.dump(device_json, device_json_file, indent=3)
            device_json_file.close()
            return True
Пример #3
0
    def export_config(self,
                      uuid=None,
                      export_format="json",
                      directory=None,
                      filename=None):
        """
        Exports the specified config in the specified export format to the specified filename
        :param uuid: The UUID of the config to be exported. If not specified, the most recent config will be used
        :param export_format: The export format (e.g. "json")
        :param directory: The directory containing the export file
        :param filename: The name of the file containing the exported content
        :return: True if export is successful, False otherwise
        """
        if export_format not in ["json"]:
            self.logger(
                level="error",
                message="Requested config export format not supported!")
            return False
        if filename is None:
            self.logger(level="error",
                        message="Missing filename in config export request!")
            return False
        if not directory:
            self.logger(
                level="debug",
                message=
                "No directory specified in config export request. Using local folder."
            )
            directory = "."

        if uuid is None:
            self.logger(
                level="debug",
                message=
                "No config UUID specified in config export request. Using latest."
            )
            config = self.get_latest_config()
        else:
            # Find the config that needs to be exported
            config_list = [
                config for config in self.config_list if config.uuid == uuid
            ]
            if len(config_list) != 1:
                self.logger(level="error",
                            message="Failed to locate config with UUID " +
                            str(uuid) + " for export")
                return False
            else:
                config = config_list[0]

        if config is None:
            # We could not find any config
            self.logger(level="error",
                        message="Could not find any config to export!")
            return False
        if config.export_list is None or len(config.export_list) == 0:
            # Nothing to export
            self.logger(level="error",
                        message="Nothing to export on the selected config!")
            return False

        self.logger(level="debug",
                    message="Using config " + str(config.uuid) + " for export")

        if export_format == "json":
            self.logger(level="debug",
                        message="Requested config export format is JSON")
            header_json = {}
            header_json["metadata"] = [
                export.generate_json_metadata_header(file_type="config",
                                                     config=config)
            ]
            config_json = {}
            config_json["easyucs"] = header_json
            config_json["config"] = {}
            for export_attribute in config.export_list:
                # We check if the attribute to be exported is an empty list, in which case, we don't export it
                if isinstance(getattr(config, export_attribute), list):
                    if len(getattr(config, export_attribute)) == 0:
                        continue
                config_json["config"][export_attribute] = []
                if isinstance(getattr(config, export_attribute), list):
                    count = 0
                    for config_object in getattr(config, export_attribute):
                        if isinstance(config_object, str):
                            config_json["config"][export_attribute].append(
                                config_object)
                        elif isinstance(config_object, list):
                            config_json["config"][export_attribute].extend(
                                config_object)
                        else:
                            config_json["config"][export_attribute].append({})
                            export.export_attributes_json(
                                config_object,
                                config_json["config"][export_attribute][count])
                        count += 1
                elif isinstance(getattr(config, export_attribute), str):
                    config_json["config"][export_attribute] = getattr(
                        config, export_attribute)
                else:
                    config_object = getattr(config, export_attribute)
                    config_json["config"][export_attribute].append({})
                    export.export_attributes_json(
                        config_object,
                        config_json["config"][export_attribute][0])

            # Calculate md5 hash of entire JSON file and adding it to header before exporting
            config_json = export.insert_json_metadata_hash(
                json_content=config_json)

            self.logger(message="Exporting config " + str(config.uuid) +
                        " to file: " + directory + "/" + filename)
            if not os.path.exists(directory):
                self.logger(message="Creating directory " + directory)
                os.makedirs(directory)
            with open(directory + '/' + filename, 'w') as config_json_file:
                json.dump(config_json, config_json_file, indent=3)
            config_json_file.close()
            return True