Created
October 15, 2018 14:44
-
-
Save bfahr/28b4112d628a9e4215ab3bc07b0cadc5 to your computer and use it in GitHub Desktop.
Insights Core sample code showing missing requirements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| This is sample code to show how you can run insights-core from a | |
| stand alone Python script. It also demonstrates missing requirements. | |
| Run from the command line:: | |
| `$ ./stand_alone_missing.py -m` | |
| """ | |
| from __future__ import print_function | |
| from collections import namedtuple | |
| from insights import get_active_lines, parser, Parser | |
| from insights import make_response, rule, run | |
| from insights.core.spec_factory import SpecSet, simple_file | |
| from insights.parsers.redhat_release import RedhatRelease | |
| ERROR_KEY = "TOO_MANY_HOSTS" | |
| CONTENT = { | |
| ERROR_KEY: """Too many hosts in /etc/hosts: {{num}}""" | |
| } | |
| class Specs(SpecSet): | |
| hosts = simple_file("/etc/hosts") | |
| missing_spec = simple_file("/etc/missing_file") | |
| missing_spec_two = simple_file("/etc/missing_file_two") | |
| @parser(Specs.hosts) | |
| class HostParser(Parser): | |
| Host = namedtuple("Host", ["ip", "host", "aliases"]) | |
| def parse_content(self, content): | |
| self.hosts = [] | |
| for line in get_active_lines(content): | |
| # remove inline comments | |
| line = line.partition("#")[0].strip() | |
| # break the line into parts | |
| parts = line.split() | |
| ip, host = parts[:2] | |
| aliases = parts[2:] | |
| self.hosts.append(HostParser.Host(ip, host, aliases)) | |
| def __repr__(self): | |
| me = self.__class__.__name__ | |
| msg = "%s([" + ", ".join([str(d) for d in self.hosts]) + "])" | |
| return msg % me | |
| @parser(Specs.missing_spec) | |
| class MissingParser(object): | |
| def parse_content(self, content): | |
| self.data = len(content) | |
| def __repr__(self): | |
| me = self.__class__.__name__ | |
| msg = "%s({})".format(self.data) | |
| return msg % me | |
| @parser(Specs.missing_spec_two) | |
| class MissingParserTwo(MissingParser): | |
| pass | |
| @rule(HostParser, RedhatRelease) | |
| def report(hp, rhr): | |
| if len(hp.hosts) > 1: | |
| return make_response(ERROR_KEY, num=len(hp.hosts)) | |
| @rule(MissingParser) | |
| def report_missing(missing): | |
| if missing > 0: | |
| return make_response("FOUND_MISSING", length=missing) | |
| @rule(MissingParserTwo) | |
| def report_missing_two(missing): | |
| if missing > 0: | |
| return make_response("FOUND_MISSING_TWO", length=missing) | |
| if __name__ == "__main__": | |
| run([report, report_missing, report_missing_two], print_summary=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment