Passed
Push — master ( b3870e...b0b632 )
by Patrick
02:01
created

StatusController::pluginsAction()   B

Complexity

Conditions 7
Paths 34

Size

Total Lines 42
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 26
nc 34
nop 0
dl 0
loc 42
rs 8.5706
c 0
b 0
f 0
1
<?php
2
3
namespace Icinga\Module\Trapdirector\Controllers;
4
5
use Icinga\Web\Url;
6
use Icinga\Web\Form;
7
use Zend_Form_Element_File as File;
8
use Zend_Form_Element_Submit as Submit;
9
10
use Exception;
11
12
use Icinga\Module\Trapdirector\TrapsController;
13
use Trapdirector\Trap;
14
15
class StatusController extends TrapsController
16
{
17
	public function indexAction()
18
	{
19
		$this->prepareTabs()->activate('status');
20
		
21
		/************  Trapdb ***********/
22
		try
23
		{
24
			$db = $this->getDb()->getConnection();
25
			$query = $db->select()->from(
26
				$this->getModuleConfig()->getTrapTableName(),
27
				array('COUNT(*)')
28
			);			
29
			$this->view->trap_count=$db->fetchOne($query);
30
			$query = $db->select()->from(
31
				$this->getModuleConfig()->getTrapDataTableName(),
32
				array('COUNT(*)')
33
			);			
34
			$this->view->trap_object_count=$db->fetchOne($query);
35
			$query = $db->select()->from(
36
				$this->getModuleConfig()->getTrapRuleName(),
37
				array('COUNT(*)')
38
			);			
39
			$this->view->rule_count=$db->fetchOne($query);			
40
 			
41
			$this->view->trap_days_delete=$this->getDBConfigValue('db_remove_days');
42
			
43
		}
44
		catch (Exception $e)
45
		{
46
			$this->displayExitError('status',$e->getMessage());
47
		}
48
		
49
		/*************** Log destination *******************/
50
		
51
		try
52
		{		
53
			$this->view->currentLogDestination=$this->getDBConfigValue('log_destination');
54
			$this->view->logDestinations=$this->getModuleConfig()->getLogDestinations();
55
			$this->view->currentLogFile=$this->getDBConfigValue('log_file');
56
			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
57
			$this->view->currentLogLevel=$this->getDBConfigValue('log_level');
58
		}
59
		catch (Exception $e)
60
		{
61
			$this->displayExitError('status',$e->getMessage());
62
		}		
63
		
64
	} 
65
  
66
	/** Mib management
67
	*	Post param : action=update_mib_db : update mib database
68
	*	Post param : ation=check_update : check if mib update is finished
69
	*	File post : mibfile -> save mib file
70
	*/
71
	public function mibAction()
72
	{
73
		$this->prepareTabs()->activate('mib');
74
		
75
		$this->view->uploadStatus=null;
76
		// check if it is an ajax query
77
		if ($this->getRequest()->isPost())
78
		{
79
			$postData=$this->getRequest()->getPost();
80
			/** Check for action update or check update */
81
			if (isset($postData['action']))
82
			{
83
				$action=$postData['action'];
84
				if ($action == 'update_mib_db')
85
				{ // Do the update in background
86
					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
87
					if (preg_match('/OK/',$return))
88
					{
89
					    $this->_helper->json(array('status'=>'OK'));
90
					}
91
					// Error
92
					$this->_helper->json(array('status'=>$return));
93
				}
94
				if ($action == 'check_update')
95
				{
96
				    $file=@fopen('/tmp/trapdirector_update.pid','r');
97
				    if ($file == false)
98
				    {   // process is dead
99
				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
100
				        return;
101
				    }
102
				    $pid=fgets($file);
103
				    $output=array();
104
				    $retVal=0;
105
					exec('ps '.$pid,$output,$retVal);
106
					if ($retVal == 0)
107
					{ // process is alive
108
						$this->_helper->json(array('status'=>'Alive and kicking'));
109
					}
110
					else
111
					{ // process is dead
112
					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
113
					}
114
				}
115
				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
116
			}
117
			/** Check for mib file UPLOAD */
118
			if (isset($_FILES['mibfile']))
119
			{
120
				$name=$_FILES['mibfile']['name'];
121
				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
122
				$destDir=array_shift($DirConf);
123
				if (!is_dir($destDir))
124
				{
125
				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
126
				}
127
				else
128
				{
129
				    if (!is_writable($destDir))
130
				    {
131
				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
132
				    }
133
				    else
134
				    {
135
				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
136
    				    if (move_uploaded_file($_FILES['mibfile']['tmp_name'],$destination)===false)
137
    				    {
138
    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
139
    				    }
140
    				    else
141
    				    {
142
    				        $this->view->uploadStatus="File $name uploaded in $destDir";
143
    				    }
144
				    }
145
				}
146
147
			}
148
			
149
		}
150
		
151
		// snmptranslate tests
152
		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
153
		$this->view->snmptranslate_bin=$snmptranslate;
154
		$this->view->snmptranslate_state='warn';
155
		if (is_executable ( $snmptranslate ))
156
		{
157
			$translate=exec($snmptranslate . ' 1');
158
			if (preg_match('/iso/',$translate))
159
			{
160
				$this->view->snmptranslate='works fine';
161
				$this->view->snmptranslate_state='ok';
162
			}
163
			else
164
			{
165
				$this->view->snmptranslate='can execute but no resolution';
166
			}
167
		}
168
		else
169
		{
170
			$this->view->snmptranslate='cannot execute';
171
		}
172
	
173
		// mib database
174
		
175
		$this->view->mibDbCount=$this->getMIB()->countObjects();
176
		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
177
		
178
		// mib dirs
179
		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
180
		$dirArray=explode(':',$DirConf);
181
182
		// Get base directories from net-snmp-config
183
		$output=$matches=array();
184
		$retVal=0;
185
		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
186
		if ($retVal==0)
187
		{
188
			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
189
		}
190
		else
191
		{
192
			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
193
			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
194
			{
195
				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
196
			}
197
			else
198
			{
199
				array_push($dirArray,'Install net-snmp-config to see system directories');
200
			}
201
		}
202
		
203
		$this->view->dirArray=$dirArray;
204
		
205
		$output=null;
206
		foreach (explode(':',$DirConf) as $mibdir)
207
		{
208
			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
209
		}
210
		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
211
		//$this->view->fileList=explode(' ',$listFiles);
212
		$this->view->fileList=$output;
213
		
214
		// Zend form 
215
		$this->view->form= new UploadForm();
216
		//$this->view->form= new Form('upload-form');
217
		
218
		
219
	}
220
221
	/** Create services and templates
222
	 *  Create template for trap service
223
	 * 
224
	 */
225
	public function servicesAction()
226
	{
227
		$this->prepareTabs()->activate('services');
228
		
229
		/*if (!$this->isDirectorInstalled())
230
		{
231
			$this->displayExitError("Status -> Services","Director is not installed, template & services install are not available");
232
		}
233
		*/
234
		// Check if data was sent :
235
		$postData=$this->getRequest()->getPost();
236
		$this->view->templateForm_output='';
237
		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
238
		{
239
			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
240
			$template_create .= '"check_interval": "' .$postData['template_revert_time']. '", "check_timeout": "20", "disabled": false, "enable_active_checks": true, "enable_event_handler": true, "enable_notifications": true, "enable_passive_checks": true, "enable_perfdata": true, "max_check_attempts": "1", ';
241
			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
242
			$output=array();
243
			$ret_code=0;
244
			exec($template_create,$output,$ret_code);
245
			if ($ret_code != 0)
246
			{
247
				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
248
			}
249
			exec('icingacli director config deploy',$output,$ret_code);
250
			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
251
		}
252
		
253
		// template creation form
254
		$this->view->templateForm_URL=Url::fromRequest()->__toString();
255
		$this->view->templateForm_name="trapdirector_main_template";
256
		$this->view->templateForm_interval="3600";
257
	}
258
    
259
	/**
260
	 * Plugins display and activation
261
	 */
262
	public function pluginsAction()
263
	{
264
	    $this->prepareTabs()->activate('plugins');
265
	    
266
	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
267
	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
268
	    $Trap = new Trap($icingaweb2_etc,4);
269
	    
270
	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
271
	    
272
	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
273
274
	    $pluginList = $Trap->pluginClass->pluginList();
275
	    
276
	    // Plugin list and fill function name list
277
	    $functionList=array();
278
	    $this->view->pluginArray=array();
279
	    foreach ($pluginList as $plugin)
280
	    {
281
	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
282
	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
283
	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
284
	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
285
	        $pluginDetails->description = htmlentities($pluginDetails->description);
286
	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
287
	        array_push($this->view->pluginArray, $pluginDetails);
288
	        // Get functions for function details
289
	        foreach ($pluginDetails->funcArray as $function)
290
	        {
291
	            array_push($functionList,$function);
292
	        }
293
	    }
294
	    
295
	    // Function list with details
296
	    $this->view->functionList=array();
297
	    foreach ($functionList as $function)
298
	    {
299
	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
300
	        $functionDetail->params = htmlentities($functionDetail->params);
301
	        $functionDetail->description = htmlentities($functionDetail->description);
302
	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
303
	        array_push($this->view->functionList, $functionDetail);
304
	    }
305
306
	}
307
	
308
	protected function prepareTabs()
309
	{
310
		return $this->getTabs()->add('status', array(
311
			'label' => $this->translate('Status'),
312
			'url'   => $this->getModuleConfig()->urlPath() . '/status')
313
		)->add('mib', array(
314
			'label' => $this->translate('MIB Management'),
315
			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
316
		)->add('services', array(
317
			'label' => $this->translate('Services management'),
318
			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
319
	    )->add('plugins', array(
320
	        'label' => $this->translate('Plugins management'),
321
	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
322
	    );
323
	} 
324
}
325
326
// TODO : see if useless 
327
class UploadForm extends Form
328
{ 
329
    public function __construct($options = null) 
330
    {
331
        parent::__construct($options);
332
        $this->addElements2();
333
    }
334
335
    public function addElements2()
336
    {
337
        // File Input
338
        $file = new File('mib-file');
339
        $file->setLabel('Mib upload');
340
             //->setAttrib('multiple', null);
341
        $this->addElement($file);
342
		$button = new Submit("upload",array('ignore'=>false));
343
		$this->addElement($button);//->setIgnore(false);
344
    }
345
}
346