def setUp(self, oneview_client): """Tests SubscriptionCollection blueprint setup""" # Loading variable in util module util.load_config('redfish.conf') # creates a test client self.app = Flask(__name__) self.app.register_blueprint(subscription_collection) @self.app.errorhandler(status.HTTP_500_INTERNAL_SERVER_ERROR) def internal_server_error(error): """General InternalServerError handler for the app""" redfish_error = RedfishError( "InternalError", "The request failed due to an internal service error. " "The service is still operational.") redfish_error.add_extended_info("InternalError") error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_500_INTERNAL_SERVER_ERROR, mimetype="application/json") # creates a test client self.app = self.app.test_client() # propagate the exceptions to the test client self.app.testing = True
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading server_hardware mockup value with open('oneview_redfish_toolkit/mockups/oneview/' 'ServerHardwares.json') as f: self.server_hardware = json.load(f) # Loading enclosures mockup value with open('oneview_redfish_toolkit/mockups/oneview/' 'Enclosures.json') as f: self.enclosures = json.load(f) # Loading racks mockup value with open('oneview_redfish_toolkit/mockups/oneview/' 'Racks.json') as f: self.racks = json.load(f) # Loading ChassisCollection result mockup with open('oneview_redfish_toolkit/mockups/redfish/' 'ChassisCollection.json') as f: self.chassis_collection_mockup = json.load(f)
def setUp(self, oneview_client_mockup): """Tests ServiceRoot blueprint setup""" # Load config on util util.load_config('redfish.conf') # creates a test client self.app = Flask(__name__) self.app.register_blueprint( service_root.service_root, url_prefix='/redfish/v1/') @self.app.errorhandler(status.HTTP_500_INTERNAL_SERVER_ERROR) def internal_server_error(error): """Creates an Internal Server Error response""" redfish_error = RedfishError( "InternalError", "The request failed due to an internal service error. " "The service is still operational.") redfish_error.add_extended_info("InternalError") error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_500_INTERNAL_SERVER_ERROR, mimetype="application/json") # creates a test client self.app = self.app.test_client() # propagate the exceptions to the test client self.app.testing = True
def setUp(self, oneview_client): """Tests Subscription blueprint setup""" # Loading variable in util module util.load_config('redfish.conf') # creates a test client self.app = Flask(__name__) self.app.register_blueprint(subscription) @self.app.errorhandler(status.HTTP_500_INTERNAL_SERVER_ERROR) def internal_server_error(error): """General InternalServerError handler for the app""" redfish_error = RedfishError( "InternalError", "The request failed due to an internal service error. " "The service is still operational.") redfish_error.add_extended_info("InternalError") error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_500_INTERNAL_SERVER_ERROR, mimetype="application/json") @self.app.errorhandler(status.HTTP_400_BAD_REQUEST) def bad_request(error): """Creates a Bad Request Error response""" redfish_error = RedfishError( "PropertyValueNotInList", error.description) redfish_error.add_extended_info( message_id="PropertyValueNotInList", message_args=["VALUE", "PROPERTY"], related_properties=["PROPERTY"]) error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_400_BAD_REQUEST, mimetype='application/json') @self.app.errorhandler(status.HTTP_404_NOT_FOUND) def not_found(error): """Creates a Not Found Error response""" redfish_error = RedfishError( "GeneralError", error.description) error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_404_NOT_FOUND, mimetype='application/json') # creates a test client self.app = self.app.test_client() # propagate the exceptions to the test client self.app.testing = True
def test_create_certs(self, oneview_client_mockup): # Test generate_certificate function util.load_config(self.config_file) util.generate_certificate("certs", "test", 2048) self.assertTrue(os.path.exists(os.path.join("certs", "test" + ".crt"))) self.assertTrue(os.path.exists(os.path.join("certs", "test" + ".key")))
def test_create_certs(self, check_ov_availability): # Test generate_certificate function util.load_config(self.config_file) util.generate_certificate("certs", "test", 2048) self.assertTrue(os.path.exists(os.path.join("certs", "test" + ".crt"))) self.assertTrue(os.path.exists(os.path.join("certs", "test" + ".key")))
def setUp(self, oneview_client_mockup): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') self.schemas = collections.OrderedDict() self.schemas["ComputerSystemCollection"] = \ "ComputerSystemCollection.json" self.schemas["ComputerSystem"] = "ComputerSystem.v1_4_0.json"
def setUp(self, mock_ov): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading EventService result mockup with open('oneview_redfish_toolkit/mockups/redfish/' 'EventService.json') as f: self.event_service_mockup = json.load(f)
def setUp(self, mock_ov): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading Subscription result mockup with open('oneview_redfish_toolkit/mockups/redfish/' 'Subscription.json') as f: self.subscription_mockup = json.load(f)
def test_load_config(self, check_ov_availability): # Test load config function util.load_config(self.config_file) # After running loadconfig all variable should be set self.assertIsNotNone(util.config, msg='Failed do load ini') self.assertIsNotNone(util.ov_config, msg='Failed do create ov_config') self.assertIsNotNone(util.registry_dict, msg='Failed to load registries') self.assertTrue(check_ov_availability.called)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading StorageCollection mockup result with open( 'oneview_redfish_toolkit/mockups/redfish/StorageCollection.json' ) as f: self.storage_collection_mockup = json.load(f)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading CompositionService mockup result with open( 'oneview_redfish_toolkit/mockups/redfish/CompositionService.json' ) as f: self.composition_service_mockup = json.load(f)
def test_load_config(self, mock_ov): # Test load config function util.load_config(self.config_file) # After running loadconfig all variable should be set self.assertIsNotNone(util.config, msg='Failed do load ini') self.assertIsNotNone(util.ov_config, msg='Failed do create ov_config') self.assertIsNotNone(util.registry_dict, msg='Failed to load registries') self.assertIsNotNone(util.ov_client, msg='Failed to connect to OV')
def setUp(self, oneview_client_mockup): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading rack mockup value with open('oneview_redfish_toolkit/mockups/oneview/Rack.json') as f: self.rack = json.load(f) # Loading rack_chassis_mockup mockup result with open('oneview_redfish_toolkit/mockups/redfish/RackChassis.json' ) as f: self.rack_chassis_mockup = json.load(f)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading Storage mockup result with open('oneview_redfish_toolkit/mockups/redfish/Storage.json') as f: self.storage_mockup = json.load(f) # Loading ServerHardwareTypes mockup value with open( 'oneview_redfish_toolkit/mockups/oneview/ServerHardwareTypes.json' ) as f: self.server_hardware_types = json.load(f)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading ServerHardware mockup with open('oneview_redfish_toolkit/mockups/oneview/' 'ServerHardware.json') as f: self.server_hardware = json.load(f) # Loading NetworkInterfaceCollection mockup result with open('oneview_redfish_toolkit/mockups/redfish/' 'NetworkInterfaceCollection.json') as f: self.network_interface_collection_mockup = json.load(f)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading ServerHardware list mockup value with open('oneview_redfish_toolkit/mockups/oneview/' 'ServerHardwares.json') as f: self.server_hardware_list = json.load(f) # Loading ComputerSystemCollection result mockup with open('oneview_redfish_toolkit/mockups/redfish/' 'ComputerSystemCollection.json') as f: self.computer_system_collection_mockup = json.load(f)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading server_hardware mockup value with open('oneview_redfish_toolkit/mockups/oneview/ServerHardware.json' ) as f: self.server_hardware = json.load(f) # Loading BladeManager mockup result with open('oneview_redfish_toolkit/mockups/redfish/BladeManager.json' ) as f: self.blade_manager_mockup = json.load(f)
def test_submit_event_without_subscriber(self, start_mock, subscription_mock, check_ov_availability): """Tests SubmitTestEvent action with no subscribers""" util.load_config(self.config_file) with open('oneview_redfish_toolkit/mockups/oneview/Alert.json') as f: event_mockup = Event(json.loads(f.read())) subscription_mock['Alert'].values.return_value = [] util.dispatch_event(event_mockup) self.assertFalse(start_mock.called)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading configuration in util module util.load_config('redfish.conf') # Loading Alert mockup value with open( 'oneview_redfish_toolkit/mockups/oneview/Alert.json' ) as f: self.alert = json.load(f) # Loading Event mockup result with open( 'oneview_redfish_toolkit/mockups/redfish/Alert.json' ) as f: self.event_mockup = json.load(f)
def test_submit_event_with_subscriber(self, start_mock, subscription_mock, check_ov_availability): """Tests SubmitTestEvent action with two subscribers""" util.load_config(self.config_file) with open('oneview_redfish_toolkit/mockups/oneview/Alert.json') as f: event_mockup = Event(json.loads(f.read())) subscription_mock['Alert'].values.return_value = [ Subscription('1', 'destination1', [], 'context1'), Subscription('2', 'destination2', [], 'context2') ] util.dispatch_event(event_mockup) self.assertTrue(start_mock.call_count == 2)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading ServerHardware mockup with open('oneview_redfish_toolkit/mockups/oneview/' 'ServerHardware.json') as f: self.server_hardware = json.load(f) # Loading NetworkDeviceFunction mockup result with open('oneview_redfish_toolkit/mockups/redfish/' 'NetworkDeviceFunction1_1_a.json') as f: self.network_device_function_mockup = json.load(f) self.device_id = "3" self.device_function_id = "1_1_a"
def setUp(self, oneview_client_mockup): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading enclosure mockup value with open( 'oneview_redfish_toolkit/mockups/oneview/Enclosure.json') as f: self.enclosure = json.load(f) # Loading enclosure_manager_mockup result with open( 'oneview_redfish_toolkit/mockups/redfish/EnclosureManager.json' ) as f: self.enclosure_manager_mockup = json.load(f) self.oneview_version = "3.00.07-0288219"
def setUp(self, oneview_client_mockup): """Tests preparation""" # Load config on util util.load_config('redfish.conf') # creates a test client self.app = Flask(__name__) self.app.register_blueprint( computer_system_collection.computer_system_collection) @self.app.errorhandler(status.HTTP_500_INTERNAL_SERVER_ERROR) def internal_server_error(error): """General InternalServerError handler for the app""" redfish_error = RedfishError( "InternalError", "The request failed due to an internal service error. " "The service is still operational.") redfish_error.add_extended_info("InternalError") error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_500_INTERNAL_SERVER_ERROR, mimetype="application/json") @self.app.errorhandler(status.HTTP_404_NOT_FOUND) def not_found(error): """Creates a Not Found Error response""" redfish_error = RedfishError( "GeneralError", error.description) error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_404_NOT_FOUND, mimetype='application/json') self.app = self.app.test_client() # propagate the exceptions to the test client self.app.testing = True
def setUp(self, mock_ov): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading server_hardware mockup value with open('oneview_redfish_toolkit/mockups/oneview/' 'ServerHardwares.json') as f: self.server_hardware = json.load(f) # Loading enclosures mockup value with open('oneview_redfish_toolkit/mockups/oneview/' 'Enclosures.json') as f: self.enclosures = json.load(f) # Loading ManagerCollection result mockup with open('oneview_redfish_toolkit/mockups/redfish/' 'ManagerCollection.json') as f: self.manager_collection_mockup = json.load(f)
def setUp(self, oneview_client_mock): """Tests preparation""" # Loading variable in util module util.load_config('redfish.conf') # Loading enclosure mockup value with open( 'oneview_redfish_toolkit/mockups/oneview/Enclosure.json') as f: self.enclosure = json.load(f) # Loading environment_config mockup value with open('oneview_redfish_toolkit/mockups/oneview/' 'EnclosureEnvironmentalConfig.json') as f: self.environment_config = json.load(f) # Loading enclosure_mockup mockup result with open( 'oneview_redfish_toolkit/mockups/redfish/EnclosureChassis.json' ) as f: self.enclosure_mockup = json.load(f)
def main(config_file_path, logging_config_file_path): # Load config file, schemas and creates a OV connection try: util.configure_logging(logging_config_file_path) util.load_config(config_file_path) except Exception as e: logging.exception('Failed to load app configuration') logging.exception(e) exit(1) # Check auth mode auth_mode = util.config.get('redfish', 'authentication_mode') if auth_mode not in ["conf", "session"]: logging.error( "Invalid authentication_mode. Please check your conf" " file. Valid values are 'conf' or 'session'") # Flask application app = Flask(__name__) # Register blueprints app.register_blueprint(redfish_base, url_prefix="/redfish/") app.register_blueprint(service_root, url_prefix='/redfish/v1/') app.register_blueprint(chassis_collection) app.register_blueprint(computer_system_collection) app.register_blueprint(computer_system) app.register_blueprint(composition_service) app.register_blueprint(chassis) app.register_blueprint(manager_collection) app.register_blueprint(manager) app.register_blueprint(metadata) app.register_blueprint(odata) app.register_blueprint(storage) app.register_blueprint(thermal) app.register_blueprint(storage_collection) app.register_blueprint(network_adapter_collection) app.register_blueprint(network_interface_collection) app.register_blueprint(network_port_collection) app.register_blueprint(network_device_function_collection) app.register_blueprint(network_device_function) app.register_blueprint(network_interface) app.register_blueprint(network_adapter) app.register_blueprint(network_port) app.register_blueprint(session) app.register_blueprint(storage_composition_details) app.register_blueprint(resource_block_collection) app.register_blueprint(resource_block) app.register_blueprint(zone_collection) app.register_blueprint(zone) if auth_mode == "conf": app.register_blueprint(event_service) app.register_blueprint(subscription_collection) app.register_blueprint(subscription) @app.before_request def check_authentication(): """Checks authentication before serving the request""" # If authentication_mode = conf don't need auth auth_mode = util.config["redfish"]["authentication_mode"] if auth_mode == "conf": g.oneview_client = util.get_oneview_client() return None else: # ServiceRoot don't need auth if request.path.rstrip("/") in {"/redfish/v1", "/redfish", "/redfish/v1/odata", "/redfish/v1/$metadata"}: g.oneview_client = util.get_oneview_client(None, True) return None # If authenticating we do nothing if request.path == "/redfish/v1/SessionService/Sessions" and \ request.method == "POST": return None # Any other path we demand auth x_auth_token = request.headers.get('x-auth-token') if not x_auth_token: abort( status.HTTP_401_UNAUTHORIZED, "x-auth-token header not found") else: try: oneview_client = util.get_oneview_client(x_auth_token) g.oneview_client = oneview_client except Exception: abort(status.HTTP_401_UNAUTHORIZED, "invalid auth token") @app.before_request def has_odata_version_header(): """Deny request that specify a different OData-Version than 4.0""" odata_version_header = request.headers.get("OData-Version") if odata_version_header is None: pass elif odata_version_header != "4.0": abort(status.HTTP_412_PRECONDITION_FAILED, "The request specify a different OData-Version " "header then 4.0. This server also responds " "to requests without the OData-Version header") @app.after_request def set_odata_version_header(response): """Set OData-Version header for all responses""" response.headers["OData-Version"] = "4.0" return response @app.errorhandler(status.HTTP_400_BAD_REQUEST) def bad_request(error): """Creates a Bad Request Error response""" redfish_error = RedfishError( "PropertyValueNotInList", error.description) redfish_error.add_extended_info( message_id="PropertyValueNotInList", message_args=["VALUE", "PROPERTY"], related_properties=["PROPERTY"]) error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_400_BAD_REQUEST, mimetype='application/json') @app.errorhandler(status.HTTP_401_UNAUTHORIZED) def unauthorized_error(error): """Creates a Unauthorized Error response""" redfish_error = RedfishError( "GeneralError", error.description) error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_401_UNAUTHORIZED, mimetype='application/json') @app.errorhandler(status.HTTP_404_NOT_FOUND) def not_found(error): """Creates a Not Found Error response""" return ResponseBuilder.error_404(error) @app.errorhandler(status.HTTP_500_INTERNAL_SERVER_ERROR) def internal_server_error(error): """Creates an Internal Server Error response""" return ResponseBuilder.error_500(error) @app.errorhandler(status.HTTP_501_NOT_IMPLEMENTED) def not_implemented(error): """Creates a Not Implemented Error response""" redfish_error = RedfishError( "ActionNotSupported", error.description) redfish_error.add_extended_info( message_id="ActionNotSupported", message_args=["action"]) error_str = redfish_error.serialize() return Response( response=error_str, status=status.HTTP_501_NOT_IMPLEMENTED, mimetype='application/json') @app.errorhandler(HPOneViewException) def hp_oneview_client_exception(exception): return ResponseBuilder.error_by_hp_oneview_exception(exception) if util.config['redfish']['authentication_mode'] == 'conf': # Loading scmb connection if scmb.check_cert_exist(): logging.info('SCMB certs already exists testing connection...') else: logging.info('SCMB certs not found. Generating/getting certs....') scmb.get_cert() logging.info('Got certs. Testing connection...') if not scmb.is_cert_working_with_scmb(): logging.error('Failed to connect to scmb. Aborting...') exit(1) scmb_thread = Thread(target=scmb.listen_scmb) scmb_thread.daemon = True scmb_thread.start() else: logging.warning("Authentication mode set to session. SCMB events will " "be disabled") config = util.config try: host = config["redfish"]["redfish_host"] # Gets the correct IP type based on the string ipaddress.ip_address(host) except ValueError: logging.error("Informed IP is not valid. Check the " "variable 'redfish_host' on your config file.") exit(1) try: port = int(config["redfish"]["redfish_port"]) except Exception: logging.exception( "Port must be an integer number between 1 and 65536.") exit(1) # Checking port range if port < 1 or port > 65536: logging.error("Port must be an integer number between 1 and 65536.") exit(1) if config["ssl"]["SSLType"] in ("self-signed", "adhoc"): logging.warning("Server is starting with a self-signed certificate.") if config["ssl"]["SSLType"] == "disabled": logging.warning( "Server is starting in HTTP mode. This is an insecure mode. " "Running the server with HTTPS enabled is highly recommended.") ssl_type = config["ssl"]["SSLType"] # Check SSLType: if ssl_type not in ('disabled', 'adhoc', 'certs', 'self-signed'): logging.error( "Invalid SSL type: {}. Must be one of: disabled, adhoc, " "self-signed or certs". format(ssl_type)) exit(1) try: debug = config["redfish"]["debug"] if debug not in ('false', 'true'): logging.warning( "Debug option must be either \'true\' or \'false\'. " "Defaulting to \'false\'.") debug = False else: debug = (debug == "true") except Exception: logging.warning( "Invalid debug configuration. " "Defaulting to \'false\'.") debug = False if ssl_type == 'disabled': app.run(host=host, port=port, debug=debug) elif ssl_type == 'adhoc': app.run(host=host, port=port, debug=debug, ssl_context="adhoc") else: # We should use certs file provided by the user ssl_cert_file = config["ssl"]["SSLCertFile"] ssl_key_file = config["ssl"]["SSLKeyFile"] # Generating cert files if they don't exists if ssl_type == "self-signed": if not os.path.exists(ssl_cert_file) and not \ os.path.exists(ssl_key_file): logging.warning("Generating self-signed certs") # Generate certificates util.generate_certificate( os.path.dirname(ssl_cert_file), "self-signed", 2048) else: logging.warning("Using existing self-signed certs") if ssl_cert_file == "" or ssl_key_file == "": logging.error( "SSL type: is 'cert' but one of the files are missing on" "the config file. SSLCertFile: {}, SSLKeyFile: {}.". format(ssl_cert_file, ssl_key_file)) ssl_context = (ssl_cert_file, ssl_key_file) app.run(host=host, port=port, debug=debug, ssl_context=ssl_context)
def setUp(self, check_ov_availability): self.config_file = './redfish.conf' util.load_config(self.config_file)
def setUp(self, oneview_client_mockup): """Tests preparation """ # Load configuration on util module util.load_config('redfish.conf')
def test_load_event_service_invalid_info(self, check_ov_availability): self.assertRaises(OneViewRedfishError, util.load_config(self.config_file))