Skip to content

Instantly share code, notes, and snippets.

@dpino
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpino/1d9c72260019927cbf21 to your computer and use it in GitHub Desktop.
Save dpino/1d9c72260019927cbf21 to your computer and use it in GitHub Desktop.
Create basic Snabb Switch app
#!/usr/bin/env luajit
local main_template = [=[
local config = require("core.config")
local app = require("core.app")
local link = require("core.link")
local pcap = require("apps.pcap.pcap")
local <?= app_name ?> = require("<?= basename ?>.<?= app_name ?>")
function run (parameters)
if not (#parameters == 2) then
error("Usage: <?= basename ?>.<?= app_name ?> <input.pcap> <output.pcap>")
end
local input = parameters[1]
local output = parameters[2]
local c = config.new()
config.app(c, "incoming", pcap.PcapReader, input)
config.app(c, "<?= app_name ?>", <?= app_name ?>.<?= app_name ?>)
config.app(c, "outgoing", pcap.PcapWriter, output)
config.link(c, "incoming.output -> <?= app_name ?>.input")
config.link(c, "<?= app_name ?>.output -> outgoing.input")
app.configure(c)
app.main({duration = 1, report = { showlinks = true}})
end
run(main.parameters)
]=]
local app_template = [=[
module(...,package.seeall)
<?= app_name ?> = {}
function <?= app_name ?>:new()
local result = { packet_counter = 0 }
return setmetatable(result, { __index = <?= app_name ?> })
end
function <?= app_name ?>:push(p)
local i = assert(self.input.input, "input port not found")
local o = assert(self.output.output, "output port not found")
while not link.empty(i) and not link.full(o) do
self:process_packet(i, o)
self.packet_counter = self.packet_counter + 1
end
end
function <?= app_name ?>:process_packet(i, o)
local p = link.receive(i)
if self.packet_counter % 2 == 0 then
link.transmit(o, p)
else
packet.free(p)
end
end
]=]
local function execute(command)
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
end
local function write(content, filename)
local f = io.open(filename, "w+")
f:write(content)
f:close()
end
if #arg == 0 then
error("snabb-create-app basename app_name")
end
local env = {
basename = arg[1],
app_name = arg[2]
}
local function replace(content, env)
for k,v in pairs(env) do
content = content:gsub("<%?=%s"..k.."%s%?>", v)
end
return content
end
local app_path = env.basename:gsub("%.", "%/")
execute(("mkdir -p %s"):format(app_path))
write(replace(main_template, env), app_path.."/main.lua")
write(replace(app_template, env), ("%s/%s.lua"):format(app_path, env.app_name))
print("Created app '"..app_path.."'")
-- Print how to use
local input = "apps/packet_filter/samples/v6.pcap"
local output = "/tmp/output.pcap"
print("Run 'sudo make && sudo ./snabb snsh "..app_path.."/main.lua "..input.." "..output.."'")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment