StatusController::mibAction()   F
last analyzed

Complexity

Conditions 18
Paths 1227

Size

Total Lines 154
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 18
eloc 78
c 4
b 0
f 0
nc 1227
nop 0
dl 0
loc 154
rs 0.7

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
		    $dbConn = $this->getUIDatabase()->getDbConn();
25
		    if ($dbConn === null) throw new \ErrorException('uncatched db error');
26
			$query = $dbConn->select()->from(
27
				$this->getModuleConfig()->getTrapTableName(),
28
				array('COUNT(*)')
29
			);			
30
			$this->view->trap_count=$dbConn->fetchOne($query);
31
			$query = $dbConn->select()->from(
32
				$this->getModuleConfig()->getTrapDataTableName(),
33
				array('COUNT(*)')
34
			);			
35
			$this->view->trap_object_count=$dbConn->fetchOne($query);
36
			$query = $dbConn->select()->from(
37
				$this->getModuleConfig()->getTrapRuleName(),
38
				array('COUNT(*)')
39
			);			
40
			$this->view->rule_count=$dbConn->fetchOne($query);			
41
 			
42
			$this->view->trap_days_delete=$this->getUIDatabase()->getDBConfigValue('db_remove_days');
43
			
44
		}
45
		catch (Exception $e)
46
		{
47
			$this->displayExitError('status',$e->getMessage());
48
		}
49
		
50
		/*************** Log destination *******************/
51
		
52
		try
53
		{		
54
		    $this->view->currentLogDestination=$this->getUIDatabase()->getDBConfigValue('log_destination');
55
			$this->view->logDestinations=$this->getModuleConfig()->getLogDestinations();
56
			$this->view->currentLogFile=$this->getUIDatabase()->getDBConfigValue('log_file');
57
			$this->view->logLevels=$this->getModuleConfig()->getlogLevels();
58
			$this->view->currentLogLevel=$this->getUIDatabase()->getDBConfigValue('log_level');
59
		}
60
		catch (Exception $e)
61
		{
62
			$this->displayExitError('status',$e->getMessage());
63
		}
64
		
65
		/*************** SNMP configuration ****************/
66
		try
67
		{
68
		    $this->view->useSnmpTrapAddess= ( $this->getUIDatabase()->getDBConfigValue('use_SnmpTrapAddess') == 1 ) ? TRUE : FALSE;
69
		    $this->view->SnmpTrapAddressOID=$this->getUIDatabase()->getDBConfigValue('SnmpTrapAddess_oid');
70
		    $this->view->SnmpTrapAddressOIDDefault = ($this->view->SnmpTrapAddressOID == $this->getModuleConfig()->getDBConfigDefaults()['SnmpTrapAddess_oid'] ) ? TRUE : FALSE;
71
		    
72
		}
73
		catch (Exception $e)
74
		{
75
		    $this->displayExitError('status',$e->getMessage());
76
		}		
77
		
78
	} 
79
  
80
	/** Mib management
81
	*	Post param : action=update_mib_db : update mib database
82
	*	Post param : ation=check_update : check if mib update is finished
83
	*	File post : mibfile -> save mib file
84
	*/
85
	public function mibAction()
86
	{
87
		$this->prepareTabs()->activate('mib');
88
		
89
		$this->view->uploadStatus=null;
90
		// check if it is an ajax query
91
		if ($this->getRequest()->isPost())
92
		{
93
			$postData=$this->getRequest()->getPost();
94
			/** Check for action update or check update */
95
			if (isset($postData['action']))
96
			{
97
				$action=$postData['action'];
98
				if ($action == 'update_mib_db')
99
				{ // Do the update in background
100
					$return=exec('icingacli trapdirector mib update --pid /tmp/trapdirector_update.pid');
101
					if (preg_match('/OK/',$return))
102
					{
103
					    $this->_helper->json(array('status'=>'OK'));
104
					}
105
					// Error
106
					$this->_helper->json(array('status'=>$return));
107
				}
108
				if ($action == 'check_update')
109
				{
110
				    $file=@fopen('/tmp/trapdirector_update.pid','r');
111
				    if ($file == false)
112
				    {   // process is dead
113
				        $this->_helper->json(array('status'=>'tu quoque fili','err'=>'Cannot open file'));
114
				        return;
115
				    }
116
				    $pid=fgets($file);
117
				    $output=array();
118
				    $retVal=0;
119
					exec('ps '.$pid,$output,$retVal);
120
					if ($retVal == 0)
121
					{ // process is alive
122
						$this->_helper->json(array('status'=>'Alive and kicking'));
123
					}
124
					else
125
					{ // process is dead
126
					    $this->_helper->json(array('status'=>'tu quoque fili','err'=>'no proc'.$pid));
127
					}
128
				}
129
				$this->_helper->json(array('status'=>'ERR : no '.$action.' action possible' ));
130
			}
131
			/** Check for mib file UPLOAD */
132
			if (isset($_FILES['mibfile']))
133
			{
134
			    $name=filter_var($_FILES['mibfile']['name'],FILTER_SANITIZE_STRING);
135
				$DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs'));
136
				$destDir=array_shift($DirConf);
137
				if (!is_dir($destDir))
138
				{
139
				    $this->view->uploadStatus="ERROR : no $destDir directory, check module configuration";
140
				}
141
				else
142
				{
143
				    if (!is_writable($destDir))
144
				    {
145
				        $this->view->uploadStatus="ERROR : $destDir directory is not writable";
146
				    }
147
				    else
148
				    {
149
				        $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name";
150
				        $sourceTmpNam=filter_var($_FILES['mibfile']['tmp_name'],FILTER_SANITIZE_STRING);
151
				        if (move_uploaded_file($sourceTmpNam,$destination)===false)
152
    				    {
153
    				        $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations";
154
    				    }
155
    				    else
156
    				    {
157
    				        $this->view->uploadStatus="File $name uploaded in $destDir";
158
    				    }
159
				    }
160
				}
161
162
			}
163
			
164
		}
165
		
166
		// snmptranslate tests
167
		$snmptranslate = $this->Config()->get('config', 'snmptranslate');
168
		$this->view->snmptranslate_bin=$snmptranslate;
169
		$this->view->snmptranslate_state='warn';
170
		if (is_executable ( $snmptranslate ))
171
		{
172
			$translate=exec($snmptranslate . ' 1');
173
			if (preg_match('/iso/',$translate))
174
			{
175
			    $translate=exec($snmptranslate . ' 1.3.6.1.4');
176
			    if (preg_match('/private/',$translate))
177
			    {		    
178
    				$this->view->snmptranslate='works fine';
179
    				$this->view->snmptranslate_state='ok';
180
			    }
181
			    else
182
			    {
183
			        $this->view->snmptranslate='works fine but missing basic MIBs';
184
			    }
185
			}
186
			else
187
			{
188
				$this->view->snmptranslate='Can execute but no OID to name resolution';
189
			}
190
		}
191
		else
192
		{
193
			$this->view->snmptranslate='Cannot execute';
194
		}
195
	
196
		// mib database
197
		
198
		$this->view->mibDbCount=$this->getMIB()->countObjects();
199
		$this->view->mibDbCountTrap=$this->getMIB()->countObjects(null,21);
200
		
201
		// mib dirs
202
		$DirConf=$this->Config()->get('config', 'snmptranslate_dirs');
203
		$dirArray=explode(':',$DirConf);
204
205
		// Get base directories from net-snmp-config
206
		$output=$matches=array();
207
		$retVal=0;
208
		$sysDirs=exec('net-snmp-config --default-mibdirs',$output,$retVal);
209
		if ($retVal==0)
210
		{
211
			$dirArray=array_merge($dirArray,explode(':',$sysDirs));
212
		}
213
		else
214
		{
215
			$translateOut=exec($this->Config()->get('config', 'snmptranslate') . ' -Dinit_mib .1.3 2>&1 | grep MIBDIRS');
216
			if (preg_match('/MIBDIRS.*\'([^\']+)\'/',$translateOut,$matches))
217
			{
218
				$dirArray=array_merge($dirArray,explode(':',$matches[1]));
219
			}
220
			else
221
			{
222
				array_push($dirArray,'Install net-snmp-config to see system directories');
223
			}
224
		}
225
		
226
		$this->view->dirArray=$dirArray;
227
		
228
		$output=null;
229
		foreach (explode(':',$DirConf) as $mibdir)
230
		{
231
			exec('ls '.$mibdir.' | grep -v traplist.txt',$output);
232
		}
233
		//$i=0;$listFiles='';while (isset($output[$i])) $listFiles.=$output[$i++];
234
		//$this->view->fileList=explode(' ',$listFiles);
235
		$this->view->fileList=$output;
236
		
237
		// Zend form 
238
		$this->view->form= new UploadForm();
239
		//$this->view->form= new Form('upload-form');
240
		
241
		
242
	}
243
244
	/** UI options */
245
	public function uimgtAction()
246
	{
247
	    $this->prepareTabs()->activate('uimgt');
248
	    
249
	    $this->view->setError='';
250
	    $this->view->setOKMsg='';
251
	    
252
	    //max_rows=25&row_update=update
253
	    if ( $this->getRequest()->getParam('max_rows',NULL) !== NULL )
254
	    {
255
	        $maxRows = $this->getRequest()->getParam('max_rows');
256
	        if (!preg_match('/^[0-9]+$/', $maxRows) || $maxRows < 1)
257
	        {
258
	            $this->view->setError='Max rows must be a number';
259
	        }
260
	        else
261
	        {
262
	            $this->setitemListDisplay($maxRows);
263
	            $this->view->setOKMsg='Set max rows to ' . $maxRows;
264
	        }
265
	    }
266
	    
267
	    if ( $this->getRequest()->getParam('add_category',NULL) !== NULL )
268
	    {
269
	        $addCat = $this->getRequest()->getParam('add_category');
270
            $this->addHandlersCategory($addCat);
271
	    }
272
	    
273
	    if ( $this->getRequest()->getPost('type',NULL) !== NULL )
274
	    {
275
	        $type = $this->getRequest()->getPost('type',NULL);
276
	        $index = $this->getRequest()->getPost('index',NULL);
277
	        $newname = $this->getRequest()->getPost('newname',NULL);
278
279
	        if (!preg_match('/^[0-9]+$/', $index) || $index < 1)
280
	            $this->_helper->json(array('status'=>'Bad index'));
281
	        
282
	        switch ($type)
283
	        {
284
	            case 'delete':
285
	                $this->delHandlersCategory($index);
286
	                $this->_helper->json(array('status'=>'OK'));
287
	                return;
288
	                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
289
	            case 'rename':
290
	                $this->renameHandlersCategory($index, $newname);
291
	                $this->_helper->json(array('status'=>'OK'));
292
	                return;
293
	                break;
294
	            default:
295
	                $this->_helper->json(array('status'=>'Unknwon command'));
296
	                return;
297
	                break;
298
	        }
299
	    }
300
	    
301
	    $this->view->maxRows = $this->itemListDisplay();
302
	    
303
	    $this->view->categories = $this->getHandlersCategory();
304
	    
305
	    
306
	    
307
	}
308
	
309
	/** Create services and templates
310
	 *  Create template for trap service
311
	 * 
312
	 */
313
	public function servicesAction()
314
	{
315
		$this->prepareTabs()->activate('services');
316
		
317
		/*if (!$this->isDirectorInstalled())
318
		{
319
			$this->displayExitError("Status -> Services","Director is not installed, template & services install are not available");
320
		}
321
		*/
322
		// Check if data was sent :
323
		$postData=$this->getRequest()->getPost();
324
		$this->view->templateForm_output='';
325
		if (isset($postData['template_name']) && isset($postData['template_revert_time']))
326
		{
327
			$template_create = 'icingacli director service create --json \'{ "check_command": "dummy", ';
328
			$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", ';
329
			$template_create .= '"object_name": "'.$postData['template_name'].'", "object_type": "template", "retry_interval": "'.$postData['template_revert_time'].'"}\'';
330
			$output=array();
331
			$ret_code=0;
332
			exec($template_create,$output,$ret_code);
333
			if ($ret_code != 0)
334
			{
335
				$this->displayExitError("Status -> Services","Error creating template : ".$output[0].'<br>Command was : '.$template_create);
336
			}
337
			exec('icingacli director config deploy',$output,$ret_code);
338
			$this->view->templateForm_output='Template '.$postData['template_name']. ' created';
339
		}
340
		
341
		// template creation form
342
		$this->view->templateForm_URL=Url::fromRequest()->__toString();
343
		$this->view->templateForm_name="trapdirector_main_template";
344
		$this->view->templateForm_interval="3600";
345
	}
346
    
347
	/**
348
	 * Plugins display and activation
349
	 */
350
	public function pluginsAction()
351
	{
352
	    $this->prepareTabs()->activate('plugins');
353
	    
354
	    require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
355
	    $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
356
	    $Trap = new Trap($icingaweb2_etc,4);
357
	    
358
	    $this->view->pluginLoaded = htmlentities($Trap->pluginClass->registerAllPlugins(false));
359
	    
360
	    $enabledPlugins = $Trap->pluginClass->getEnabledPlugins();
361
362
	    $pluginList = $Trap->pluginClass->pluginList();
363
	    
364
	    // Plugin list and fill function name list
365
	    $functionList=array();
366
	    $this->view->pluginArray=array();
367
	    foreach ($pluginList as $plugin)
368
	    {
369
	        $pluginDetails=$Trap->pluginClass->pluginDetails($plugin);
370
	        $pluginDetails->enabled =  (in_array($plugin, $enabledPlugins)) ? true : false;
371
	        $pluginDetails->catchAllTraps = ($pluginDetails->catchAllTraps === true )? 'Yes' : 'No';
372
	        $pluginDetails->processTraps = ($pluginDetails->processTraps === true )? 'Yes' : 'No';
373
	        $pluginDetails->description = htmlentities($pluginDetails->description);
374
	        $pluginDetails->description = preg_replace('/\n/','<br>',$pluginDetails->description);
375
	        array_push($this->view->pluginArray, $pluginDetails);
376
	        // Get functions for function details
377
	        foreach ($pluginDetails->funcArray as $function)
378
	        {
379
	            array_push($functionList,$function);
380
	        }
381
	    }
382
	    
383
	    // Function list with details
384
	    $this->view->functionList=array();
385
	    foreach ($functionList as $function)
386
	    {
387
	        $functionDetail = $Trap->pluginClass->getFunctionDetails($function);
388
	        $functionDetail->params = htmlentities($functionDetail->params);
389
	        $functionDetail->description = htmlentities($functionDetail->description);
390
	        $functionDetail->description = preg_replace('/\n/','<br>',$functionDetail->description);
391
	        array_push($this->view->functionList, $functionDetail);
392
	    }
393
394
	}
395
396
	/**
397
	 * For testing functions
398
	 */
399
	public function debugAction()
400
	{
401
	    $this->view->answer='No answer';
402
	    $this->view->input1 = '';
403
	    
404
	    $postData=$this->getRequest()->getPost();
405
	    if (isset($postData['input1']))
406
	    {
407
	        $input1 = $postData['input1'];
408
	        $input2 = $postData['input2'];
0 ignored issues
show
Unused Code introduced by
The assignment to $input2 is dead and can be removed.
Loading history...
409
	        $input3 = $postData['input3'];
0 ignored issues
show
Unused Code introduced by
The assignment to $input3 is dead and can be removed.
Loading history...
410
	        $this->view->input1 = $input1;
411
	        //$this->view->answer=$input1 . '/' . $input2  . '/' . $input3;
412
	        try {
413
	            $this->view->answer = 'Answer : ';
414
	            $API = $this->getIdoConn();
415
	            $DB = $this->getUIDatabase();
0 ignored issues
show
Unused Code introduced by
The assignment to $DB is dead and can be removed.
Loading history...
416
417
	            //$hosts = $DB->getServicesByHostGroupid($input1);
418
	            //$this->view->answer .= 'services : '.print_r($hosts,true);
419
	            
420
	            $hosts = $API->getServicesByHostGroupid($input1);
421
	            $this->view->answer .= 'services : '.print_r($hosts,true);
422
	            
423
424
	            
425
	            return;
426
	            $hosts = $API->getHostByIP($input1);
0 ignored issues
show
Unused Code introduced by
$hosts = $API->getHostByIP($input1) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
427
	            $this->view->answer .= 'Host : '. print_r($hosts,true);
428
	            $hosts = $API->getHostGroupByName($input1);
429
	            $this->view->answer .= 'Group : '.print_r($hosts,true);
430
	            $hosts = $API->getServicesByHostid($input1);
431
	            $this->view->answer .= 'service : '.print_r($hosts,true);
432
	            
433
	            /* $hosts = $API->getHostsIPByHostGroup($input1);
434
	            $this->view->answer .= "\n Hostgrp : " . print_r($hosts,true); */
435
	            
436
	        } catch (Exception $e)
437
	        {
438
	            $this->view->answer = "Exception : " . print_r($e);
439
	        }
440
	        
441
	    }
442
	    
443
	}
444
	
445
	protected function prepareTabs()
446
	{
447
		return $this->getTabs()->add('status', array(
448
			'label' => $this->translate('Status'),
449
			'url'   => $this->getModuleConfig()->urlPath() . '/status')
450
		)->add('mib', array(
451
			'label' => $this->translate('MIB Management'),
452
			'url'   => $this->getModuleConfig()->urlPath() . '/status/mib')
453
	    )->add('uimgt', array(
454
	        'label' => $this->translate('UI Configuration'),
455
	        'url'   => $this->getModuleConfig()->urlPath() . '/status/uimgt')
456
        )->add('services', array(
457
			'label' => $this->translate('Services management'),
458
			'url'   => $this->getModuleConfig()->urlPath() . '/status/services')
459
	    )->add('plugins', array(
460
	        'label' => $this->translate('Plugins management'),
461
	        'url'   => $this->getModuleConfig()->urlPath() . '/status/plugins')
462
	    );
463
	} 
464
}
465
466
// TODO : see if useless 
467
class UploadForm extends Form
468
{ 
469
    public function __construct($options = null) 
470
    {
471
        parent::__construct($options);
472
        $this->addElements2();
473
    }
474
475
    public function addElements2()
476
    {
477
        // File Input
478
        $file = new File('mib-file');
479
        $file->setLabel('Mib upload');
480
             //->setAttrib('multiple', null);
481
        $this->addElement($file);
482
		$button = new Submit("upload",array('ignore'=>false));
483
		$this->addElement($button);//->setIgnore(false);
484
    }
485
}
486