def test_cisco_api_enabled(self):
        # create new AppSettings object and create defaults
        settings = AppSettings()

        assert settings.is_cisco_api_enabled() is False

        settings.set_cisco_api_enabled(True)
        assert settings.is_cisco_api_enabled() is True

        settings.set_cisco_api_enabled(False)
        assert settings.is_cisco_api_enabled() is False
    def test_cisco_api_enabled(self):
        # create new AppSettings object and create defaults
        settings = AppSettings()

        assert settings.is_cisco_api_enabled() is False

        settings.set_cisco_api_enabled(True)
        assert settings.is_cisco_api_enabled() is True

        settings.set_cisco_api_enabled(False)
        assert settings.is_cisco_api_enabled() is False
Exemplo n.º 3
0
    def handle(self, *args, **kwargs):
        app_settings = AppSettings()

        if not app_settings.is_cisco_api_enabled():
            raise CommandError(
                "Please configure the Cisco EoX API in the settings prior running this task"
            )

        # check if task is already running, if so print status and continue
        task_id = cache.get("CISCO_EOX_INITIAL_SYN_IN_PROGRESS", None)

        if task_id is None:
            # start initial import
            eta = now() + timedelta(seconds=3)
            task = tasks.initial_sync_with_cisco_eox_api.apply_async(
                eta=eta, args=(kwargs["years"], ))

            cache.set("CISCO_EOX_INITIAL_SYN_IN_PROGRESS", task.id,
                      60 * 60 * 48)
            cache.set("CISCO_EOX_INITIAL_SYN_LAST_RUN", task.id, 60 * 60 * 48)

            self.stdout.write("Task successful started...")

        else:
            msg = get_task_state_message(task_id)
            raise CommandError("initial import already running... \n%s" % msg)
Exemplo n.º 4
0
def get_raw_api_data(api_query):
    """
    returns all EoX records for a specific query (from all pages)
    :param api_query: single query that is send to the Cisco EoX API
    :raises CiscoApiCallFailed: exception raised if Cisco EoX API call failed
    :return: list that contains all EoX records from the Cisco EoX API
    """
    if type(api_query) is not str:
        raise ValueError("api_query must be a string value")

    # load application settings and check, that the API is enabled
    app_settings = AppSettings()

    if not app_settings.is_cisco_api_enabled():
        msg = "Cisco API access not enabled"
        logger.warning(msg)
        raise CiscoApiCallFailed(msg)

    # start Cisco EoX API query
    logger.info("send query to Cisco EoX database: %s" % api_query)

    eoxapi = CiscoEoxApi()
    eoxapi.load_client_credentials()
    results = []

    try:
        current_page = 1
        result_pages = 999

        while current_page <= result_pages:
            if current_page == 1:
                logger.info("Executing API query '%s' on first page" % api_query)

            else:
                logger.info("Executing API query '%s' on page '%d" % (api_query, current_page))

            # will raise a CiscoApiCallFailed exception on error
            eoxapi.query_product(product_id=api_query, page=current_page)
            result_pages = eoxapi.amount_of_pages()

            if eoxapi.get_page_record_count() > 0:
                results.extend(eoxapi.get_eox_records())

            current_page += 1

    except ConnectionFailedException:
        logger.error("Query failed, server not reachable: %s" % api_query, exc_info=True)
        raise

    except CiscoApiCallFailed:
        logger.fatal("Query failed: %s" % api_query, exc_info=True)
        raise

    return results
Exemplo n.º 5
0
def status(request):
    """
    Status page for the Product Database
    """
    app_config = AppSettings()

    is_cisco_api_enabled = app_config.is_cisco_api_enabled()
    context = {
        "is_cisco_api_enabled": is_cisco_api_enabled
    }

    if is_cisco_api_enabled:
        # test access (once every 30 minutes)
        cisco_eox_api_test_successful = cache.get("CISCO_EOX_API_TEST", False)

        # defaults, overwritten if an exception is thrown
        cisco_eox_api_available = True
        cisco_eox_api_message = "successful connected to the Cisco EoX API"

        if not cisco_eox_api_test_successful:
            try:
                result = utils.check_cisco_eox_api_access(client_id=app_config.get_cisco_api_client_id(),
                                                          client_secret=app_config.get_cisco_api_client_secret(),
                                                          drop_credentials=False)
                cache.set("CISCO_EOX_API_TEST", result, 60 * 30)

            except Exception as ex:
                cisco_eox_api_available = True
                cisco_eox_api_message = str(ex)

        context["cisco_eox_api_available"] = cisco_eox_api_available
        context["cisco_eox_api_message"] = cisco_eox_api_message

    # determine worker status
    state = celery.is_worker_active()

    if state and not settings.DEBUG:
        worker_status = """
            <div class="alert alert-success" role="alert">
                <span class="fa fa-info-circle"></span>
                Backend worker found.
            </div>"""

    else:
        worker_status = """
            <div class="alert alert-danger" role="alert">
                <span class="fa fa-exclamation-circle"></span>
                No backend worker found, asynchronous and scheduled tasks are not executed.
            </div>"""

    context['worker_status'] = mark_safe(worker_status)

    return render(request, "config/status.html", context=context)
Exemplo n.º 6
0
def cisco_eox_query(request):
    """Manual query page against the Cisco EoX Version 5 API (if enabled)

    :param request:
    :return:
    """
    app_config = AppSettings()
    cisco_api_enabled = app_config.is_cisco_api_enabled()

    context = {
        "is_cisco_api_enabled": cisco_api_enabled
    }

    if request.method == "POST":
        # create a form instance and populate it with data from the request:
        if "sync_cisco_eox_states_now" in request.POST.keys():
            if "sync_cisco_eox_states_query" in request.POST.keys():
                query = request.POST['sync_cisco_eox_states_query']

                if query != "":
                    if len(query.split(" ")) == 1:
                        context['query_executed'] = query
                        try:
                            eox_api_update_records = api_crawler.update_cisco_eox_database(api_query=query)

                        except ConnectionFailedException as ex:
                            eox_api_update_records = {"error": "Cannot contact Cisco API, error message:\n%s" % ex}

                        except CiscoApiCallFailed as ex:
                            eox_api_update_records = {"error": "Cisco API call failed: %s" % ex}

                        except Exception as ex:  # catch any exception
                            logger.debug("execution failed due to unexpected exception", exc_info=True)
                            eox_api_update_records = ["execution failed: %s" % ex]

                        context['eox_api_update_records'] = json.dumps(eox_api_update_records, indent=4, sort_keys=True)

                    else:
                        context['eox_api_update_records'] = "Invalid query '%s': not executed" % \
                                                            request.POST['sync_cisco_eox_states_query']
                else:
                    context['eox_api_update_records'] = ["Please specify a valid query"]

            else:
                context['eox_api_update_records'] = "Query not specified."

        else:
            context['eox_api_update_records'] = "Query not executed, please select the \"execute it now\" checkbox."

    return render(request, "ciscoeox/cisco_eox_query.html", context=context)
Exemplo n.º 7
0
def status(request):
    """
    Status page for the Product Database
    """
    app_config = AppSettings()

    is_cisco_api_enabled = app_config.is_cisco_api_enabled()
    context = {"is_cisco_api_enabled": is_cisco_api_enabled}

    if is_cisco_api_enabled:
        # test access (once every 30 minutes)
        cisco_eox_api_test_successful = cache.get("CISCO_EOX_API_TEST", False)

        # defaults, overwritten if an exception is thrown
        cisco_eox_api_available = True
        cisco_eox_api_message = "successful connected to the Cisco EoX API"

        if not cisco_eox_api_test_successful:
            try:
                result = utils.check_cisco_eox_api_access(
                    client_id=app_config.get_cisco_api_client_id(),
                    client_secret=app_config.get_cisco_api_client_secret(),
                    drop_credentials=False)
                cache.set("CISCO_EOX_API_TEST", result, 60 * 30)

            except Exception as ex:
                cisco_eox_api_available = True
                cisco_eox_api_message = str(ex)

        context["cisco_eox_api_available"] = cisco_eox_api_available
        context["cisco_eox_api_message"] = cisco_eox_api_message

    # determine worker status
    context['worker_status'] = mark_safe(utils.get_celery_worker_state_html())

    return render(request, "config/status.html", context=context)
Exemplo n.º 8
0
def change_configuration(request):
    """
    change configuration of the Product Database
    """
    # read settings from configuration file
    app_config = AppSettings()

    # read settings from database
    hp_content_after, _ = TextBlock.objects.get_or_create(
        name=TextBlock.TB_HOMEPAGE_TEXT_AFTER_FAVORITE_ACTIONS
    )
    hp_content_before, _ = TextBlock.objects.get_or_create(
        name=TextBlock.TB_HOMEPAGE_TEXT_BEFORE_FAVORITE_ACTIONS
    )

    if request.method == "POST":
        # create a form instance and populate it with data from the request:
        form = SettingsForm(request.POST)
        if form.is_valid():
            # set common settings
            app_config.set_login_only_mode(form.cleaned_data["login_only_mode"])

            hp_content_before.html_content = form.cleaned_data["homepage_text_before"]
            hp_content_before.save()
            hp_content_after.html_content = form.cleaned_data["homepage_text_after"]
            hp_content_after.save()

            # set the Cisco API configuration options
            api_enabled = form.cleaned_data["cisco_api_enabled"]

            if not api_enabled:
                # api is disabled, reset values to default
                app_config.set_cisco_api_enabled(api_enabled)
                app_config.set_cisco_api_client_id("PlsChgMe")
                app_config.set_cisco_api_client_secret("PlsChgMe")
                app_config.set_periodic_sync_enabled(False)
                app_config.set_auto_create_new_products(False)
                app_config.set_cisco_eox_api_queries("")
                app_config.set_product_blacklist_regex("")
                app_config.set_cisco_eox_api_sync_wait_time("5")

            else:
                app_config.set_cisco_api_enabled(api_enabled)

                client_id = form.cleaned_data["cisco_api_client_id"] \
                    if form.cleaned_data["cisco_api_client_id"] != "" else "PlsChgMe"
                app_config.set_cisco_api_client_id(client_id)
                client_secret = form.cleaned_data["cisco_api_client_secret"] \
                    if form.cleaned_data["cisco_api_client_secret"] != "" else "PlsChgMe"
                app_config.set_cisco_api_client_secret(client_secret)

                app_config.set_internal_product_id_label(form.cleaned_data["internal_product_id_label"])
                app_config.set_periodic_sync_enabled(form.cleaned_data["eox_api_auto_sync_enabled"])
                app_config.set_auto_create_new_products(form.cleaned_data["eox_auto_sync_auto_create_elements"])
                app_config.set_cisco_eox_api_queries(form.cleaned_data["eox_api_queries"])
                app_config.set_product_blacklist_regex(form.cleaned_data["eox_api_blacklist"])
                if form.cleaned_data["eox_api_wait_time"]:
                    app_config.set_cisco_eox_api_sync_wait_time(form.cleaned_data["eox_api_wait_time"])

                if client_id != "PlsChgMe":
                    result = utils.check_cisco_eox_api_access(
                        form.cleaned_data["cisco_api_client_id"],
                        form.cleaned_data["cisco_api_client_secret"]
                    )

                    if result:
                        messages.success(request, "Successfully connected to the Cisco EoX API")

                    else:
                        messages.error(request, "Cannot contact the Cisco EoX API. Please contact your "
                                                "Administrator")

                else:
                    messages.info(
                        request,
                        "Please configure your Cisco API credentials within the Cisco API settings tab."
                    )

            # expire cached settings
            cache.delete("LOGIN_ONLY_MODE_SETTING")

            messages.success(request, "Settings saved successfully")
            return redirect(resolve_url("productdb_config:change_settings"))

        else:
            messages.error(request, "Invalid configuration option detected, please check it below.")

    else:
        form = SettingsForm()
        form.fields['cisco_api_enabled'].initial = app_config.is_cisco_api_enabled()
        form.fields['login_only_mode'].initial = app_config.is_login_only_mode()
        form.fields['internal_product_id_label'].initial = app_config.get_internal_product_id_label()
        form.fields['cisco_api_client_id'].initial = app_config.get_cisco_api_client_id()
        form.fields['cisco_api_client_secret'].initial = app_config.get_cisco_api_client_secret()
        form.fields['eox_api_auto_sync_enabled'].initial = app_config.is_periodic_sync_enabled()
        form.fields['eox_auto_sync_auto_create_elements'].initial = app_config.is_auto_create_new_products()
        form.fields['eox_api_queries'].initial = app_config.get_cisco_eox_api_queries()
        form.fields['eox_api_blacklist'].initial = app_config.get_product_blacklist_regex()
        form.fields['eox_api_wait_time'].initial = app_config.get_cisco_eox_api_sync_wait_time()
        form.fields['homepage_text_before'].initial = hp_content_before.html_content
        form.fields['homepage_text_after'].initial = hp_content_after.html_content

    context = {
        "form": form,
        "is_cisco_api_enabled": app_config.is_cisco_api_enabled(),
        "is_cisco_eox_api_auto_sync_enabled": app_config.is_periodic_sync_enabled()
    }
    return render(request, "config/change_configuration.html", context=context)
Exemplo n.º 9
0
def update_cisco_eox_database(api_query):
    """
    synchronizes the local database with the Cisco EoX API using the specified query
    :param api_query: single query that is send to the Cisco EoX API
    :raises CiscoApiCallFailed: exception raised if Cisco EoX API call failed
    :return: list of dictionary that describe the updates to the database
    """
    if type(api_query) is not str:
        raise ValueError("api_query must be a string value")

    # load application settings and check, that the API is enabled
    app_settings = AppSettings()

    if not app_settings.is_cisco_api_enabled():
        msg = "Cisco API access not enabled"
        logger.warn(msg)
        raise CiscoApiCallFailed(msg)

    blacklist_raw_string = app_settings.get_product_blacklist_regex()
    create_missing = app_settings.is_auto_create_new_products()

    # clean blacklist string and remove empty statements
    # (split lines, if any and split the string by semicolon)
    blacklist = []
    for e in [e.split(";") for e in blacklist_raw_string.splitlines()]:
        blacklist += e
    blacklist = [e for e in blacklist if e != ""]

    # start Cisco EoX API query
    logger.info("Query EoX database: %s" % api_query)

    eoxapi = CiscoEoxApi()
    eoxapi.load_client_credentials()
    results = []

    try:
        max_pages = 999
        current_page = 1
        result_pages = 0

        while current_page <= max_pages:
            logger.info("Executing API query '%s' on page '%d" % (api_query, current_page))
            # will raise a CiscoApiCallFailed exception on error
            eoxapi.query_product(product_id=api_query, page=current_page)
            if current_page == 1:
                result_pages = eoxapi.amount_of_pages()
                logger.info("Initial query returns %d page(s)" % result_pages)

            records = eoxapi.get_eox_records()

            # check that the query has valid results
            if eoxapi.get_page_record_count() > 0:
                # processing records
                for record in records:
                    result_record = {}
                    pid = record["EOLProductID"]
                    result_record["PID"] = pid
                    result_record["created"] = False
                    result_record["updated"] = False
                    result_record["message"] = None
                    logger.info("processing product '%s'..." % pid)

                    pid_in_database = product_id_in_database(pid)

                    # check if the product ID is blacklisted by a regular expression
                    pid_blacklisted = False
                    for regex in blacklist:
                        try:
                            if re.search(regex, pid, re.I):
                                pid_blacklisted = True
                                break
                        except:
                            # silently ignore the issue, invalid regular expressions are handled by the settings form
                            logger.info("invalid regular expression: %s" % regex)

                    # ignore if the product id is not in the database
                    if pid_blacklisted and not pid_in_database:
                        logger.info("Product '%s' blacklisted... no further processing" % pid)
                        result_record.update({"blacklist": True})

                    else:
                        res = {}
                        try:
                            res = update_local_db_based_on_record(record, create_missing)

                        except ValidationError:
                            logger.error(
                                "invalid data received from Cisco API, cannot save data object for '%s'" % pid,
                                exc_info=True,
                            )
                            result_record["message"] = "invalid data received from Cisco EoX API, import incomplete"

                        finally:
                            res["blacklist"] = False
                            result_record.update(res)

                    results.append(result_record)

            if current_page == result_pages:
                break

            else:
                current_page += 1

        # filter empty result strings
        if len(results) == 0:
            results = [
                {
                    "PID": None,
                    "blacklist": False,
                    "updated": False,
                    "created": False,
                    "message": "No product update required",
                }
            ]

    except ConnectionFailedException:
        logger.error("Query failed, server not reachable: %s" % api_query, exc_info=True)
        raise

    except CiscoApiCallFailed:
        logger.fatal("Query failed: %s" % api_query, exc_info=True)
        raise

    return results
Exemplo n.º 10
0
def get_raw_api_data(api_query=None, year=None):
    """
    returns all EoX records for a specific query (from all pages)
    :param api_query: single query that is send to the Cisco EoX API
    :param year: get all EoX data that are announced in a specific year
    :raises CiscoApiCallFailed: exception raised if Cisco EoX API call failed
    :return: list that contains all EoX records from the Cisco EoX API
    """
    if api_query is None and year is None:
        raise ValueError("either year or the api_query must be provided")

    if api_query:
        if type(api_query) is not str:
            raise ValueError("api_query must be a string value")

    if year:
        if type(year) is not int:
            raise ValueError("year must be an integer value")

    # load application settings and check, that the API is enabled
    app_settings = AppSettings()

    if not app_settings.is_cisco_api_enabled():
        msg = "Cisco API access not enabled"
        logger.warning(msg)
        raise CiscoApiCallFailed(msg)

    # start Cisco EoX API query
    logger.info("send query to Cisco EoX database: %s" % api_query)

    eoxapi = CiscoEoxApi()
    eoxapi.load_client_credentials()
    results = []

    try:
        current_page = 1
        result_pages = 999

        while current_page <= result_pages:
            logger.info("Executing API query %s on page '%d" % ('%s' % api_query if api_query else "for year %d" % year, current_page))

            # will raise a CiscoApiCallFailed exception on error
            if year:
                eoxapi.query_year(year_to_query=year, page=current_page)

            else:
                eoxapi.query_product(product_id=api_query, page=current_page)

            result_pages = eoxapi.amount_of_pages()

            if eoxapi.get_page_record_count() > 0:
                results.extend(eoxapi.get_eox_records())

            current_page += 1

    except ConnectionFailedException:
        logger.error("Query failed, server not reachable: %s" % api_query, exc_info=True)
        raise

    except CiscoApiCallFailed:
        logger.fatal("Query failed: %s" % api_query, exc_info=True)
        raise

    logger.debug("found %d records for year %s" % (len(results), year))

    return results
Exemplo n.º 11
0
def cisco_eox_query(request):
    """Manual query page against the Cisco EoX Version 5 API (if enabled)

    :param request:
    :return:
    """
    app_config = AppSettings()
    cisco_api_enabled = app_config.is_cisco_api_enabled()

    context = {"is_cisco_api_enabled": cisco_api_enabled}

    if request.method == "POST":
        # create a form instance and populate it with data from the request:
        if "sync_cisco_eox_states_now" in request.POST.keys():
            if "sync_cisco_eox_states_query" in request.POST.keys():
                query = request.POST['sync_cisco_eox_states_query']

                if query != "":
                    if len(query.split(" ")) == 1:
                        context['query_executed'] = query
                        try:
                            eox_api_update_records = api_crawler.update_cisco_eox_database(
                                api_query=query)

                        except ConnectionFailedException as ex:
                            eox_api_update_records = {
                                "error":
                                "Cannot contact Cisco API, error message:\n%s"
                                % ex
                            }

                        except CiscoApiCallFailed as ex:
                            eox_api_update_records = {
                                "error": "Cisco API call failed: %s" % ex
                            }

                        except Exception as ex:  # catch any exception
                            logger.debug(
                                "execution failed due to unexpected exception",
                                exc_info=True)
                            eox_api_update_records = [
                                "execution failed: %s" % ex
                            ]

                        context['eox_api_update_records'] = json.dumps(
                            eox_api_update_records, indent=4, sort_keys=True)

                    else:
                        context['eox_api_update_records'] = "Invalid query '%s': not executed" % \
                                                            request.POST['sync_cisco_eox_states_query']
                else:
                    context['eox_api_update_records'] = [
                        "Please specify a valid query"
                    ]

            else:
                context['eox_api_update_records'] = "Query not specified."

        else:
            context[
                'eox_api_update_records'] = "Query not executed, please select the \"execute it now\" checkbox."

    return render(request, "ciscoeox/cisco_eox_query.html", context=context)
Exemplo n.º 12
0
def update_cisco_eox_database(api_query):
    """
    synchronizes the local database with the Cisco EoX API using the specified query
    :param api_query: single query that is send to the Cisco EoX API
    :raises CiscoApiCallFailed: exception raised if Cisco EoX API call failed
    :return: list of dictionary that describe the updates to the database
    """
    if type(api_query) is not str:
        raise ValueError("api_query must be a string value")

    # load application settings and check, that the API is enabled
    app_settings = AppSettings()

    if not app_settings.is_cisco_api_enabled():
        msg = "Cisco API access not enabled"
        logger.warn(msg)
        raise CiscoApiCallFailed(msg)

    blacklist_raw_string = app_settings.get_product_blacklist_regex()
    create_missing = app_settings.is_auto_create_new_products()

    # clean blacklist string and remove empty statements
    # (split lines, if any and split the string by semicolon)
    blacklist = []
    for e in [e.split(";") for e in blacklist_raw_string.splitlines()]:
        blacklist += e
    blacklist = [e for e in blacklist if e != ""]

    # start Cisco EoX API query
    logger.info("Query EoX database: %s" % api_query)

    eoxapi = CiscoEoxApi()
    eoxapi.load_client_credentials()
    results = []

    try:
        max_pages = 999
        current_page = 1
        result_pages = 0

        while current_page <= max_pages:
            logger.info("Executing API query '%s' on page '%d" % (api_query, current_page))
            # will raise a CiscoApiCallFailed exception on error
            eoxapi.query_product(product_id=api_query, page=current_page)
            if current_page == 1:
                result_pages = eoxapi.amount_of_pages()
                logger.info("Initial query returns %d page(s)" % result_pages)

            records = eoxapi.get_eox_records()

            # check that the query has valid results
            if eoxapi.get_page_record_count() > 0:
                # processing records
                for record in records:
                    result_record = {}
                    pid = record['EOLProductID']
                    result_record["PID"] = pid
                    result_record["created"] = False
                    result_record["updated"] = False
                    result_record["message"] = None
                    logger.info("processing product '%s'..." % pid)

                    pid_in_database = product_id_in_database(pid)

                    # check if the product ID is blacklisted by a regular expression
                    pid_blacklisted = False
                    for regex in blacklist:
                        try:
                            if re.search(regex, pid, re.I):
                                pid_blacklisted = True
                                break
                        except:
                            # silently ignore the issue, invalid regular expressions are handled by the settings form
                            logger.info("invalid regular expression: %s" % regex)

                    # ignore if the product id is not in the database
                    if pid_blacklisted and not pid_in_database:
                        logger.info("Product '%s' blacklisted... no further processing" % pid)
                        result_record.update({
                            "blacklist": True
                        })

                    else:
                        res = {}
                        try:
                            res = update_local_db_based_on_record(record, create_missing)

                        except ValidationError:
                            logger.error("invalid data received from Cisco API, cannot save data object for '%s'" % pid,
                                         exc_info=True)
                            result_record["message"] = "invalid data received from Cisco EoX API, import incomplete"

                        finally:
                            res["blacklist"] = False
                            result_record.update(res)

                    results.append(result_record)

            if current_page == result_pages:
                break

            else:
                current_page += 1

        # filter empty result strings
        if len(results) == 0:
            results = [
                {
                    "PID": None,
                    "blacklist": False,
                    "updated": False,
                    "created": False,
                    "message": "No product update required"
                }
            ]

    except ConnectionFailedException:
        logger.error("Query failed, server not reachable: %s" % api_query, exc_info=True)
        raise

    except CiscoApiCallFailed:
        logger.fatal("Query failed: %s" % api_query, exc_info=True)
        raise

    return results
Exemplo n.º 13
0
def status(request):
    """
    Status page for the Product Database
    """
    app_config = AppSettings()

    is_cisco_api_enabled = app_config.is_cisco_api_enabled()
    context = {
        "is_cisco_api_enabled": is_cisco_api_enabled
    }

    if is_cisco_api_enabled:
        # test access (once every 30 minutes)
        cisco_eox_api_test_successful = cache.get("CISCO_EOX_API_TEST", False)

        # defaults, overwritten if an exception is thrown
        cisco_eox_api_available = True
        cisco_eox_api_message = "successful connected to the Cisco EoX API"

        if not cisco_eox_api_test_successful:
            try:
                result = utils.check_cisco_eox_api_access(client_id=app_config.get_cisco_api_client_id(),
                                                          client_secret=app_config.get_cisco_api_client_secret(),
                                                          drop_credentials=False)
                cache.set("CISCO_EOX_API_TEST", result, 60 * 30)

            except Exception as ex:
                cisco_eox_api_available = True
                cisco_eox_api_message = str(ex)

        context["cisco_eox_api_available"] = cisco_eox_api_available
        context["cisco_eox_api_message"] = cisco_eox_api_message

    # determine worker status
    ws = WorkerState.objects.all()
    if ws.count() == 0:
        worker_status = """
            <div class="alert alert-danger" role="alert">
                <span class="fa fa-exclamation-circle"></span>
                <span class="sr-only">Error:</span>
                All backend worker offline, asynchronous and scheduled tasks are not executed.
            </div>"""
    else:
        alive_worker = False
        for w in ws:
            if w.is_alive():
                alive_worker = True
                break
        if alive_worker:
            worker_status = """
                <div class="alert alert-success" role="alert">
                    <span class="fa fa-info-circle"></span>
                    <span class="sr-only">Error:</span>
                    Backend worker found.
                </div>"""

        else:
            worker_status = """
                <div class="alert alert-warning" role="alert">
                    <span class="fa fa-exclamation-circle"></span>
                    <span class="sr-only">Error:</span>
                    Only unregistered backend worker found, asynchronous and scheduled tasks are not executed.
                    Please verify the state in the <a href="/productdb/admin">Django Admin</a> page.
                </div>"""

    context['worker_status'] = mark_safe(worker_status)

    return render(request, "config/status.html", context=context)
Exemplo n.º 14
0
def change_configuration(request):
    """
    change configuration of the Product Database
    """
    # read settings from configuration file
    app_config = AppSettings()

    # read settings from database
    hp_content_after, _ = TextBlock.objects.get_or_create(
        name=TextBlock.TB_HOMEPAGE_TEXT_AFTER_FAVORITE_ACTIONS
    )
    hp_content_before, _ = TextBlock.objects.get_or_create(
        name=TextBlock.TB_HOMEPAGE_TEXT_BEFORE_FAVORITE_ACTIONS
    )

    if request.method == "POST":
        # create a form instance and populate it with data from the request:
        form = SettingsForm(request.POST)
        if form.is_valid():
            # set common settings
            app_config.set_login_only_mode(form.cleaned_data["login_only_mode"])

            hp_content_before.html_content = form.cleaned_data["homepage_text_before"]
            hp_content_before.save()
            hp_content_after.html_content = form.cleaned_data["homepage_text_after"]
            hp_content_after.save()

            # set the Cisco API configuration options
            api_enabled = form.cleaned_data["cisco_api_enabled"]

            if not api_enabled:
                # api is disabled, reset values to default
                app_config.set_cisco_api_enabled(api_enabled)
                app_config.set_cisco_api_client_id("PlsChgMe")
                app_config.set_cisco_api_client_secret("PlsChgMe")
                app_config.set_periodic_sync_enabled(False)
                app_config.set_auto_create_new_products(False)
                app_config.set_cisco_eox_api_queries("")
                app_config.set_product_blacklist_regex("")
                app_config.set_cisco_eox_api_sync_wait_time("5")

            else:
                app_config.set_cisco_api_enabled(api_enabled)

                client_id = form.cleaned_data["cisco_api_client_id"] \
                    if form.cleaned_data["cisco_api_client_id"] != "" else "PlsChgMe"
                app_config.set_cisco_api_client_id(client_id)
                client_secret = form.cleaned_data["cisco_api_client_secret"] \
                    if form.cleaned_data["cisco_api_client_secret"] != "" else "PlsChgMe"
                app_config.set_cisco_api_client_secret(client_secret)

                if client_id != "PlsChgMe":
                    result = utils.check_cisco_eox_api_access(
                        form.cleaned_data["cisco_api_client_id"],
                        form.cleaned_data["cisco_api_client_secret"]
                    )

                    if result:
                        messages.success(request, "Successfully connected to the Cisco EoX API")

                    else:
                        messages.error(request, "Cannot contact the Cisco EoX API. Please contact your "
                                                "Administrator")

                else:
                    messages.info(
                        request,
                        "Please configure your Cisco API credentials within the Cisco API settings tab."
                    )

                app_config.set_periodic_sync_enabled(form.cleaned_data["eox_api_auto_sync_enabled"])
                app_config.set_internal_product_id_label(form.cleaned_data["internal_product_id_label"])
                app_config.set_auto_create_new_products(form.cleaned_data["eox_auto_sync_auto_create_elements"])
                app_config.set_cisco_eox_api_queries(form.cleaned_data["eox_api_queries"])
                app_config.set_product_blacklist_regex(form.cleaned_data["eox_api_blacklist"])
                if form.cleaned_data["eox_api_wait_time"]:
                    app_config.set_cisco_eox_api_sync_wait_time(form.cleaned_data["eox_api_wait_time"])

            # expire cached settings
            cache.delete("LOGIN_ONLY_MODE_SETTING")

            messages.success(request, "Settings saved successfully")
            return redirect(resolve_url("productdb_config:change_settings"))

        else:
            messages.error(request, "Invalid configuration option detected, please check it below.")

    else:
        form = SettingsForm()
        form.fields['cisco_api_enabled'].initial = app_config.is_cisco_api_enabled()
        form.fields['login_only_mode'].initial = app_config.is_login_only_mode()
        form.fields['internal_product_id_label'].initial = app_config.get_internal_product_id_label()
        form.fields['cisco_api_client_id'].initial = app_config.get_cisco_api_client_id()
        form.fields['cisco_api_client_secret'].initial = app_config.get_cisco_api_client_secret()
        form.fields['eox_api_auto_sync_enabled'].initial = app_config.is_periodic_sync_enabled()
        form.fields['eox_auto_sync_auto_create_elements'].initial = app_config.is_auto_create_new_products()
        form.fields['eox_api_queries'].initial = app_config.get_cisco_eox_api_queries()
        form.fields['eox_api_blacklist'].initial = app_config.get_product_blacklist_regex()
        form.fields['eox_api_wait_time'].initial = app_config.get_cisco_eox_api_sync_wait_time()
        form.fields['homepage_text_before'].initial = hp_content_before.html_content
        form.fields['homepage_text_after'].initial = hp_content_after.html_content

    context = {
        "form": form,
        "is_cisco_api_enabled": app_config.is_cisco_api_enabled(),
        "is_cisco_eox_api_auto_sync_enabled": app_config.is_periodic_sync_enabled()
    }
    return render(request, "config/change_configuration.html", context=context)