-
Notifications
You must be signed in to change notification settings - Fork 174
/
base.py
5684 lines (4795 loc) · 204 KB
/
base.py
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (c) 2014, Palo Alto Networks
#
# Permission to use, copy, modify, and/or 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.
"""Base object classes for inheritence by other classes"""
import base64
import collections
import copy
import datetime
import hashlib
import inspect
import itertools
import re
import sys
import time
import xml.dom.minidom as minidom
import xml.etree.ElementTree as ET
import pan.commit
import pan.xapi
from pan.config import PanConfig
import panos
import panos.errors as err
from panos import (
chunk_instances_for_delete_similar,
isstring,
string_or_list,
updater,
userid,
yesno,
)
logger = panos.getlogger(__name__)
Root = panos.enum("DEVICE", "VSYS", "MGTCONFIG", "PANORAMA", "PANORAMA_VSYS")
SELF = "/%s"
ENTRY = "/entry[@name='%s']"
MEMBER = "/member[text()='%s']"
# PanObject type
class PanObject(object):
"""Base class for all package objects
This class defines an object that can be placed in a tree to generate configuration.
Args:
name (str): The name of this object
Attributes:
uid (str): The unique identifier for this object if it has one. If it
doesn't have one, then this returns the class name.
vsys (str): The vsys id for this object (eg. 'vsys2') or 'shared' if no vsys
"""
XPATH = ""
SUFFIX = None
ROOT = Root.DEVICE
NAME = "name"
CHILDTYPES = ()
CHILDMETHODS = ()
HA_SYNC = True
TEMPLATE_NATIVE = False
_UNKNOWN_PANOS_VERSION = (sys.maxsize, 0, 0)
OPSTATES = {}
def __init__(self, *args, **kwargs):
# Set the 'name' variable
idx_start = 0
if self.NAME is not None:
try:
name = args[0]
idx_start = 1
except IndexError:
name = kwargs.pop(self.NAME, None)
setattr(self, self.NAME, name)
# Initialize other common variables
self.parent = None
self.children = []
# Gather all the variables from the 'variables' class method
# from the args/kwargs into instance variables.
variables = kwargs.pop("variables", None)
if variables is None:
variables = type(self).variables()
# Sort the variables by order
variables = sorted(variables, key=lambda x: x.order)
for idx, var in enumerate(variables, idx_start):
varname = var.variable
try:
# Try to get the variables from 'args' first
varvalue = args[idx]
except IndexError:
# If it's not in args, get it from 'kwargs', or store a None in the variable
try:
varvalue = kwargs.pop(varname)
except KeyError:
# If None was stored in the variable, check if
# there's a default value, and store that instead
if var.default is not None:
setattr(self, varname, var.default)
else:
setattr(self, varname, None)
continue
# For member variables, store a list containing the value instead of the individual value
if var.vartype in ("member", "entry"):
varvalue = panos.string_or_list(varvalue)
# Store the value in the instance variable
setattr(self, varname, varvalue)
self._setups()
def _setups(self):
"""The various setup functions that will be called on object creation."""
funcs = [
"_setup",
"_setup_opstate",
]
for func in funcs:
if hasattr(self, func):
f = getattr(self, func)
if callable(f):
f()
def _setup_opstate(self):
self.opstate = OpStateContainer(self, self.OPSTATES)
def __str__(self):
return self.uid
def __repr__(self):
return "<{0}{1} {2:#x}>".format(
type(self).__name__, " {0}".format(self.uid) if self.uid else "", id(self)
)
@classmethod
def variables(cls):
"""Defines the variables that exist in this object. Override in each subclass."""
return ()
@property
def vsys(self):
"""Return the vsys for this object
Traverses the tree to determine the vsys from a :class:`panos.firewall.Firewall`
or :class:`panos.device.Vsys` instance somewhere before this node in the tree.
Returns:
str: The vsys id (eg. vsys2)
"""
if self.parent is not None:
vsys = self.parent.vsys
if vsys is None and self.ROOT == Root.VSYS:
return getattr(self.parent, "DEFAULT_VSYS", None)
else:
return vsys
@vsys.setter
def vsys(self, value):
raise err.PanDeviceError("Cannot set vsys on non-vsys object")
@property
def uid(self):
"""Returns the unique identifier of this object as a string."""
if hasattr(self, "id"):
return self.id
elif self.NAME is not None:
return str(getattr(self, self.NAME))
else:
return ""
def add(self, child):
"""Add a child node to this node
Args:
child (PanObject): Node to add as a child
Returns:
PanObject: Child node
"""
child.parent = self
self.children.append(child)
return child
def insert(self, index, child):
"""Insert a child node at a specific index
This is useful for ordering or reordering security policy rules
Args:
index (int): The index where the child obj should be inserted
child (PanObject): Node to add as a child
Returns:
PanObject: Child node
"""
child.parent = self
self.children.insert(index, child)
return child
def extend(self, children):
"""Add a list of child nodes to this node
Args:
children (list): List of PanObject instances
"""
for child in children:
child.parent = self
self.children.extend(children)
def pop(self, index):
"""Remove and return the object at an index
Args:
index (int): Index of the object to remove and return
Returns:
PanObject: The object removed from the children of this node
"""
child = self.children.pop(index)
child.parent = None
return child
def remove(self, child):
"""Remove the child from this node
Args:
child (PanObject): Child to remove
"""
self.children.remove(child)
child.parent = None
def remove_by_name(self, name, cls=None):
"""Remove a child node by name
If the class is not specified, then it defaults to type(self).
Args:
name (str): Name of the child node
Keyword Args:
cls (class): Restrict removal to instances of this class
Returns:
PanObject: The removed node, otherwise None
"""
# Get the index of the first matching child
index = self.find_index(name, cls)
if index is not None:
return self.pop(index)
def removeall(self, cls=None):
"""Remove all children of a type
Not recursive.
Args:
cls (class): The class of objects to remove
Returns:
list: List of PanObjects that were removed
"""
if not self.children:
return
if cls is not None:
children = [child for child in self.children if isinstance(child, cls)]
for child in children:
self.children.remove(child)
return children
else:
children = self.children
for child in children:
child.parent = None
self.children = []
return children
def xpath(self, root=None):
"""Return the full xpath for this object
Xpath in the form: parent's xpath + this object's xpath + entry or member if applicable.
Args:
root: The root to use for this object (default: this object's root)
Returns:
str: The full xpath to this object
"""
path = []
p = self
if root is None:
root = self.ROOT
vsys = self.vsys
label = getattr(self, "VSYS_LABEL", "vsys")
while True:
if isinstance(p, PanDevice) and p != self:
# Stop on the first pandevice encountered, unless the
# panos.PanDevice object is the object whose xpath
# was asked for.
# If the object whose xpath we are creating is directly
# attached to a Panorama and the root is PANORAMA
if root == Root.PANORAMA_VSYS:
if p.__class__.__name__ == "Panorama":
root = Root.PANORAMA
else:
root = Root.VSYS
path.insert(0, p.xpath_root(root, vsys, label))
break
elif p.__class__.__name__ == "Predefined":
# Stop on predefined namespace.
path.insert(0, p.XPATH)
break
elif not hasattr(p, "VSYS_LABEL") or p == self:
# Add on the xpath of this object, unless it is a
# device.Vsys, unless the device.Vsys is the object whose
# xpath was asked for.
addon = p.XPATH
if p.SUFFIX is not None:
addon += p.SUFFIX % (p.uid,)
path.insert(0, addon)
if p.__class__.__name__ == "Firewall" and p.parent is not None:
if p.parent.__class__.__name__ == "DeviceGroup":
root = Root.VSYS
p = p.parent
if p is None:
break
if hasattr(p, "VSYS_LABEL"):
# Either panorama.DeviceGroup or device.Vsys.
label = p.VSYS_LABEL
vsys = p.vsys
elif p.__class__.__name__ in ("Template", "TemplateStack"):
if not self.TEMPLATE_NATIVE:
# Hit a template, make sure that the appropriate /config/...
# xpath has been saved.
if not path[0].startswith("/config/"):
if root == Root.PANORAMA_VSYS:
root = Root.VSYS
path.insert(0, self.xpath_root(root, vsys, label))
vsys = p.vsys
root = p.ROOT
return "".join(path)
def xpath_nosuffix(self):
"""Return the xpath without the suffix
This is used by refreshall().
Returns:
str: The xpath without entry or member on the end
"""
if self.SUFFIX is None:
return self.xpath()
else:
return self.xpath_short()
def xpath_short(self, root=None):
"""Return an xpath for this object without the final segment
Xpath in the form: parent's xpath + this object's xpath. Used for set API calls.
Args:
root: The root to use for this object (default: this object's root)
Returns:
str: The xpath without the final segment
"""
xpath = self.xpath(root)
xpath = re.sub(r"/(?=[^/']*'[^']*'[^/']*$|[^/]*$).*$", "", xpath)
return xpath
def xpath_root(self, root_type, vsys, label="vsys"):
if self.parent:
return self.parent.xpath_root(root_type, vsys, label)
def xpath_vsys(self):
if self.parent is not None:
return self.parent.xpath_vsys()
def xpath_panorama(self):
if self.parent is not None:
return self.parent.xpath_panorama()
def _root_xpath_vsys(self, vsys, label="vsys"):
if vsys == "shared":
xpath = "/config/shared"
else:
xpath = "/config/devices/entry[@name='localhost.localdomain']"
xpath += "/{0}/entry[@name='{1}']".format(label, vsys or "vsys1")
return xpath
def element(self, with_children=True, comparable=False):
"""Construct an ElementTree for this PanObject and all its children
Args:
with_children (bool): Include children in element.
comparable (bool): Element will be used in a comparison with another.
Returns:
xml.etree.ElementTree: An ElementTree instance representing the
xml form of this object and its children
"""
root = self._root_element()
variables = self.variables()
for var in variables:
missing_replacement = False
if var.vartype == "none":
value = "nonetype"
else:
value = getattr(self, var.variable)
if value is None:
continue
if var.condition is not None:
condition = var.condition.split(":")
if str(getattr(self, condition[0])) != condition[1]:
continue
path = var.path.split("/")
nextelement = root
for section in path:
if section.find("|") != -1:
# This is an element variable, so create an element containing
# the variables's value
section = re.sub(r"\([\w\d|-]*\)", str(value), section)
# Search for variable replacements in path
matches = re.findall(r"{{(.*?)}}", section)
entryvar = None
# Do variable replacement, ie. {{ }}
for match in matches:
regex = r"{{" + re.escape(match) + r"}}"
# Ignore variables that are None
if getattr(self, match) is None:
missing_replacement = True
break
# Find the discovered replacement in the list of vars
for nextvar in variables:
if nextvar.variable == match:
matchedvar = nextvar
break
if matchedvar.vartype == "entry":
# If it's an 'entry' variable
# XXX: this is using a quick patch. Should handle array-based entry vars better.
entry_value = panos.string_or_list(
getattr(self, matchedvar.variable)
)
section = re.sub(
regex,
matchedvar.path
+ "/"
+ "entry[@name='%s']" % entry_value[0],
section,
)
entryvar = matchedvar
else:
# Not an 'entry' variable
section = re.sub(
regex, getattr(self, matchedvar.variable), section
)
if missing_replacement:
break
found = nextelement.find(section)
if found is not None:
# Existing element
nextelement = found
else:
# Create elements
if entryvar is not None:
# for vartype="entry" with replacement from above
nextelement = ET.SubElement(nextelement, entryvar.path)
nextelement = ET.SubElement(
nextelement,
"entry",
{"name": getattr(self, entryvar.variable)},
)
else:
# for entry vartypes that are empty
if var.vartype == "entry" and not value:
continue
# non-entry vartypes
nextelement = ET.SubElement(nextelement, section)
if missing_replacement:
continue
var._set_inner_xml_tag_text(nextelement, value, comparable)
if with_children:
self.xml_merge(root, self._subelements())
return root
def element_str(self, pretty_print=False):
"""The XML representation of this PanObject and all its children.
Args:
pretty_print (bool): Return the resulting string pretty_printed with indentation.
Returns:
str: XML form of this object and its children
"""
if pretty_print:
raw = ET.tostring(self.element(), encoding="utf-8")
parsed = minidom.parseString(raw)
return parsed.toprettyxml(indent="\t", encoding="utf-8")
return ET.tostring(self.element(), encoding="utf-8")
def _root_element(self):
if self.SUFFIX == ENTRY:
return ET.Element("entry", {"name": self.uid})
elif self.SUFFIX == MEMBER:
root = ET.Element("member")
root.text = self.uid
return root
elif self.SUFFIX is None:
# Get right of last / in xpath
tag = self.XPATH.rsplit("/", 1)[-1]
return ET.Element(tag)
raise ValueError(
"No suffix or XPATH defined for {0}".format(self.__class__.__name__)
)
def _subelements(self, comparable=False):
"""Generator function to turn children into XML objects.
Yields:
xml.etree.ElementTree: The next child as an ``ElementTree`` object.
"""
for child in self.children:
root = self._root_element()
# Paths have a leading slash to get rid of
xpath_sections = child.XPATH.split("/")[1:]
if child.SUFFIX is None:
# If not suffix, remove the last xpath section
# because it will be part of the element
xpath_sections = xpath_sections[:-1]
e = root
for path in xpath_sections:
if path == "entry[@name='localhost.localdomain']":
e = ET.SubElement(e, "entry", {"name": "localhost.localdomain"})
else:
e = ET.SubElement(e, path)
e.append(child.element(comparable=comparable))
yield root
def _check_child_methods(self, method):
if method in self.CHILDMETHODS:
getattr(self, "child_" + method)()
for child in self.children:
child._check_child_methods(method)
def equal(self, panobject, force=False, compare_children=True):
"""Compare this object to another object
Equality of the objects is determined by the XML they generate, not by the
values of their variables.
Args:
panobject (PanObject): The object to compare with this object
force (bool): Do not raise a PanObjectError if the objects are different classes
compare_children (bool): Not supported in this object, use True
Raises:
PanObjectError: Raised if the objects are different types that
would not normally be comparable
Returns:
bool: True if the XML of the objects is equal, False if not
"""
if not panobject:
return False
if not force and type(self) != type(panobject):
raise err.PanObjectError(
"Object {0} is not comparable to {1}".format(
type(self), type(panobject)
)
)
return self.element_str() == panobject.element_str()
def apply(self):
"""Apply this object to the device, replacing any existing object of the same name
**Modifies the live device**
"""
device = self.nearest_pandevice()
logger.debug(
device.id + ': apply called on %s object "%s"' % (type(self), self.uid)
)
device.set_config_changed()
if self.HA_SYNC:
device.active().xapi.edit(
self.xpath(), self.element_str(), retry_on_peer=self.HA_SYNC
)
else:
device.xapi.edit(
self.xpath(), self.element_str(), retry_on_peer=self.HA_SYNC
)
for child in self.children:
child._check_child_methods("apply")
def create(self):
"""Create this object on the device
**Modifies the live device**
This method is nondestructive. If the object exists, the variables are added to the device
without changing existing variables on the device. If a variables already exists on the
device and this object has a different value, the value on the firewall is changed to
the value in this object.
"""
device = self.nearest_pandevice()
logger.debug(
device.id + ': create called on %s object "%s"' % (type(self), self.uid)
)
device.set_config_changed()
element = self.element_str()
if self.HA_SYNC:
device.active().xapi.set(
self.xpath_short(), element, retry_on_peer=self.HA_SYNC
)
else:
device.xapi.set(self.xpath_short(), element, retry_on_peer=self.HA_SYNC)
for child in self.children:
child._check_child_methods("create")
def delete(self):
"""Delete this object from the firewall
**Modifies the live device**
"""
device = self.nearest_pandevice()
logger.debug(
device.id + ': delete called on %s object "%s"' % (type(self), self.uid)
)
device.set_config_changed()
for child in self.children:
child._check_child_methods("delete")
if self.HA_SYNC:
device.active().xapi.delete(self.xpath(), retry_on_peer=self.HA_SYNC)
else:
device.xapi.delete(self.xpath(), retry_on_peer=self.HA_SYNC)
if self.parent is not None:
self.parent.remove(self)
def update(self, variable):
"""Change the value of a variable
**Modifies the live device**
Do not attempt this on an element variable (|) or variable with replacement {{}}
If the variable's value is None, then a delete API call is attempted.
Args:
variable (str): The name of an instance variable to update on the device
"""
device = self.nearest_pandevice()
logger.debug(
device.id
+ ': update called on %s object "%s" and variable "%s"'
% (type(self), self.uid, variable)
)
device.set_config_changed()
path, attr, value, var_path = self._get_param_specific_info(variable)
if var_path.vartype == "attrib":
raise NotImplementedError("Cannot update 'attrib' style params")
xpath = "{0}/{1}".format(self.xpath(), path)
if value is None:
# Value is None, so delete it from the live device.
device.xapi.delete(xpath, retry_on_peer=self.HA_SYNC)
else:
# Variable has a new value.
element_tag = path.split("/")[-1]
element = ET.Element(element_tag)
var_path._set_inner_xml_tag_text(element, value)
device.xapi.edit(
xpath,
ET.tostring(element, encoding="utf-8"),
retry_on_peer=self.HA_SYNC,
)
def rename(self, new_name):
"""Change the name of this object.
**Modifies the live device**
NOTE: This does not change any references that may exist in your
pan-os-python object hierarchy, but it does update the name of the
object itself.
Args:
new_name (str): The new UID for this object.
"""
dev = self.nearest_pandevice()
logger.debug(
'{0}: rename called on {1} object "{2}"'.format(
dev.id, type(self), self.uid
)
)
dev.set_config_changed()
dev.xapi.rename(self.xpath(), new_name)
setattr(self, self.NAME, new_name)
def move(self, location, ref=None, update=True):
"""Moves the current object.
**Modifies the live device**
This is useful for stuff like moving one security policy above another.
If this object's parent is a rulebase object, then this object is also
moved to the appropriate position in the local pan-os-python object tree.
Args:
location (str): Any of the following: before, after, top, or bottom
ref (PanObject/str): If location is "before" or "after", move this object before/after the ref object. If this is a string, then the string should just be the name of the object.
update (bool): If this is set to False, then only move this object in the pan-os-python object tree, do not actually perform the MOVE operation on the live device. Note that in order for this object to be moved in the pan-os-python object tree, the parent object must be a rulebase object.
Raises:
ValueError
"""
d = self.nearest_pandevice()
dst = None
new_index = None
rbs = ("Rulebase", "PreRulebase", "PostRulebase")
ref_locs = ("before", "after")
standalone_locs = ("top", "bottom")
parent = self.parent
# Sanity checks + determine move location.
if parent is None:
raise ValueError("No parent for object {0}".format(self.uid))
elif location in standalone_locs:
if ref is not None:
raise ValueError("ref should be None for {0} move".format(location))
if parent.__class__.__name__ in rbs:
new_index = 0 if location == "top" else len(parent.children) - 1
elif location in ref_locs:
if ref is None:
raise ValueError("ref must be specified for {0} move".format(location))
dst = str(ref)
if self.uid == dst:
raise ValueError("Cannot move rule in relation to self")
if parent.__class__.__name__ in rbs:
offset = 0
for i, x in enumerate(parent.children):
if self == x:
offset = 1
elif type(x) == type(self) and x.uid == dst:
new_index = (
i - offset if location == "before" else i - offset + 1
)
break
else:
raise ValueError(
"Location must be one of: {0} or {1}".format(ref_locs, standalone_locs)
)
logger.debug('{0}: move called on {1} "{2}"'.format(d.id, type(self), self.uid))
# Move the rule in the pan-os-python object tree, if applicable.
if new_index is not None:
parent.remove(self)
parent.insert(new_index, self)
# Done if we're not updating.
if not update:
return
# Perform the move on the nearest pandevice.
d.set_config_changed()
d.xapi.move(self.xpath(), location, dst)
def _get_param_specific_info(self, variable):
"""Gets a tuple of info for the given parameter.
This is to aid in things like updates or refreshes of a specific
parameter attached to this PanObject / VersionedPanObject.
Returns:
A three element tuple of the variable's xpath (str), the value of
the variable, and the full ``VarPath`` or ``ParamPath`` object that
is responsible for handling this variable.
Raises:
PanDeviceError: If the variable specified does not exist.
"""
variables = type(self).variables()
value = getattr(self, variable)
# Get the requested variable from the class' variables tuple
var = next((x for x in variables if x.variable == variable), None)
if var is None:
raise err.PanDeviceError(
"Variable %s does not exist in variable tuple" % variable
)
varpath = var.path
# Do replacements on variable path
if varpath.find("|") != -1:
# This is an element variable, so create an element containing
# the variables's value
varpath = re.sub(r"\([\w\d|-]*\)", str(value), varpath)
# Search for variable replacements in path
matches = re.findall(r"{{(.*?)}}", varpath)
entryvar = None
# Do variable replacement, ie. {{ }}
for match in matches:
regex = r"{{" + re.escape(match) + r"}}"
# Ignore variables that are None
if getattr(self, match) is None:
raise ValueError(
"While updating variable %s, missing replacement variable %s in path"
% (variable, match)
)
# Find the discovered replacement in the list of vars
for nextvar in variables:
if nextvar.variable == match:
matchedvar = nextvar
break
if matchedvar.vartype == "entry":
# If it's an 'entry' variable
# XXX: this is using a quick patch. Should handle array-based entry vars better.
entry_value = panos.string_or_list(getattr(self, matchedvar.variable))
varpath = re.sub(
regex,
matchedvar.path + "/" + "entry[@name='%s']" % entry_value[0],
varpath,
)
else:
# Not an 'entry' variable
varpath = re.sub(regex, getattr(self, matchedvar.variable), varpath)
# For vartype=attrib params, we need the containing XML element.
attr = None
if var.vartype == "attrib":
tokens = varpath.rsplit("/", 1)
attr = tokens[-1]
if len(tokens) == 1:
varpath = None
else:
varpath = tokens[0]
return (varpath, attr, value, var)
def refresh(
self, running_config=False, refresh_children=True, exceptions=True, xml=None
):
"""Refresh all variables and child objects from the device.
Args:
running_config (bool): Set to True to refresh from the running
configuration (Default: False)
xml (xml.etree.ElementTree): XML from a configuration to use
instead of refreshing from a live device
refresh_children (bool): Set to False to prevent refresh of child
objects (Default: True)
exceptions (bool): Set to False to prevent exceptions on failure
(Default: True)
"""
# Either retrieve the xml or use what is passed in
if xml is None:
xml = self._refresh_xml(running_config, exceptions, refresh_children)
else:
logger.debug(
'refresh called using xml on {0} object "{1}"'.format(
type(self), self.uid
)
)
if xml is None:
return
# Refresh this object
if hasattr(self, "parse_xml"):
# Versioned object
self.parse_xml(xml)
else:
# Classic object
variables = type(self)._parse_xml(xml)
for var, value in variables.items():
setattr(self, var, value)
# Refresh children objects if requested
if refresh_children:
self._refresh_children(xml=xml)
def refresh_variable(self, variable, running_config=False, exceptions=False):
"""Refresh a single variable of an object.
**Don't use for variables with replacements or selections in path.**
Args:
variable (str): Variable name to refresh.
running_config (bool): Set to True to refresh from the running
configuration (Default: False)
exceptions (bool): Set to False to prevent exceptions on failure
(Default: True)
Returns:
New value of the refreshed variable.
Raises:
PanObjectMissing: When the object this variable is connected to
does not exist.
"""
device = self.nearest_pandevice()
msg = '{0}: refresh_variable({1}) called on {2} object "{3}"'
logger.debug(msg.format(device.id, variable, self.__class__.__name__, self.uid))
path, attr, value, var_path = self._get_param_specific_info(variable)
xpath = self.xpath()
if path is not None:
xpath += "/{0}".format(path)
err_msg = "Object doesn't exist: {0}".format(xpath)
setattr(self, variable, [] if var_path.vartype in ("member", "entry") else None)
# Query to get the variable's XML from the device
if running_config:
api_action = device.xapi.show
else:
api_action = device.xapi.get
try:
root = api_action(xpath, retry_on_peer=self.HA_SYNC)
except (pan.xapi.PanXapiError, err.PanNoSuchNode) as e:
if exceptions:
raise err.PanObjectMissing(err_msg, pan_device=device)
return
# Determine the first element to look for in the XML
lasttag = xpath.rsplit("/", 1)[-1]
obj = root.find("result/" + lasttag)
if obj is None:
if exceptions:
raise err.PanObjectMissing(err_msg, pan_device=device)
return
if hasattr(var_path, "parse_value_from_xml_last_tag"):
# Versioned class
settings = {}
var_path.parse_value_from_xml_last_tag(obj, settings, attr)
setattr(self, variable, settings.get(variable))
else:
# Classic class
# Rebuild the elements that are lost by refreshing the
# variable directly
sections = xpath.split("/")[:-1]
root = ET.Element("root")
next_element = root
for section in sections:
next_element = ET.SubElement(next_element, section)
next_element.append(obj)
# Refresh the requested variable
variables = type(self)._parse_xml(root)
for var, value in variables.items():
if var == variable:
setattr(self, var, value)
return getattr(self, variable)
def _refresh_children(self, running_config=False, xml=None):
# Retrieve the xml if we weren't given it