Project

General

Profile

__init__.py

hacen bani, 05/09/2016 02:10 AM

Download (2.42 KB)

 
1
"""A basic inventory plugin""" 
2
from pkg_resources import resource_filename
3
from prewikka import database, env, utils, view
4
from inventory import templates
5

    
6
class Inventory(view.View):
7
    """The main Inventory view""" 
8
    plugin_name = "Inventory" 
9
    plugin_description = "A basic inventory plugin" 
10
    plugin_version = "1.0.0" 
11
    view_name = "Inventory" 
12
    view_section = "Inventory"
13
    plugin_database_version = "0"
14
    view_template = templates.inventory
15
    view_parameters = InventoryParameters
16
    plugin_htdocs = (("inventory", resource_filename(__name__, "htdocs")),)
17

    
18
    def __init__(self):
19
        view.View.__init__(self)
20
        self._config = getattr(env.config, "inventory", {})
21
        self._db = InventoryDatabase() 
22
        env.hookmgr.declare_once("HOOK_LINK")
23
        env.hookmgr.register("HOOK_LINK", self._get_inventory_link)
24
          
25
    def _get_inventory_link(self, value):
26
        """Create a link to the inventory to be displayed in the alert view""" 
27
        return ("host",
28
                "Search in inventory",
29
                utils.create_link(self.view_path, {"search": value}),
30
                False)
31

    
32
    def render(self):
33
        params = self.parameters
34
        if "hostname" in params:
35
            self._db.add_host(params.get("hostname"),
36
                              params.get("address"),
37
                              params.get("os"))
38
        self.dataset["inventory"] = self._db.get_hosts(params.get("search"))
39
        self.dataset["title"] = self._config.get("title", "Inventory")     
40

    
41
class InventoryDatabase(database.DatabaseHelper):
42
    """Handle database queries related to the inventory""" 
43

    
44
    def get_hosts(self, keyword=None):
45
        """Return all hosts in the inventory database matching the keyword""" 
46
        query = "SELECT hostname, address, os FROM Prewikka_Inventory" 
47
        if keyword:
48
            query += (" WHERE hostname = %(keyword)s" 
49
                      " OR address = %(keyword)s" 
50
                      " OR os = %(keyword)s" %
51
                      {"keyword": self.escape(keyword)})
52
        return self.query(query)
53

    
54
    def add_host(self, hostname, address, os):
55
        """Add a host to the inventory database""" 
56
        self.query("INSERT INTO Prewikka_Inventory (hostname, address, os) " 
57
                   "VALUES (%s, %s, %s)" % (self.escape(hostname),
58
                                            self.escape(address),
59
                                            self.escape(os)))