~shinken-dev/shinken/trunk

« back to all changes in this revision

Viewing changes to modules/landscape/module.py

  • Committer: naparuba
  • Date: 2013-07-17 14:55:41 UTC
  • Revision ID: git-v1:3ed4da6390f7424d887e0c8dc55be2830ee44baa
Enh: remove the Landscape import module from the core repo.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
2
 
 
3
 
# -*- coding: utf-8 -*-
4
 
 
5
 
# Copyright (C) 2009-2012:
6
 
#    Gabes Jean, naparuba@gmail.com
7
 
#    Gerhard Lausser, Gerhard.Lausser@consol.de
8
 
#    Gregory Starck, g.starck@gmail.com
9
 
#    Hartmut Goebel, h.goebel@goebel-consult.de
10
 
#
11
 
# This file is part of Shinken.
12
 
#
13
 
# Shinken is free software: you can redistribute it and/or modify
14
 
# it under the terms of the GNU Affero General Public License as published by
15
 
# the Free Software Foundation, either version 3 of the License, or
16
 
# (at your option) any later version.
17
 
#
18
 
# Shinken is distributed in the hope that it will be useful,
19
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 
# GNU Affero General Public License for more details.
22
 
#
23
 
# You should have received a copy of the GNU Affero General Public License
24
 
# along with Shinken.  If not, see <http://www.gnu.org/licenses/>.
25
 
# This module imports hosts and services configuration from a MySQL Database
26
 
# Queries for getting hosts and services are pulled from shinken-specific.cfg configuration file.
27
 
 
28
 
import os
29
 
 
30
 
# Try to import landscape API 
31
 
try:
32
 
    from landscape_api.base import API, HTTPError
33
 
except ImportError:
34
 
    API = HTTPError = None
35
 
 
36
 
from shinken.basemodule import BaseModule
37
 
from shinken.log import logger
38
 
 
39
 
properties = {
40
 
    'daemons': ['arbiter'],
41
 
    'type': 'landscape_import',
42
 
    'external': False,
43
 
    'phases': ['configuration'],
44
 
}
45
 
 
46
 
 
47
 
# called by the plugin manager to get a broker
48
 
def get_instance(plugin):
49
 
    logger.debug("[Landscape Importer Module]: Get Landscape importer instance for plugin %s" % plugin.get_name())
50
 
    if not API:
51
 
        raise Exception('Missing module landscape-api. Please install it from https://launchpad.net/~landscape/+archive/landscape-api.')
52
 
 
53
 
    # Beware : we must have RAW string here, not unicode!
54
 
    key = str(plugin.key.strip())
55
 
    secret = str(plugin.secret.strip())
56
 
    ca = getattr(plugin, 'ca', None)
57
 
    default_template = getattr(plugin, 'default_template', '')
58
 
    https_proxy = getattr(plugin, 'https_proxy', '')
59
 
    
60
 
    instance = Landscape_importer_arbiter(plugin, key, secret, ca, default_template, https_proxy)
61
 
    return instance
62
 
 
63
 
 
64
 
# Retrieve hosts from landscape API
65
 
class Landscape_importer_arbiter(BaseModule):
66
 
    def __init__(self, mod_conf, key, secret, ca, default_template, https_proxy):
67
 
        BaseModule.__init__(self, mod_conf)
68
 
        self.key = key
69
 
        self.secret = secret
70
 
        self.ca = ca
71
 
        self.default_template = default_template
72
 
        self.https_proxy   = https_proxy
73
 
 
74
 
 
75
 
    # Called by Arbiter to say 'let's prepare yourself guy'
76
 
    def init(self):
77
 
        if self.https_proxy:
78
 
            os.environ["https_proxy"] = self.https_proxy
79
 
            
80
 
        logger.debug("[Landscape Importer Module]: Try to open a Landscape connection")
81
 
        uri = "https://landscape.canonical.com/api/"
82
 
        try:
83
 
            if self.ca:
84
 
                self.api = API(uri, self.key, self.secret, self.ca)
85
 
            else:
86
 
                self.api = API(uri, self.key, self.secret)
87
 
        except HTTPError, e:
88
 
            logger.debug("Landscape Module: Error %s" % e)
89
 
            raise
90
 
        logger.info("[Landscape Importer Module]: Connection opened")
91
 
 
92
 
 
93
 
    # Main function that is called in the CONFIGURATION phase
94
 
    def get_objects(self):
95
 
        try:
96
 
            computers = self.api.get_computers(with_network=True, limit=30000)
97
 
        except HTTPError, e:
98
 
            logger.debug("Landscape Module: Error %s" % e)
99
 
            raise
100
 
        
101
 
        # Create variables for result
102
 
        r = {'hosts' : []}
103
 
 
104
 
        for c in computers:
105
 
            hname = c['hostname']
106
 
            alias = c["title"]
107
 
            tags = c["tags"]
108
 
            if tags == [] and self.default_template:
109
 
                tags = [self.default_template]
110
 
            ips = [net["ip_address"] for net in c["network_devices"]]
111
 
 
112
 
            # If there is more than one IP address, use the first
113
 
            ip = ''
114
 
            if len(ips) > 0:
115
 
                ip = ips[0]
116
 
            # By default take the IP as the address
117
 
            address = ip
118
 
            # But if not available, use the hostname
119
 
            if not address:
120
 
                address = hname
121
 
            h = {'host_name' : hname,
122
 
                 'alias'     : alias,
123
 
                 'use'       : tags,
124
 
                 'use'       : ','.join(tags)
125
 
                 }
126
 
            r['hosts'].append(h)
127
 
 
128
 
        logger.debug("[Landscape Importer Module]: Returning to Arbiter %d hosts" % len(r['hosts']))
129
 
        return r