This repository has been archived by the owner on Jun 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
servicegroup-merger.php
546 lines (458 loc) · 17 KB
/
servicegroup-merger.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
<?php
/*
* Copyright (c) 2014-2017 Christophe Painchaud <shellescape _AT_ gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
echo "\n***********************************************\n";
echo "*********** ".basename(__FILE__)." UTILITY **********\n\n";
set_include_path( dirname(__FILE__).'/../'. PATH_SEPARATOR . get_include_path() );
require_once("lib/panconfigurator.php");
require_once(dirname(__FILE__).'/common/misc.php');
$supportedArguments = Array();
$supportedArguments[] = Array('niceName' => 'in', 'shortHelp' => 'input file ie: in=config.xml', 'argDesc' => '[filename]');
$supportedArguments[] = Array('niceName' => 'out', 'shortHelp' => 'output file to save config after changes. Only required when input is a file. ie: out=save-config.xml', 'argDesc' => '[filename]');
$supportedArguments[] = Array(
'niceName' => 'DupAlgorithm',
'shortHelp' =>
"Specifies how to detect duplicates:\n".
" - SameMembers: groups holding same members replaced by the one picked first (default)\n".
" - SamePortMapping: groups resolving the same port mapping coverage will be replaced by the one picked first\n".
" - WhereUsed: groups used exactly in the same location will be merged into 1 single groups with all members together\n",
'argDesc'=> 'SamePorts|WhereUsed');
$supportedArguments[] = Array('niceName' => 'Location', 'shortHelp' => 'specify if you want to limit your query to a VSYS/DG. By default location=shared for Panorama, =vsys1 for PANOS', 'argDesc' => 'vsys1|shared|dg1');
$supportedArguments[] = Array('niceName' => 'mergeCountLimit', 'shortHelp' => 'stop operations after X objects have been merged', 'argDesc'=> '100');
$supportedArguments[] = Array('niceName' => 'pickFilter', 'shortHelp' => 'specify a filter a pick which object will be kept while others will be replaced by this one', 'argDesc' => '(name regex /^g/)');
$supportedArguments[] = Array('niceName' => 'excludeFilter', 'shortHelp' => 'specify a filter to exclude objects from merging process entirely', 'argDesc' => '(name regex /^g/)');
$supportedArguments[] = Array('niceName' => 'allowMergingWithUpperLevel', 'shortHelp' => 'when this argument is specified, it instructs the script to also look for duplicates in upper level');
$supportedArguments[] = Array('niceName' => 'help', 'shortHelp' => 'this message');
$usageMsg = PH::boldText('USAGE: ')."php ".basename(__FILE__)." in=inputfile.xml [out=outputfile.xml] location=shared [DupAlgorithm=SameMembers] ['pickFilter=(name regex /^H-/)'] ...";
prepareSupportedArgumentsArray($supportedArguments);
PH::processCliArgs();
$nestedQueries = Array();
// check that only supported arguments were provided
foreach ( PH::$args as $index => &$arg )
{
if( !isset($supportedArguments[$index]) )
{
if( strpos($index,'subquery') === 0 )
{
$nestedQueries[$index] = &$arg;
continue;
}
display_error_usage_exit("unsupported argument provided: '$index'");
}
}
if( isset(PH::$args['help']) )
{
display_usage_and_exit();
}
if( !isset(PH::$args['in']) )
display_error_usage_exit(' "in=" argument is missing');
if( !isset(PH::$args['location']) )
display_error_usage_exit(' "location=" argument is missing');
$location = PH::$args['location'];
if( isset(PH::$args['mergecountlimit']) )
$mergeCountLimit = PH::$args['mergecountlimit'];
else
$mergeCountLimit = false;
//
// What kind of config input do we have.
// File or API ?
//
// <editor-fold desc=" **** input method validation and PANOS vs Panorama auto-detect ****" defaultstate="collapsed" >
$configInput = PH::processIOMethod(PH::$args['in'], true);
$xmlDoc = null;
if( $configInput['status'] == 'fail' )
{
fwrite(STDERR, "\n\n**ERROR** " . $configInput['msg'] . "\n\n");exit(1);
}
if( $configInput['type'] == 'file' )
{
$apiMode = false;
if( !file_exists($configInput['filename']) )
derr("file '{$configInput['filename']}' not found");
$xmlDoc = new DOMDocument();
echo " - Reading XML file from disk... ";
if( ! $xmlDoc->load($configInput['filename'], XML_PARSE_BIG_LINES) )
derr("error while reading xml config file");
echo "OK!\n";
}
elseif ( $configInput['type'] == 'api' )
{
$apiMode = true;
echo " - Downloading config from API... ";
$xmlDoc = $configInput['connector']->getCandidateConfig();
echo "OK!\n";
}
else
derr('not supported yet');
//
// Determine if PANOS or Panorama
//
$xpathResult = DH::findXPath('/config/devices/entry/vsys', $xmlDoc);
if( $xpathResult === FALSE )
derr('XPath error happened');
if( $xpathResult->length <1 )
$configType = 'panorama';
else
$configType = 'panos';
unset($xpathResult);
if( $configType == 'panos' )
$panc = new PANConf();
else
$panc = new PanoramaConf();
echo " - Detected platform type is '{$configType}'\n";
if( $configInput['type'] == 'api' )
$panc->connector = $configInput['connector'];
//
// load the config
//
echo " - Loading configuration through PAN-Configurator library... ";
$loadStartMem = memory_get_usage(true);
$loadStartTime = microtime(true);
$panc->load_from_domxml($xmlDoc);
$loadEndTime = microtime(true);
$loadEndMem = memory_get_usage(true);
$loadElapsedTime = number_format( ($loadEndTime - $loadStartTime), 2, '.', '');
$loadUsedMem = convert($loadEndMem - $loadStartMem);
echo "OK! ($loadElapsedTime seconds, $loadUsedMem memory)\n";
// --------------------
// </editor-fold>
if( !$apiMode )
{
if( !isset(PH::$args['out']) )
display_error_usage_exit(' "out=" argument is missing');
$outputfile = PH::$args['out'];
// destroy destination file if it exists
if( file_exists($outputfile) && is_file($outputfile) )
unlink($outputfile);
}
if( $location == 'shared' )
{
$store = $panc->serviceStore;
$parentStore = null;
}
else
{
$findLocation = $panc->findSubSystemByName($location);
if( $findLocation === null )
derr("cannot find DeviceGroup/VSYS named '{$location}', check case or syntax");
$store = $findLocation->serviceStore;
$parentStore = $findLocation->owner->serviceStore;
}
if( $panc->isPanorama() )
{
if( $location == 'shared' )
$childDeviceGroups = $panc->deviceGroups;
else
$childDeviceGroups = $findLocation->childDeviceGroups(true);
}
$pickFilter = null;
if( isset(PH::$args['pickfilter']) )
{
$pickFilter = new RQuery('service');
$errMsg = '';
if( $pickFilter->parseFromString(PH::$args['pickfilter'], $errMsg) === FALSE )
derr("invalid pickFilter was input: ".$errMsg);
echo " - pickFilter was input: ";
$pickFilter->display();
echo "\n";
}
$excludeFilter = null;
if( isset(PH::$args['excludefilter']) )
{
$excludeFilter = new RQuery('service');
$errMsg = '';
if( $excludeFilter->parseFromString(PH::$args['excludefilter'], $errMsg) === FALSE )
derr("invalid pickFilter was input: ".$errMsg);
echo " - excludeFilter was input: ";
$excludeFilter->display();
echo "\n";
}
$upperLevelSearch = false;
if( isset(PH::$args['allowmergingwithupperlevel']) )
$upperLevelSearch = true;
if( isset(PH::$args['dupalgorithm']) )
{
$dupAlg = strtolower(PH::$args['dupalgorithm']);
if( $dupAlg != 'samemembers' && $dupAlg != 'sameportmapping' && $dupAlg != 'whereused')
display_error_usage_exit('unsupported value for dupAlgorithm: '.PH::$args['dupalgorithm']);
}
else
$dupAlg = 'samemembers';
echo " - upper level search status : ".boolYesNo($upperLevelSearch)."\n";
echo " - location '{$location}' found\n";
echo " - found {$store->count()} service Objects\n";
echo " - DupAlgorithm selected: {$dupAlg}\n";
echo " - computing ServiceGroup hash database ... ";
sleep(1);
/**
* @param ServiceGroup $object
* @return string
*/
if( $dupAlg == 'samemembers' )
$hashGenerator = function($object)
{
/** @var ServiceGroup $object */
$value = '';
$members = $object->members();
usort($members, '__CmpObjName');
foreach( $members as $member )
{
$value .= './.'.$member->name();
}
return $value;
};
elseif( $dupAlg == 'sameportmapping' )
$hashGenerator = function($object)
{
/** @var ServiceGroup $object */
$value = '';
$mapping = $object->dstPortMapping();
$value = $mapping->mappingToText();
if( count($mapping->unresolved) > 0 )
{
ksort($mapping->unresolved);
$value .= '//unresolved:/';
foreach($mapping->unresolved as $unresolvedEntry)
$value .= $unresolvedEntry->name().'.%.';
}
return $value;
};
elseif( $dupAlg == 'whereused' )
$hashGenerator = function($object)
{
if( $object->countReferences() == 0 )
return null;
/** @var ServiceGroup $object */
$value = $object->getRefHashComp();
return $value;
};
else
derr("unsupported dupAlgorithm");
//
// Building a hash table of all service objects with same value
//
if( $upperLevelSearch)
$objectsToSearchThrough = $store->nestedPointOfView();
else
$objectsToSearchThrough = $store->serviceGroups();
$hashMap = Array();
$upperHashMap = Array();
foreach( $objectsToSearchThrough as $object )
{
if( !$object->isGroup() )
continue;
if( $excludeFilter !== null && $excludeFilter->matchSingleObject( Array('object' =>$object, 'nestedQueries'=>&$nestedQueries) ) )
continue;
$skipThisOne = false;
// Object with descendants in lower device groups should be excluded
if( $panc->isPanorama() )
{
foreach( $childDeviceGroups as $dg )
{
if( $dg->serviceStore->find($object->name(), null, FALSE) !== null )
{
$skipThisOne = true;
break;
}
}
if( $skipThisOne )
continue;
}
$value = $hashGenerator($object);
if( $value === null )
continue;
if( $object->owner === $store )
{
$hashMap[$value][] = $object;
if( $parentStore !== null )
{
$findAncestor = $parentStore->find($object->name(), null, true);
if( $findAncestor !== null )
$object->ancestor = $findAncestor;
}
}
else
$upperHashMap[$value][] = $object;
}
//
// Hashes with single entries have no duplicate, let's remove them
//
$countConcernedObjects = 0;
foreach( $hashMap as $index => &$hash )
{
if( count($hash) == 1 && !isset($upperHashMap[$index]) && !isset(reset($hash)->ancestor) )
{
//echo "\nancestor not found for ".reset($hash)->name()."\n";
unset($hashMap[$index]);
}
else
$countConcernedObjects += count($hash);
}
unset($hash);
echo "OK!\n";
echo " - found ".count($hashMap)." duplicate values totalling {$countConcernedObjects} groups which are duplicate\n";
echo "\n\nNow going after each duplicates for a replacement\n";
$countRemoved = 0;
foreach( $hashMap as $index => &$hash )
{
echo "\n";
if( $dupAlg == 'sameportmapping')
{
echo " - value '{$index}'\n";
}
$setList = Array();
foreach( $hash as $object )
{
/** @var Service $object */
$setList[] = PH::getLocationString($object->owner->owner).'/'.$object->name();
}
echo " - duplicate set : '".PH::list_to_string($setList)."'\n";
$pickedObject = null;
if( $pickFilter !== null )
{
if( isset($upperHashMap[$index]) )
{
foreach( $upperHashMap[$index] as $object )
{
if( $pickFilter->matchSingleObject( Array('object' =>$object, 'nestedQueries'=>&$nestedQueries) ) )
{
$pickedObject = $object;
break;
}
}
if( $pickedObject === null )
$pickedObject = reset($upperHashMap[$index]);
echo " * using object from upper level : '{$pickedObject->name()}'\n";
}
else
{
foreach( $hash as $object )
{
if( $pickFilter->matchSingleObject( Array('object' =>$object, 'nestedQueries'=>&$nestedQueries) ) )
{
$pickedObject = $object;
break;
}
}
if( $pickedObject === null )
$pickedObject = reset($hash);
echo " * keeping object '{$pickedObject->name()}'\n";
}
}
else
{
if( isset($upperHashMap[$index]) )
{
$pickedObject = reset($upperHashMap[$index]);
echo " * using object from upper level : '{$pickedObject->name()}'\n";
}
else
{
$pickedObject = reset($hash);
echo " * keeping object '{$pickedObject->name()}'\n";
}
}
// Merging loop finally!
foreach( $hash as $object)
{
/** @var ServiceGroup $object */
if( isset($object->ancestor) )
{
$ancestor = $object->ancestor;
/** @var ServiceGroup $ancestor */
if( $upperLevelSearch && $ancestor->isGroup() )
{
if( $hashGenerator($object) == $hashGenerator($ancestor) )
{
echo " - group '{$object->name()}' merged with its ancestor, deleting this one... ";
$object->replaceMeGlobally($ancestor);
if( $apiMode )
$object->owner->API_remove($object);
else
$object->owner->remove($object);
echo "OK!\n";
if( $pickedObject === $object )
$pickedObject = $ancestor;
$countRemoved++;
if( $mergeCountLimit !== FALSE && $countRemoved >= $mergeCountLimit )
{
echo "\n *** STOPPING MERGE OPERATIONS NOW SINCE WE REACHED mergeCountLimit ({$mergeCountLimit})\n";
break 2;
}
continue;
}
}
echo " - group '{$object->name()}' cannot be merged because it has an ancestor\n";
continue;
}
if( $object === $pickedObject )
continue;
if( $dupAlg == 'whereused' )
{
echo " - merging '{$object->name()}' members into '{$pickedObject->name()}': \n";
foreach( $object->members() as $member )
{
echo " - adding member '{$member->name()}'... ";
if( $apiMode )
$pickedObject->API_addMember($member);
else
$pickedObject->addMember($member);
echo " OK!\n";
}
echo " - now removing '{$object->name()} from where it's used\n";
if( $apiMode )
{
$object->API_removeWhereIamUsed(TRUE, 6);
echo " - deleting '{$object->name()}'... ";
$object->owner->API_remove($object);
echo "OK!\n";
}
else
{
$object->removeWhereIamUsed(TRUE, 6);
echo " - deleting '{$object->name()}'... ";
$object->owner->remove($object);
echo "OK!\n";
}
}
else
{
echo " - replacing '{$object->_PANC_shortName()}' ...\n";
$object->__replaceWhereIamUsed($apiMode, $pickedObject, true, 5);
echo " - deleting '{$object->_PANC_shortName()}'\n";
if( $apiMode )
{
//true flag needed for nested groups in a specific constellation
$object->owner->API_remove($object, true);
}
else
{
$object->owner->remove($object, true);
}
}
$countRemoved++;
if( $mergeCountLimit !== FALSE && $countRemoved >= $mergeCountLimit )
{
echo "\n *** STOPPING MERGE OPERATIONS NOW SINCE WE REACHED mergeCountLimit ({$mergeCountLimit})\n";
break 2;
}
}
}
echo "\n\nDuplicates removal is now done. Number of objects after cleanup: '{$store->countServiceGroups()}' (removed {$countRemoved} groups)\n\n";
echo "\n\n***********************************************\n\n";
echo "\n\n";
if( !$apiMode )
$panc->save_to_file($outputfile);
echo "\n************* END OF SCRIPT ".basename(__FILE__)." ************\n\n";