Project

General

Profile

Revision efcf5ecf

IDefcf5ecf81924603180dfd735ff5c187ccc68c0a
Parent ad7fd012
Child 4b923a13

Added by Francois POIROTTE about 8 years ago

[#1538] Commit initial

Première version d'un plugin d'intégration entre GLPI et Vigilo.

Change-Id: I5d9922dee2a10929a533129b7f05a1f9214430ac
Refs: #1538

View differences:

front/menu.php
1
<?php
2

  
3
include ("../../../inc/includes.php");
4

  
5
if (PluginVigiloMenu::canView()) {
6
    Html::header(__('Vigilo', 'vigilo'), $_SERVER["PHP_SELF"], "plugins",
7
                    "PluginVigiloMenu", "menu");
8

  
9
    $res = null;
10
    if (!empty($_POST["deploy"])) {
11
        $fds = array(
12
            1 => array("pipe", "w"),
13
            2 => array("pipe", "w"),
14
        );
15
        $cmd = "/usr/bin/sudo -n /usr/bin/vigiconf deploy -f --debug 2>&1";
16
        $res = proc_open($cmd, $fds, $pipes);
17
        if (!is_resource($res))
18
            $res = false;
19
    }
20

  
21
    PluginVigiloMenu::displayMenu($res, $pipes);
22
} else {
23
    Html::displayRightError();
24
}
25

  
26
Html::footer();
27

  
hook.php
1
<?php
2

  
3
//require_once(__DIR__ . DIRECTORY_SEPARATOR . '');
4

  
5
abstract class VigiloXml
6
{
7
    abstract public function __toString();
8

  
9
    public static function sprintf($s)
10
    {
11
        $args = func_get_args();
12
        array_shift($args); // pop $s
13

  
14
        $new_args = array();
15
        foreach ($args as $arg) {
16
            if (is_string($arg)) {
17
                $new_args[] = htmlspecialchars($arg, ENT_XML1 | ENT_QUOTES, "utf-8");
18
            } else if (is_array($arg)) {
19
                $acc = '';
20
                foreach ($arg as $sub) {
21
                    if (is_object($sub))
22
                        $acc .= (string) $sub;
23
                }
24
                $new_args[] = $acc;
25
            } else {
26
                $new_args[] = (string) $arg;
27
            }
28
        }
29

  
30
        return vsprintf($s, $new_args);
31
    }
32
}
33

  
34
class VigiloHostTemplate extends VigiloXml
35
{
36
    protected $name;
37

  
38
    public function __construct($tpl)
39
    {
40
        $this->name = $tpl;
41
    }
42

  
43
    public function __toString()
44
    {
45
        return self::sprintf('<template>%s</template>', $this->name);
46
    }
47
}
48

  
49
class VigiloGroup extends VigiloXml
50
{
51
    protected $name;
52

  
53
    public function __construct($group)
54
    {
55
        $this->name = $group;
56
    }
57

  
58
    public function __toString()
59
    {
60
        return self::sprintf('<group>%s</group>', $this->name);
61
    }
62
}
63

  
64
class VigiloAttribute extends VigiloXml
65
{
66
    protected $name;
67
    protected $value;
68

  
69
    public function __construct($name, $value)
70
    {
71
        $this->name = $name;
72
        $this->value = $value;
73
    }
74

  
75
    public function __toString()
76
    {
77
        return self::sprintf(
78
            '<attribute name="%s">%s</attribute>',
79
            $this->name,
80
            $this->value
81
        );
82
    }
83
}
84

  
85
class VigiloItem extends VigiloXml
86
{
87
    protected $value;
88

  
89
    public function __construct($value)
90
    {
91
        $this->value = $value;
92
    }
93

  
94
    public function getValue()
95
    {
96
        return $this->value;
97
    }
98

  
99
    public function __toString()
100
    {
101
        return self::sprintf('<item>%s</item>', $this->value);
102
    }
103
}
104

  
105
class VigiloArg extends VigiloXml
106
{
107
    protected $name;
108
    protected $values;
109

  
110
    public function __construct($name, $values)
111
    {
112
        if (is_array($values)) {
113
            $new_values = array();
114
            foreach ($values as $value) {
115
                if (is_string($value))
116
                    $new_values[] = new VigiloItem($value);
117
                else if (!is_a($value, 'VigiloItem'))
118
                    throw new \RuntimeException();
119
                else
120
                    $new_values[] = $value;
121
            }
122
            $values = $new_values;
123
        } else if (!is_string($values) && !is_int($values) &&
124
                   !is_bool($values) && !is_float($values))
125
            throw new \RuntimeException();
126
        else {
127
            $values = (string) $values;
128
        }
129

  
130
        $this->name = $name;
131
        $this->values = $values;
132
    }
133

  
134
    public function getName()
135
    {
136
        return $this->name;
137
    }
138

  
139
    public function getValue()
140
    {
141
        if (is_string($this->values))
142
            return $this->values;
143
        return array_map('getValue', $this->values);
144
    }
145

  
146
    public function __toString()
147
    {
148
        return self::sprintf(
149
            '<arg name="%s">%s</arg>',
150
            $this->name,
151
            $this->values
152
        );
153
    }
154
}
155

  
156
class VigiloTest extends VigiloXml
157
{
158
    protected $name;
159
    protected $args;
160

  
161
    public function __construct($name, array $args = array())
162
    {
163
        $new_args = array();
164
        foreach ($args as $arg) {
165
            if (!is_a($arg, 'VigiloArg'))
166
                    throw new \RuntimeException();
167
            $new_args[$arg->getName()] = $arg;
168
        }
169

  
170
        $this->name = $name;
171
        $this->args = $new_args;
172
    }
173

  
174
    public function __toString()
175
    {
176
        return self::sprintf(
177
            '<test name="%s">%s</test>',
178
            $this->name,
179
            $this->args
180
        );
181
    }
182
}
183

  
184
class VigiloHost extends VigiloXml
185
{
186
    protected $computer;
187
    protected $addresses;
188
    protected $ventilation;
189
    protected $children;
190
    protected $agent;
191

  
192
    public function __construct($computer)
193
    {
194
        $this->agent        = null;
195
        $this->ventilation  = "Servers";
196
        $this->computer     = $computer;
197
        $this->addresses    = array();
198
        $this->children     = array();
199

  
200
        if (class_exists('PluginFusioninventoryAgent')) {
201
            $agent = new PluginFusioninventoryAgent();
202
            if ($agent->getAgentWithComputerid($this->computer->getID()) !== false)
203
                $this->agent = $agent;
204
        }
205

  
206
        $this->selectTemplates();
207
        $this->selectGroups();
208
        $this->monitorProcessor();
209
        $this->monitorMemory();
210
        $this->monitorNetworkInterfaces();
211
        $this->monitorSoftwares();
212
        $this->monitorPartitions();
213
    }
214

  
215
    public function getName()
216
    {
217
        return $this->computer->getName();
218
    }
219

  
220
    protected function selectTemplates()
221
    {
222
        $refs = array(
223
            "glpi_operatingsystems" => "operatingsystems_id",
224
            "glpi_operatingsystemversions" => "operatingsystemversions_id",
225
            "glpi_operatingsystemservicepacks" => "operatingsystemservicepacks_id",
226
        );
227

  
228
        $model = array();
229
        foreach ($refs as $table => $field) {
230
            $id = $this->computer->fields[$field];
231
            $value = Dropdown::getDropdownName($table, $id);
232
            if ($value !== "" && $value !== null && $value !== "&nbsp;" &&
233
                $value !== false && $value !== "-----") {
234
                $model[] = $value;
235
            }
236
        }
237

  
238
        if (!count($model))
239
            $model = "default";
240
        else
241
            $model = implode(" - ", $model);
242

  
243
        $this->children[] = new VigiloHostTemplate($model);
244
    }
245

  
246
    protected function selectGroups()
247
    {
248
        $location = new Location();
249
        $location->getFromDB($this->computer->fields["locations_id"]);
250
        $location = $location->getName();
251

  
252
        if (!$location)
253
            $location = "Servers";
254

  
255
        $this->children[] = new VigiloGroup($location);
256
    }
257

  
258
    protected function selectAddress()
259
    {
260
        static $address = null;
261

  
262
        if ($address === null && $this->agent) {
263
            $addresses = $this->agent->getIPs();
264
            if (count($addresses))
265
                $address = current($addresses);
266
        }
267

  
268
        if ($address === null) {
269
            $address = $this->$computer->getName();
270
            foreach ($this->addresses as $addr) {
271
                if (!$addr->is_ipv4())
272
                    continue;
273

  
274
                $textual = $addr->getTextual();
275
                if (is_string($textual)) {
276
                    $address = $textual;
277
                    break;
278
                }
279
            }
280
        }
281

  
282
        return $address;
283
    }
284

  
285
    protected function monitorProcessor()
286
    {
287
        $this->children[] = new VigiloTest('CPU');
288
    }
289

  
290
    protected function monitorMemory()
291
    {
292
        global $DB;
293

  
294
        $total = 0;
295
        $query = Item_DeviceMemory::getSQLRequestToSearchForItem(
296
            $this->computer->getType(),
297
            $this->computer->getID()
298
        );
299

  
300
        foreach ($DB->query($query) as $mem) {
301
            $memory = new Item_DeviceMemory();
302
            $memory->getFromDB($mem['id']);
303
            $total += $memory->fields['size'] * 1024 * 1024;
304
        }
305

  
306
        if ($total > 0)
307
            $this->children[] = new VigiloTest('RAM');
308
    }
309

  
310
    protected function monitorNetworkInterfaces()
311
    {
312
        global $DB;
313

  
314
        $query = NetworkPort::getSQLRequestToSearchForItem(
315
            $this->computer->getType(),
316
            $this->computer->getID()
317
        );
318

  
319
        foreach ($DB->query($query) as $np) {
320
            $query2 = NetworkName::getSQLRequestToSearchForItem("NetworkPort", $np['id']);
321

  
322
            $port = new NetworkPort();
323
            $port->getFromDB($np['id']);
324
            if ($port->getName() == 'lo')
325
                continue;
326

  
327
            $args   = array();
328
            $label  = isset($port->fields['comment']) ? $port->fields['comment'] : $port->getName();
329
            $args[] = new VigiloArg('label', $label);
330
            $args[] = new VigiloArg('name', $port->getName());
331
            // TODO: retrieve interface speed (from glpi_networkportethernets)
332
            $this->children[] = new VigiloTest('Interface', $args);
333

  
334
            // Retrieve all IP addresses associated with this interface.
335
            // This will be used later in selectAddress() to select
336
            // the most appropriate IP address to query this computer.
337
            foreach ($DB->query($query2) as $nn) {
338
                $query3 = IPAddress::getSQLRequestToSearchForItem("NetworkName", $nn['id']);
339
                foreach ($DB->query($query3) as $ip) {
340
                    $addr = new IPAddress();
341
                    if ($addr->getFromDB($ip['id']))
342
                        $this->addresses[] = $addr;
343
                }
344
            }
345
        }
346
    }
347

  
348
    protected function monitorSoftwares()
349
    {
350
        
351
    }
352

  
353
    protected function monitorPartitions()
354
    {
355
        global $DB;
356

  
357
        $query = ComputerDisk::getSQLRequestToSearchForItem(
358
            $this->computer->getType(),
359
            $this->computer->getID()
360
        );
361

  
362
        foreach ($DB->query($query) as $cd) {
363
            $disk = new ComputerDisk();
364
            $disk->getFromDB($cd['id']);
365

  
366
            $args = array();
367
            $args[] = new VigiloArg('label', $disk->getName());
368
            $args[] = new VigiloArg('partname', $disk->fields['mountpoint']);
369
            $total = $disk->fields['totalsize'];
370
            if (!empty($total))
371
                $args[] = new VigiloArg('max', $total * 1024 * 1024);
372
            $this->children[] = new VigiloTest('Partition', $args);
373
        }
374
    }
375

  
376
    public function __toString()
377
    {
378
        return self::sprintf(
379
            '<?xml version="1.0"?>' .
380
            '<host name="%s" address="%s" ventilation="%s">%s</host>',
381
            $this->computer->getName(),
382
            $this->selectAddress(),
383
            "Servers",
384
            $this->children
385
        );
386
    }
387
}
388

  
389
class VigiloHooks
390
{
391
    private $confdir;
392

  
393
    public function __construct($confdir="/etc/vigilo/vigiconf/conf.d")
394
    {
395
        $this->confdir = $confdir;
396
    }
397

  
398
    public function add($computer)
399
    {
400
        $host       = new VigiloHost($computer);
401
        $dirs       = array($this->confdir, "hosts", "managed");
402
        $confdir    = implode(DIRECTORY_SEPARATOR, $dirs);
403
        $file       = $confdir . DIRECTORY_SEPARATOR . $host->getName() . ".xml";
404

  
405
        mkdir($confdir, 0770, true);
406
        $acc = "";
407
        foreach ($dirs as $dir) {
408
            $acc .= DIRECTORY_SEPARATOR . $dir;
409
            chgrp($acc, "vigiconf");
410
        }
411

  
412
        $res = file_put_contents($file, $host, LOCK_EX);
413
        if ($res !== false) {
414
            chgrp($file, "vigiconf");
415
            chmod($file, 0660);
416
        }
417
    }
418

  
419
    public function delete($computer)
420
    {
421
        $this->_unmonitor($computer->fields["name"]);
422
    }
423

  
424
    public function update($computer)
425
    {
426
        if (isset($computer->oldvalues["name"])) {
427
            $this->_unmonitor($computer->oldvalues["name"]);
428
        }
429

  
430
        $this->add($computer);
431
    }
432

  
433
    public function _unmonitor($host)
434
    {
435
        $dirs = array($this->confdir, "hosts", "managed", $host . ".xml");
436
        unlink(implode(DIRECTORY_SEPARATOR, $dirs));
437
    }
438
}
439

  
inc/menu.class.php
1
<?php
2

  
3
if (!defined('GLPI_ROOT')) {
4
    die("Sorry. You can't access directly to this file");
5
}
6

  
7

  
8
class PluginVigiloMenu extends CommonGLPI
9
{
10
    const TIMEOUT = 30;
11

  
12
    /**
13
     * Name of the type
14
     *
15
     * @param $nb  integer  number of item in the type (default 0)
16
    **/
17
    static function getTypeName($nb=0) {
18
        return 'Vigilo';
19
    }
20

  
21
    static function canView() {
22
        return true;
23
    }
24

  
25
    static function canCreate() {
26
        return false;
27
    }
28

  
29
    static function getMenuName() {
30
        return self::getTypeName();
31
    }
32

  
33
    static function getAdditionalMenuOptions() {
34
        return array();
35
    }
36

  
37
    static function getAdditionalMenuContent() {
38
        return array();
39
    }
40

  
41
    static function displayMenu($res, $pipes) {
42
        echo '<h1>Vigilo</h1><form method="post" action="?itemtype=vigilo">';
43

  
44
        if (is_resource($res)) {
45
            ini_set("max_execution_time", 0);
46
            ignore_user_abort(true);
47
            set_time_limit(0);
48

  
49
            echo '<textarea readonly="readonly" id="vigilo_deploy" style="display: block; width: 99%; height: 280px">';
50
            do {
51
                $read = $exc = $pipes;
52
                $write = array();
53

  
54
                $nb = stream_select($read, $write, $exc, static::TIMEOUT, 0);
55

  
56
                // Error
57
                if ($nb === FALSE) {
58
                    echo "UNKNOWN ERROR\n";
59
                    break;
60
                }
61

  
62
                // Timeout
63
                if ($nb === 0) {
64
                    echo "ERROR: command timed out!\n";
65
                    break;
66
                }
67

  
68
                if (count($exc)) {
69
                    echo "UNKNOWN ERROR\n";
70
                    break;
71
                }
72

  
73
                foreach ($read as $stream)
74
                    echo htmlspecialchars(fread($stream, 1024), ENT_HTML5 | ENT_QUOTES, "utf-8");
75
                ob_flush();
76
                flush();
77

  
78
                if (feof($pipes[1]))
79
                    break;
80
            } while (1);
81

  
82
            $info = proc_get_status($res);
83
            if ($info === false) {
84
                echo "ERROR: could not determine process status\n";
85
            } else {
86
                if ($info["signaled"])
87
                    echo "Command terminated by signal ${info['termsig']}\n";
88
                if ($info["stopped"])
89
                    echo "Command stopped by signal ${info['stopsig']}\n";
90
                echo "Command exited with return code ${info['exitcode']}\n";
91
            }
92

  
93
            proc_close($res);
94
            echo '</textarea>';
95
        }
96

  
97
        echo '<button type="submit" name="deploy" value="1">Deploy</button>';
98
        Html::closeForm();
99
    }
100
}
setup.php
1
<?php
2

  
3
include(__DIR__ . "/hook.php");
4

  
5
function plugin_init_vigilo() {
6
    global $PLUGIN_HOOKS;
7

  
8
    $hooks      =& $PLUGIN_HOOKS;
9
    $p          =  "vigilo";
10
    $hookObj    =  new VigiloHooks();
11

  
12
    $hooks['csrf_compliant'][$p]        = true;
13
    $hooks['item_add'][$p]              = array("Computer" => array($hookObj, "add"));
14
    $hooks['item_update'][$p]           = array("Computer" => array($hookObj, "update"));
15
    $hooks['item_purge'][$p]            = array("Computer" => array($hookObj, "delete"));
16
    $hooks['item_delete'][$p]           = array("Computer" => array($hookObj, "delete"));
17
    $hooks['item_restore'][$p]          = array("Computer" => array($hookObj, "add"));
18
    $hooks["menu_toadd"][$p]['plugins'] = 'PluginVigiloMenu';
19
    $hooks['config_page'][$p]           = 'front/menu.php?itemtype=vigilo';
20
}
21

  
22
function plugin_version_vigilo() {
23
   return array('name'           => 'Vigilo monitoring',
24
                'version'        => '0.1',
25
                'author'         => 'CSSI',
26
                'license'        => 'GPLv2+',
27
                'homepage'       => 'http://vigilo-nms.org',
28
                'minGlpiVersion' => '9.1');
29
}
30

  
31
function plugin_vigilo_check_config($verbose=false) {
32
    if (version_compare(GLPI_VERSION,'9.1','lt')) {
33
        echo "This plugin requires GLPI >= 9.1";
34
        return false;
35
    }
36
    return true;
37
}
38

  
39
function plugin_vigilo_check_prerequisites() {
40
    return true;
41
}
42

  
43
function plugin_vigilo_install() {
44
    return true;
45
}
46

  
47
function plugin_vigilo_uninstall() {
48
    return true;
49
}
50

  

Also available in: Unified diff