Skip to content

Commit

Permalink
introduced Queue/Stack itervalues
Browse files Browse the repository at this point in the history
This commit introduces the possibility to iterate over all elements of a Queue/Stack.
To avoid infinite loop, a maximum of MAX_ENTRIES pop() are performed

Signed-off-by: Simone Magnani <[email protected]>
  • Loading branch information
smagnani96 authored and yonghong-song committed Apr 29, 2021
1 parent f41f378 commit 226816d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
15 changes: 15 additions & 0 deletions src/python/bcc/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1157,6 +1157,8 @@ def __init__(self, bpf, map_id, map_fd, leaftype):
self.Leaf = leaftype
self.ttype = lib.bpf_table_type_id(self.bpf.module, self.map_id)
self.flags = lib.bpf_table_flags_id(self.bpf.module, self.map_id)
self.max_entries = int(lib.bpf_table_max_entries_id(self.bpf.module,
self.map_id))

def leaf_sprintf(self, leaf):
buf = ct.create_string_buffer(ct.sizeof(self.Leaf) * 8)
Expand Down Expand Up @@ -1193,3 +1195,16 @@ def peek(self):
if res < 0:
raise KeyError("Could not peek table")
return leaf

def itervalues(self):
# to avoid infinite loop, set maximum pops to max_entries
cnt = self.max_entries
while cnt:
try:
yield(self.pop())
cnt -= 1
except KeyError:
return

def values(self):
return [value for value in self.itervalues()]
26 changes: 20 additions & 6 deletions tests/python/test_queuestack.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")

from bcc import BPF
import os
import distutils.version
import ctypes as ct
import random
import time
import subprocess

from bcc import BPF

from unittest import main, TestCase, skipUnless

def kernel_version_ge(major, minor):
Expand All @@ -22,8 +21,9 @@ def kernel_version_ge(major, minor):
return False
return True

@skipUnless(kernel_version_ge(4,20), "requires kernel >= 4.20")
class TestQueueStack(TestCase):
@skipUnless(kernel_version_ge(4,20), "requires kernel >= 4.20")

def test_stack(self):
text = """
BPF_STACK(stack, u64, 10);
Expand All @@ -48,9 +48,15 @@ def test_stack(self):
with self.assertRaises(KeyError):
stack.pop()

for i in reversed(range(10)):
stack.push(ct.c_uint64(i))

# testing itervalues()
for i,v in enumerate(stack.values()):
assert v.value == i

b.cleanup()

@skipUnless(kernel_version_ge(4,20), "requires kernel >= 4.20")
def test_queue(self):
text = """
BPF_QUEUE(queue, u64, 10);
Expand All @@ -75,7 +81,15 @@ def test_queue(self):
with self.assertRaises(KeyError):
queue.pop()

for i in range(10):
queue.push(ct.c_uint64(i))

# testing itervalues()
for i,v in enumerate(queue.values()):
assert v.value == i

b.cleanup()


if __name__ == "__main__":
main()

0 comments on commit 226816d

Please sign in to comment.