Skip to content

Commit

Permalink
feat(PanDevice): add is_ready() (#532)
Browse files Browse the repository at this point in the history
* feat(PanDevice): add `is_ready()`
  • Loading branch information
shinmog committed Nov 8, 2023
1 parent 8f52450 commit a6b018e
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ format:

check-format:
isort --recursive --atomic --check-only panos
black --check .
black --check --diff .

test:
pytest
Expand Down
33 changes: 33 additions & 0 deletions panos/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5589,3 +5589,36 @@ def whoami(self):

if name is not None and is_self:
return name

def is_ready(self, minutes=None, seconds=None):
"""Runs "show chassis-ready" until the PAN-OS management plane is up.
Args:
minutes (int): The number of minutes to wait before giving up.
seconds (int): The number of seconds to wait before giving up.
Returns:
True if PAN-OS is ready, or False if a timeout was reached.
"""
end = None
if minutes is not None or seconds is not None:
end = datetime.datetime.now() + datetime.timedelta(
minutes=minutes or 0, seconds=seconds or 0,
)

while True:
response = None
try:
response = self.op("show chassis-ready")
except (err.PanURLError, pan.xapi.PanXapiError, err.PanDeviceXapiError):
pass
else:
ready_status = response.find(".//result").text.strip()
if ready_status.lower() == "yes":
return True

if end is not None and datetime.datetime.now() >= end:
return False

# Device isn't up yet, retry after sleeping.
time.sleep(2)
30 changes: 30 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1620,5 +1620,35 @@ def test_delete_extreme_members(self):
self.assertTrue(dev.xapi.delete.call_count > 2)


class TestIsReady(unittest.TestCase):
@mock.patch("time.sleep")
def test_ok(self, mocksleep):
fw = Base.PanDevice("127.0.0.1", "admin", "secret", api_key="apikey")
fw.xapi.op = mock.Mock(
side_effect=[
Err.PanURLError,
pan.xapi.PanXapiError,
Err.PanXapiError,
ET.fromstring("<response><result>yes</result></response>"),
ValueError,
],
)

ans = fw.is_ready()

assert ans == True
assert mocksleep.call_count == 3

@mock.patch("time.sleep")
def test_times_out(self, mocksleep):
fw = Base.PanDevice("127.0.0.1", "admin", "secret", api_key="apikey")
fw.xapi.op = mock.Mock(side_effect=[Err.PanURLError, ValueError,],)

ans = fw.is_ready(seconds=0)

assert ans == False
assert mocksleep.call_count == 0


if __name__ == "__main__":
unittest.main()

0 comments on commit a6b018e

Please sign in to comment.