Exemplo n.º 1
0
 def _get_graphs(self, target_components):
     graph = {}
     tc = tuple(target_components or [])
     if tc:
         for c in dr.DELEGATES:
             if dr.get_name(c).startswith(tc):
                 graph.update(dr.get_dependency_graph(c))
     return graph
Exemplo n.º 2
0
def test_spec_factory():
    hn = HostContext()
    broker = dr.Broker()
    broker[HostContext] = hn
    broker = dr.run(dr.get_dependency_graph(dostuff), broker)
    assert dostuff in broker, broker.tracebacks
    assert broker[Stuff.smpl_file].content == file_content
    assert not any(l.endswith("\n") for l in broker[Stuff.smpl_file].content)
 def _get_target_components(self):
     tc = tuple(self.service.get("target_components", []))
     if not tc:
         return
     graph = {}
     for c in dr.DELEGATES:
         if dr.get_name(c).startswith(tc):
             graph.update(dr.get_dependency_graph(c))
     return graph or None
Exemplo n.º 4
0
def test_line_terminators():
    add_filter(Stuff.smpl_file, "def test")
    hn = HostContext()
    broker = dr.Broker()
    broker[HostContext] = hn
    broker = dr.run(dr.get_dependency_graph(dostuff), broker)

    content = broker[Stuff.smpl_file].content
    assert all("def test" in l for l in content), content
    assert not any(l.endswith("\n") for l in content)
Exemplo n.º 5
0
def test_spec_factory():
    add_filter(Stuff.smpl_cmd_list_of_lists, " hello ")
    hn = HostContext()
    broker = dr.Broker()
    broker[HostContext] = hn
    broker = dr.run(dr.get_dependency_graph(dostuff), broker)
    assert dostuff in broker, broker.tracebacks
    assert broker[Stuff.smpl_file].content == file_content
    assert not any(l.endswith("\n") for l in broker[Stuff.smpl_file].content)
    assert "hello" in broker[Stuff.smpl_cmd_list_of_lists].content[0]
    assert len(broker[Stuff.smpl_cmd_list_of_lists].content) == 1
Exemplo n.º 6
0
def test_insights_evaluator():
    broker = dr.Broker()
    e = InsightsEvaluator(broker)
    graph = dr.get_dependency_graph(report)
    result1 = e.process(graph)

    broker = dr.Broker()
    with InsightsEvaluator(broker) as e:
        dr.run(report, broker=broker)
        result2 = e.get_response()
        assert result1 == result2
Exemplo n.º 7
0
def test_insights_evaluator():
    broker = dr.Broker()
    e = InsightsEvaluator(broker)
    graph = dr.get_dependency_graph(report)
    result1 = e.process(graph)

    broker = dr.Broker()
    with InsightsEvaluator(broker) as e:
        dr.run(report, broker=broker)
        result2 = e.get_response()
        assert result1["reports"] == result2["reports"]
        for k in ["start", "finish", "execution_context", "plugin_sets"]:
            assert k in result1["analysis_metadata"]
            assert k in result2["analysis_metadata"]
Exemplo n.º 8
0
    def get_datasources(self, comp, broker):
        """
        Get the most relevant activated datasources for each rule.
        """
        graph = dr.get_dependency_graph(comp)
        ds = []
        for cand in graph:
            if cand in broker and is_datasource(cand):
                val = broker[cand]
                if not isinstance(val, list):
                    val = [val]

                results = []
                for v in val:
                    if isinstance(v, ContentProvider):
                        results.append(v.cmd or v.path
                                       or "python implementation")
                ds.extend(results)
        return ds
Exemplo n.º 9
0
    def make_rule(self, path=None, overwrite=False, pick=None):
        """
        Attempt to generate a rule based on models used so far.

        Args:
            path(str): path to store the rule.
            overwrite (bool): whether to overwrite an existing file.
            pick (str): Optionally specify which lines or line ranges
                to use for the rule body. "1 2 3" gets lines 1,2 and 3.
                "1 3-5 7" gets line 1, lines 3 through 5, and line 7.
        """
        import IPython

        ip = IPython.get_ipython()
        ignore = [
            r"=.*models\.",
            r"^(%|!|help)",
            r"make_rule",
            r"models\.(show|find).*",
            r".*\?$",
            r"^(clear|pwd|cd *.*|ll|ls)$",
        ]

        if pick:
            lines = [r[2] for r in ip.history_manager.get_range_by_str(pick)]
        else:
            lines = []
            for r in ip.history_manager.get_range():
                l = r[2]
                if any(re.search(i, l) for i in ignore):
                    continue
                elif l.startswith("models."):
                    l = l[7:]
                lines.append(l)

        # the user asked for these models during the session.
        requested = sorted(self._requested, key=lambda i: i[0])

        # figure out what we need to import for filtering.
        filterable = defaultdict(list)
        for _, c in requested:
            for d in dr.get_dependency_graph(c):
                try:
                    if isinstance(d, RegistryPoint) and d.filterable:
                        n = d.__qualname__
                        cls = n.split(".")[0]
                        filterable[dr.get_module_name(d)].append((cls, n))
                except:
                    pass

        model_names = [dr.get_simple_name(i[1]) for i in requested]
        var_names = [i[0].lower() for i in requested]

        imports = [
            "from insights import rule, make_fail, make_info, make_pass  # noqa",
            "from insights.parsr.query import *  # noqa",
            "from insights.parsr.query import make_child_query as q  # noqa",
            "",
        ]

        for _, c in requested:
            mod = dr.get_module_name(c)
            name = dr.get_simple_name(c)
            imports.append("from {} import {}".format(mod, name))

        seen = set()
        if filterable:
            imports.append("")

        for k in sorted(filterable):
            for (cls, n) in filterable[k]:
                if (k, cls) not in seen:
                    imports.append("from {} import {}".format(k, cls))
                    seen.add((k, cls))

        seen = set()
        filters = []
        for k in sorted(filterable):
            for i in filterable[k]:
                if i not in seen:
                    filters.append("add_filter({}, ...)".format(i[1]))
                    seen.add(i)

        if filters:
            imports.append("from insights.core.filters import add_filter")

        filter_stanza = os.linesep.join(filters)
        import_stanza = os.linesep.join(imports)
        decorator = "@rule({})".format(", ".join(model_names))
        func_decl = "def report({}):".format(", ".join(var_names))
        body = os.linesep.join(["    " + x
                                for x in lines]) if lines else "    pass"

        res = import_stanza
        if filter_stanza:
            res += (os.linesep * 2) + filter_stanza

        res += (os.linesep *
                3) + decorator + os.linesep + func_decl + os.linesep + body

        if path:
            if not path.startswith("/"):
                realpath = os.path.realpath(path)
                if not realpath.startswith(self._cwd):
                    path = os.path.join(self._cwd, path)

            if os.path.exists(path) and not overwrite:
                print("{} already exists. Use overwrite=True to overwrite.".
                      format(path))
                return

            if not os.path.exists(path) or overwrite:
                with open(path, "w") as f:
                    f.write(res)
                ip.magic("edit -x {}".format(path))
                print("Saved to {}".format(path))
        else:
            IPython.core.page.page(ip.pycolorize(res))
Exemplo n.º 10
0
def _get_deps(rule_func):
    graph = dr.get_dependency_graph(rule_func)
    graph.update(dr.get_dependency_graph(RedHatRelease))

    deps = [c for c in graph if is_type(c, condition) or is_type(c, incident)]
    return graph, deps
def test_type():
    graph = dr.get_dependency_graph(report)
    components = dr._determine_components(needs)
    assert graph == components
def test_group():
    graph = dr.get_dependency_graph(report)
    components = dr._determine_components("needs")
    assert graph == components
def test_list_of_components():
    graph = dr.get_dependency_graph(report)
    components = dr._determine_components([one, two, report])
    assert graph == components
def test_single_component():
    graph = dr.get_dependency_graph(report)
    components = dr._determine_components(report)
    assert graph == components