Skip to content

Instantly share code, notes, and snippets.

@dpino

dpino/snabb-create-app.lua

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.