You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lsyncd/lsyncd.lua

6573 lines
114 KiB

--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- lsyncd.lua Live (Mirror) Syncing Demon
--
-- This is the "runner" part of Lsyncd. It containts all its high-level logic.
-- It works closely together with the Lsyncd core in lsyncd.c. This means it
-- cannot be runned directly from the standard lua interpreter.
--
-- This code assumes your editor is at least 100 chars wide.
--
-- License: GPLv2 (see COPYING) or any later version
-- Authors: Axel Kittenberger <axkibe@gmail.com>
--
--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- A security measurement.
-- The core will exit if version ids mismatch.
--
if lsyncd_version
then
-- ensures the runner is not being loaded twice
lsyncd.log( 'Error', 'You cannot use the lsyncd runner as configuration file!' )
lsyncd.terminate( -1 )
end
---@diagnostic disable-next-line: lowercase-global
lsyncd_version = '2.3.1'
-- compatibility with 5.1
if table.unpack == nil then
--- @diagnostic disable-next-line deprecated
table.unpack = unpack
end
local _LUA_VERSION_MAJOR, _LUA_VERSION_MINOR = string.gmatch(
_VERSION, "%w (%d).(%d)")()
---@type any
_LUA_VERSION_MAJOR = tonumber(_LUA_VERSION_MAJOR)
_LUA_VERSION_MINOR = tonumber(_LUA_VERSION_MINOR)
--
-- Shortcuts (which user is supposed to be able to use them as well)
--
---@diagnostic disable: lowercase-global
log = lsyncd.log
terminate = lsyncd.terminate
now = lsyncd.now
readdir = lsyncd.readdir
---@diagnostic enable: lowercase-global
--
-- Debug helper. Prints contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
--
---@diagnostic disable-next-line: lowercase-global
function dump(tbl, indent)
if not indent then indent = 0 end
for k, v in pairs(tbl) do
if type(k) ~= "string" then
k = tostring(k)
end
local formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
print(formatting)
if indent > 3 then
print("dump: Already 3 deep, skip")
else
dump(v, indent+1)
end
elseif type(v) ~= 'string' then
print(formatting .. tostring(v))
else
print(formatting .. v)
end
end
end
lsyncd.dump = dump
local inherit = nil
local inheritKV = nil
local CountArray = nil
local functionWriter = nil
--
--
-- Recurvely inherits a source table to a destionation table
-- copying all keys from source.
--
-- All entries with integer keys are inherited as additional
-- sources for non-verbatim tables
--
inherit = function
(
cd, -- table copy destination
cs, -- table copy source
verbatim, -- forced verbatim ( for e.g. 'exitcodes' )
ignored -- table of keys not to copy
)
-- First copies all entries with non-integer keys.
--
-- Tables are merged; already present keys are not
-- overwritten
--
-- For verbatim tables integer keys are treated like
-- non-integer keys
for k, v in pairs( cs )
do
if type(ignored) == 'table' and table.contains(ignored, k)
then
-- do nothing
-- print("ignore x", k)
elseif
(
type( k ) ~= 'number'
or verbatim
or cs._verbatim == true
)
and
(
type( cs ) ~= CountArray
and type( cs._merge ) ~= 'table'
or cs._merge[ k ] == true
)
then
inheritKV( cd, k, v )
end
end
-- recursevely inherits all integer keyed tables
-- ( for non-verbatim tables )
if cs._verbatim ~= true
then
for k, v in ipairs( cs )
do
if type( v ) == 'table'
then
inherit( cd, v )
else
cd[ #cd + 1 ] = v
end
end
end
end
table.contains = function
(
t, -- array to search in. Only the numeric values are tested
needle -- value to search for
)
for _, v in ipairs(t) do
if needle == v then
return true
end
end
return false
end
-- lsyncd.inherit = inherit
-- print("inherit ")
--
-- Helper to inherit. Inherits one key.
--
inheritKV =
function(
cd, -- table copy destination
k, -- key
v -- value
)
-- don't merge inheritance controls
if k == '_merge' or k == '_verbatim' then return end
local dtype = type( cd [ k ] )
if type( v ) == 'table'
then
if dtype == 'nil'
then
cd[ k ] = { }
inherit( cd[ k ], v, k == 'exitcodes' )
elseif
dtype == 'table' and
v._merge ~= false
then
inherit( cd[ k ], v, k == 'exitcodes' )
end
elseif dtype == 'nil'
then
cd[ k ] = v
end
end
local function alarm2string(a)
if type(a) == 'userdata' then
return a.string
end
return tostring( a )
end
--
-- Coping globals to ensure userscripts cannot change this.
--
local log = log
local terminate = terminate
local now = now
local readdir = readdir
local inherit = inherit
local inheritKV = inheritKV
--
-- Predeclarations.
--
local Monitors
--
-- Global: total number of processess running.
--
local processCount = 0
local crontab = nil
local function loadCrontab()
local names = {"crontab.crontab", "crontab", "lua-crontab"}
for _,lname in ipairs(names) do
local ok, mod = pcall(require, lname)
if ok then
-- print update crontab
log('Debug', "Using crontab: "..lname)
crontab = mod
return true
end
end
return false
end
--
-- All valid entries in a settings{} call.
--
local settingsCheckgauge =
{
logfile = true,
pidfile = true,
nodaemon = true,
onepass = true,
statusFile = true,
statusInterval = true,
logfacility = true,
logident = true,
insist = true,
inotifyMode = true,
maxProcesses = true,
maxDelays = true,
}
--
-- Settings specified by command line.
--
local clSettings = { }
--
-- Settings specified by config scripts.
--
local uSettings = { }
--
-- A copy of the settings function to see if the
-- user script replaced the settings() by a table
-- ( pre Lsyncd 2.1 style )
--
local settingsSafe
-- Access to process counter
lsyncd.get_process_info = function()
return processCount, uSettings.maxProcesses
end
--============================================================================
-- Lsyncd Prototypes
--============================================================================
--
-- Array tables error if accessed with a non-number.
--
local Array = ( function
( )
--
-- Metatable.
--
local mt = { }
--
-- On accessing a nil index.
--
mt.__index = function
(
t, -- table accessed
k -- key value accessed
)
if type(k) ~= 'number'
then
error( 'Key "'..k..'" invalid for Array', 2 )
end
return rawget( t, k )
end
--
-- On assigning a new index.
--
mt.__newindex = function
(
t, -- table getting a new index assigned
k, -- key value to assign to
v -- value to assign
)
if type( k ) ~= 'number'
then
error( 'Key "'..k..'" invalid for Array', 2 )
end
rawset( t, k, v )
end
--
-- Creates a new object
--
local function new
( )
local o = { }
setmetatable( o, mt )
return o
end
--
-- Public interface
--
return { new = new }
end )( )
--
-- Count array tables error if accessed with a non-number.
--
-- Additionally they maintain their length as 'size' attribute,
-- since Lua's # operator does not work on tables whose key values are not
-- strictly linear.
--
CountArray = ( function
( )
--
-- Metatable
--
local mt = { }
--
-- Key to native table
--
local k_nt = { }
--
-- On accessing a nil index.
--
mt.__index = function
(
t, -- table being accessed
k -- key used to access
)
if k == '_merge' or k == '_verbatim'
then
return nil
end
if type( k ) ~= 'number'
then
error( 'Key "' .. k .. '" invalid for CountArray', 2 )
end
return t[ k_nt ][ k ]
end
--
-- On assigning a new index.
--
mt.__newindex = function
(
t, -- table getting a new index assigned
k, -- key value to assign to
v -- value to assign
)
if type( k ) ~= 'number'
then
error( 'Key "'..k..'" invalid for CountArray', 2 )
end
-- value before
local vb = t[ k_nt ][ k ]
if v and not vb
then
t._size = t._size + 1
elseif not v and vb
then
t._size = t._size - 1
end
t[ k_nt ][ k ] = v
end
--
-- Walks through all entries in any order.
--
local function walk
(
self -- the count array
)
return pairs( self[ k_nt ] )
end
--
-- Returns the count.
--
local function size
(
self -- the count array
)
return self._size
end
--
-- Creates a new count array
--
local function new
( )
-- k_nt is a native table, private to this object.
local o =
{
_size = 0,
walk = walk,
size = size,
[ k_nt ] = { }
}
setmetatable( o, mt )
return o
end
--
-- Public interface
--
return { new = new }
end )( )
--
-- A queue is optimized for pushing and poping.
-- TODO: make this an object
--
Queue = ( function
( )
--
-- Metatable
--
local mt = { }
--
-- Key to native table
--
local k_nt = { }
--
-- On accessing a nil index.
--
mt.__index = function
(
t, -- table being accessed
k -- key used to access
)
if type( k ) ~= 'number'
then
error( 'Key "' .. k .. '" invalid for Queue', 2 )
end
return t[ k_nt ][ k ]
end
--
-- On assigning a new index.
--
mt.__newindex = function
(
t, -- table getting a new index assigned
k, -- key value to assign to
v -- value to assign
)
error( 'Queues are not directly assignable.', 2 )
end
--
-- Returns the first item of the Queue.
--
local function first
(
self
)
local nt = self[ k_nt ]
return nt[ nt.first ]
end
--
-- Returns the last item of the Queue.
--
local function last
(
self
)
local nt = self[ k_nt ]
return nt[ nt.last ]
end
--
-- Returns the size of the queue.
--
local function size
(
self
)
return self[ k_nt ].size
end
--
-- Pushes a value on the queue.
-- Returns the last value
--
local function push
(
self, -- queue to push to
value -- value to push
)
if not value
then
error( 'Queue pushing nil value', 2 )
end
local nt = self[ k_nt ]
local last = nt.last + 1
nt.last = last
nt[ last ] = value
nt.size = nt.size + 1
return last
end
--
-- Removes an item at pos from the Queue.
--
local function remove
(
self, -- the queue
pos -- position to remove
)
local nt = self[ k_nt ]
if nt[ pos ] == nil
then
error( 'Removing nonexisting item in Queue', 2 )
end
-- if removing first or last element,
-- the queue limits are adjusted.
if pos == nt.first
then
nt[ pos ] = nil
nt.first = pos + 1
elseif pos == nt.last
then
nt[ pos ] = nil
nt.last = nt.last - 1
else
local first = nt.first
local last = nt.first
local i = pos
while i < last do
if i == pos then
nt[ i ] = nt[ i + 1 ]
i = i + 1
end
i = i + 1
end
nt.last = last - 1
end
-- reset the indizies if the queue is empty
if nt.last < nt.first
then
nt.first = 1
nt.last = 0
end
nt.size = nt.size - 1
end
--
-- Injects a value in front of the Queue.
--
local function inject
(
self, -- the queue
value -- position to remove
)
local nt = self[ k_nt ]
local pos = nt.last
while pos >= nt.first
do
nt[pos + 1] = nt[pos]
pos = pos - 1
end
nt[nt.first] = value
nt.size = nt.size + 1
nt.last = nt.last + 1
end
--
-- Replaces a value.
--
local function replace
(
self, -- the queue
pos, -- position to replace
value -- the new entry
)
local nt = self[ k_nt ]
if nt[ pos ] == nil
then
error( 'Trying to replace an unset Queue entry.' )
end
nt[ pos ] = value
end
--
-- Queue iterator ( stateless )
-- TODO rename next
--
local function iter
(
self, -- queue to iterate
pos -- current position
)
local nt = self[ k_nt ]
pos = pos + 1
while nt[ pos ] == nil and pos <= nt.last
do
pos = pos + 1
end
if pos > nt.last
then
return nil
end
return pos, nt[ pos ]
end
--
-- Reverse queue iterator (stateless)
-- TODO rename prev
--
local function iterReverse
(
self, -- queue to iterate
pos -- current position
)
local nt = self[ k_nt ]
pos = pos - 1
while nt[ pos ] == nil and pos >= nt.first
do
pos = pos - 1
end
if pos < nt.first
then
return nil
end
return pos, nt[ pos ]
end
--
-- Iteraters through the queue
-- returning all non-nil pos-value entries.
--
local function qpairs
(
self
)
return iter, self, self[ k_nt ].first - 1
end
--
-- Iteraters backwards through the queue
-- returning all non-nil pos-value entries.
--
local function qpairsReverse
(
self
)
return iterReverse, self, self[ k_nt ].last + 1
end
--
-- Creates a new queue.
--
local function new
( )
local q = {
first = first,
last = last,
push = push,
inject = inject,
qpairs = qpairs,
qpairsReverse = qpairsReverse,
remove = remove,
replace = replace,
size = size,
[ k_nt ] =
{
first = 1,
last = 0,
size = 0
}
}
setmetatable( q, mt )
return q
end
--
-- Public interface
--
return { new = new }
end )( )
--
-- Locks globals.
--
-- No more globals can be created after this!
--
local function lockGlobals
( )
local t = _G
local mt = getmetatable( t ) or { }
-- TODO try to remove the underscore exceptions
mt.__index = function
(
t, -- table being accessed
k -- key used to access
)
if k ~= '_' and string.sub( k, 1, 2 ) ~= '__'
then
error( 'Access of non-existing global "' .. k ..'"', 2 )
else
rawget( t, k )
end
end
mt.__newindex = function
(
t, -- table getting a new index assigned
k, -- key value to assign to
v -- value to assign
)
if k ~= '_' and string.sub( k, 1, 2 ) ~= '__'
then
error(
'Lsyncd does not allow GLOBALS to be created on the fly. '
.. 'Declare "' .. k.. '" local or declare global on load.',
2
)
else
rawset( t, k, v )
end
end
setmetatable( t, mt )
end
--
-- Holds the information about a delayed event for one Sync.
--
-- Valid stati of an delay are:
-- 'wait' ... the event is ready to be handled.
-- 'active' ... there is process running catering for this event.
-- 'blocked' ... this event waits for another to be handled first.
--
local Delay = ( function
( )
--
-- Metatable.
--
local mt = { }
--
-- Secret key to native table
--
local k_nt = { }
local assignAble =
{
dpos = true,
etype = true,
path = true,
path2 = true,
status = true,
}
--
-- On accessing a nil index.
--
mt.__index = function
(
t, -- table accessed
k -- key value accessed
)
return t[ k_nt ][ k ]
end
--
-- On assigning a new index.
--
mt.__newindex = function
(
t, -- table getting a new index assigned
k, -- key value to assign to
v -- value to assign
)
if not assignAble[ k ]
then
error( 'Cannot assign new key "' .. k .. '" to Delay' )
end
t[ k_nt ][ k ] = v
end
--
-- This delay is being blocked by another delay
--
local function blockedBy
(
self, -- this delay
delay -- the blocking delay
)
self[ k_nt ].status = 'block'
local blocks = delay[ k_nt ].blocks
if not blocks
then
blocks = { }
delay[ k_nt ].blocks = blocks
end
table.insert( blocks, self )
end
--
-- Sets the delay status to 'active'.
--
local function setActive
(
self
)
self[ k_nt ].status = 'active'
end
--
-- Sets the delay status to 'wait'
--
local function wait
(
self, -- this delay
alarm -- alarm for the delay
)
self[ k_nt ].status = 'wait'
self[ k_nt ].alarm = alarm
end
--
-- Returns a debug string of the delay
--
local function debug(self, deep)
local rv = "<Delay "..self.status.." dpos:"..self.dpos.." type:"..self.etype.." alarm:"..alarm2string(self.alarm).." blocked:"..(self.blocks and #self.blocks or 0).." path:"..self.path
if deep and self.blocks then
for k,v in ipairs(self.blocks) do
rv = rv.."\n blocked: "..v:debug(false)
end
end
rv = rv..">"
return rv
end
--
-- Creates a new delay.
--
local function new
(
etype, -- type of event.
-- 'Create', 'Modify', 'Attrib', 'Delete' or 'Move'
sync, -- the Sync this delay belongs to
alarm, -- latest point in time this should be catered for
path, -- path and file-/dirname of the delay relative
-- -- to the syncs root.
path2 -- used only in moves, path and file-/dirname of
-- move destination
)
local delay =
{
blockedBy = blockedBy,
setActive = setActive,
wait = wait,
debug = debug,
[ k_nt ] =
{
etype = etype,
sync = sync,
alarm = alarm,
path = path,
path2 = path2,
status = 'wait'
},
}
setmetatable( delay, mt )
return delay
end
--
-- Public interface
--
return { new = new }
end )( )
--
-- Combines delays.
--
local Combiner = ( function
( )
--
-- The new delay replaces the old one if it's a file
--
local function refi
(
d1, -- old delay
d2 -- new delay
)
-- but a directory blocks
if d2.path:byte( -1 ) == 47
then
log(
'Delay',
d2.etype,': ',d2.path,
' blocked by ',
d1.etype,': ',d1.path
)
return 'stack'
end
log(
'Delay',
d2.etype, ': ', d2.path,
' replaces ',
d1.etype, ': ', d1.path
)
return 'replace'
end
--
-- Table on how to combine events that dont involve a move.
--
local combineNoMove = {
Attrib = {
Attrib = 'absorb',
Modify = 'replace',
Create = 'replace',
Delete = 'replace'
},
Modify = {
Attrib = 'absorb',
Modify = 'absorb',
Create = 'replace',
Delete = 'replace'
},
Create = {
Attrib = 'absorb',
Modify = 'absorb',
Create = 'absorb',
Delete = 'replace'
},
Delete = {
Attrib = 'absorb',
Modify = 'absorb',
Create = 'replace file,block dir',
Delete = 'absorb'
},
}
--
-- Returns the way two Delay should be combined.
--
-- Result:
-- nil -- They don't affect each other.
-- 'stack' -- Old Delay blocks new Delay.
-- 'replace' -- Old Delay is replaced by new Delay.
-- 'absorb' -- Old Delay absorbs new Delay.
-- 'toDelete,stack' -- Old Delay is turned into a Delete
-- and blocks the new Delay.
-- 'split' -- New Delay a Move is to be split
-- into a Create and Delete.
--
local function combine
(
d1, -- old delay
d2 -- new delay
)
if d1.etype == 'Init' or d1.etype == 'Blanket'
then
return 'stack'
end
-- A full sync does not affect us
if d1.etype == 'Full' or d2.etype == 'Full' then
return nil
end
-- two normal events
if d1.etype ~= 'Move' and d2.etype ~= 'Move'
then
if d1.path == d2.path
then
-- lookups up the function in the combination matrix
-- and calls it
local result = combineNoMove[ d1.etype ][ d2.etype ]
if result == 'replace file,block dir'
then
if d2.path:byte( -1 ) == 47
then
return 'stack'
else
return 'replace'
end
end
end
-- if one is a parent directory of another, events are blocking
if d1.path:byte( -1 ) == 47 and string.starts( d2.path, d1.path )
or d2.path:byte( -1 ) == 47 and string.starts( d1.path, d2.path )
then
return 'stack'
end
return nil
end
-- non-move event on a move.
if d1.etype == 'Move' and d2.etype ~= 'Move'
then
-- if the move source could be damaged the events are stacked
if d1.path == d2.path
or d2.path:byte( -1 ) == 47 and string.starts( d1.path, d2.path )
or d1.path:byte( -1 ) == 47 and string.starts( d2.path, d1.path )
then
return 'stack'
end
-- the event does something with the move destination
if d1.path2 == d2.path
then
if d2.etype == 'Delete'
or d2.etype == 'Create'
then
return 'toDelete,stack'
end
-- on 'Attrib' or 'Modify' simply stack on moves
return 'stack'
end
if d2.path:byte( -1 ) == 47 and string.starts( d1.path2, d2.path )
or d1.path2:byte( -1 ) == 47 and string.starts( d2.path, d1.path2 )
then
return 'stack'
end
return nil
end
-- a move upon a non-move event
if d1.etype ~= 'Move' and d2.etype == 'Move'
then
if d1.path == d2.path
or d1.path == d2.path2
or d1.path:byte( -1 ) == 47 and string.starts( d2.path, d1.path )
or d1.path:byte( -1 ) == 47 and string.starts( d2.path2, d1.path )
or d2.path:byte( -1 ) == 47 and string.starts( d1.path, d2.path )
or d2.path2:byte( -1 ) == 47 and string.starts( d1.path, d2.path2 )
then
return 'split'
end
return nil
end
--
-- a move event upon a move event
--
if d1.etype == 'Move' and d2.etype == 'Move'
then
-- TODO combine moves,
if d1.path == d2.path
or d1.path == d2.path2
or d1.path2 == d2.path
or d2.path2 == d2.path
or d1.path:byte( -1 ) == 47 and string.starts( d2.path, d1.path )
or d1.path:byte( -1 ) == 47 and string.starts( d2.path2, d1.path )
or d1.path2:byte( -1 ) == 47 and string.starts( d2.path, d1.path2 )
or d1.path2:byte( -1 ) == 47 and string.starts( d2.path2, d1.path2 )
or d2.path:byte( -1 ) == 47 and string.starts( d1.path, d2.path )
or d2.path:byte( -1 ) == 47 and string.starts( d1.path2, d2.path )
or d2.path2:byte( -1 ) == 47 and string.starts( d1.path, d2.path2 )
or d2.path2:byte( -1 ) == 47 and string.starts( d1.path2, d2.path2 )
then
return 'split'
end
return nil
end
error( 'reached impossible state' )
end
--
-- The new delay is absorbed by an older one.
--
local function logAbsorb
(
d1, -- old delay
d2 -- new delay
)
log(
'Delay',
d2.etype, ': ',d2.path,
' absorbed by ',
d1.etype,': ',d1.path
)
end
--
-- The new delay replaces the old one if it's a file.
--
local function logReplace
(
d1, -- old delay
d2 -- new delay
)
log(
'Delay',
d2.etype, ': ', d2.path,
' replaces ',
d1.etype, ': ', d1.path
)
end
--
-- The new delay splits on the old one.
--
local function logSplit
(
d1, -- old delay
d2 -- new delay
)
log(
'Delay',
d2.etype, ': ',
d2.path, ' -> ', d2.path2,
' splits on ',
d1.etype, ': ', d1.path
)
end
--
-- The new delay is blocked by the old delay.
--
local function logStack
(
d1, -- old delay
d2 -- new delay
)
local active = ''
if d1.active
then
active = 'active '
end
if d2.path2
then
log(
'Delay',
d2.etype, ': ',
d2.path, '->', d2.path2,
' blocked by ',
active,
d1.etype, ': ', d1.path
)
else
log(
'Delay',
d2.etype, ': ', d2.path,
' blocked by ',
active,
d1.etype, ': ', d1.path
)
end
end
--
-- The new delay turns the old one (a move) into a delete and is blocked.
--
local function logToDeleteStack
(
d1, -- old delay
d2 -- new delay
)
if d1.path2
then
log(
'Delay',
d2.etype, ': ', d2.path,
' turns ',
d1.etype, ': ', d1.path, ' -> ', d1.path2,
' into Delete: ', d1.path
)
else
log(
'Delay',
d2.etype, ': ', d2.path,
' turns ',
d1.etype, ': ', d1.path,
' into Delete: ', d1.path
)
end
end
local logFuncs =
{
absorb = logAbsorb,
replace = logReplace,
split = logSplit,
stack = logStack,
[ 'toDelete,stack' ] = logToDeleteStack
}
--
-- Prints the log message for a combination result
--
local function log
(
result, -- the combination result
d1, -- old delay
d2 -- new delay
)
local lf = logFuncs[ result ]
if not lf
then
error( 'unknown combination result: ' .. result )
end
lf( d1, d2 )
end
--
-- Public interface
--
return
{
combine = combine,
log = log
}
end )( )
--
-- Creates inlets for syncs: the user interface for events.
--
local InletFactory = ( function
( )
--
-- Table to receive the delay of an event
-- or the delay list of an event list.
--
-- Keys are events and values are delays.
--
local e2d = { }
--
-- Table to ensure the uniqueness of every event
-- related to a delay.
--
-- Keys are delay and values are events.
--
local e2d2 = { }
--
-- Allows the garbage collector to remove not refrenced
-- events.
--
setmetatable( e2d, { __mode = 'k' } )
setmetatable( e2d2, { __mode = 'v' } )
--
-- Removes the trailing slash from a path.
--
local function cutSlash
(
path -- path to cut
)
if string.byte( path, -1 ) == 47
then
return string.sub( path, 1, -2 )
else
return path
end
end
--
-- Gets the path of an event.
--
local function getPath
(
event
)
if event.move ~= 'To'
then
return e2d[ event ].path
else
return e2d[ event ].path2
end
end
--
-- Interface for user scripts to get event fields.
--
local eventFields = {
--
-- Returns a copy of the configuration as called by sync.
-- But including all inherited data and default values.
--
-- TODO give user a readonly version.
--
config = function
(
event
)
return e2d[ event ].sync.config
end,
--
-- Returns the inlet belonging to an event.
--
inlet = function
(
event
)
return e2d[ event ].sync.inlet
end,
--
-- Returns the type of the event.
--
-- Can be: 'Attrib', 'Create', 'Delete', 'Modify' or 'Move',
--
etype = function
(
event
)
return e2d[ event ].etype
end,
--
-- Events are not lists.
--
isList = function
( )
return false
end,
--
-- Returns the status of the event.
--
-- Can be:
-- 'wait', 'active', 'block'.
--
status = function
(
event
)
return e2d[ event ].status
end,
--
-- Returns true if event relates to a directory
--
isdir = function
(
event
)
return string.byte( getPath( event ), -1 ) == 47
end,
--
-- Returns the name of the file/dir.
--
-- Includes a trailing slash for dirs.
--
name = function
(
event
)
return string.match( getPath( event ), '[^/]+/?$' )
end,
--
-- Returns the name of the file/dir
-- excluding a trailing slash for dirs.
--
basename = function
(
event
)
return string.match( getPath( event ), '([^/]+)/?$')
end,
--
-- Returns the file/dir relative to watch root
-- including a trailing slash for dirs.
--
path = function
(
event
)
local p = getPath( event )
if string.byte( p, 1 ) == 47
then
p = string.sub( p, 2, -1 )
end
return p
end,
--
-- Returns the directory of the file/dir relative to watch root
-- Always includes a trailing slash.
--
pathdir = function
(
event
)
local p = getPath( event )
if string.byte( p, 1 ) == 47
then
p = string.sub( p, 2, -1 )
end
return string.match( p, '^(.*/)[^/]+/?' ) or ''
end,
--
-- Returns the file/dir relativ to watch root
-- excluding a trailing slash for dirs.
--
pathname = function
(
event
)
local p = getPath( event )
if string.byte( p, 1 ) == 47
then
p = string.sub( p, 2, -1 )
end
return cutSlash( p )
end,
--
-- Returns the absolute path of the watch root.
-- All symlinks are resolved.
--
source = function
(
event
)
return e2d[ event ].sync.source
end,
--
-- Returns the absolute path of the file/dir
-- including a trailing slash for dirs.
--
sourcePath = function
(
event
)
return e2d[ event ].sync.source .. getPath( event )
end,
--
-- Returns the absolute dir of the file/dir
-- including a trailing slash.
--
sourcePathdir = function
(
event
)
return(
e2d[event].sync.source
.. (
string.match( getPath( event ), '^(.*/)[^/]+/?' )
or ''
)
)
end,
--
-- Returns the absolute path of the file/dir
-- excluding a trailing slash for dirs.
--
sourcePathname = function
(
event
)
return e2d[ event ].sync.source .. cutSlash( getPath( event ) )
end,
--
-- Returns the configured target.
--
target = function
(
event
)
return e2d[ event ].sync.config.target
end,
--
-- Returns the absolute dir/file appended to the target
-- including a trailing slash for dirs.
--
targetPath = function
(
event
)
return e2d[ event ].sync.config.target .. getPath( event )
end,
--
-- Returns the dir of the dir/file appended to the target
-- including a trailing slash.
--
targetPathdir = function
(
event
)
return(
e2d[ event ].sync.config.target
.. (
string.match( getPath( event ), '^(.*/)[^/]+/?' )
or ''
)
)
end,
--
-- Returns the relative dir/file appended to the target
-- excluding a trailing slash for dirs.
--
targetPathname = function( event )
return(
e2d[ event ].sync.config.target
.. cutSlash( getPath( event ) )
)
end,
}
--
-- Retrievs event fields for the user script.
--
local eventMeta =
{
__index = function
(
event,
field
)
local f = eventFields[ field ]
if not f
then
if field == 'move'
then
-- possibly undefined
return nil
end
error( 'event does not have field "' .. field .. '"', 2 )
end
return f( event )
end
}
--
-- Interface for user scripts to get list fields.
--
local eventListFuncs =
{
--
-- Returns a list of paths of all events in list.
--
--
getPaths = function
(
elist, -- handle returned by getevents( )
mutator -- if not nil called with ( etype, path, path2 )
-- returns one or two strings to add.
)
local dlist = e2d[ elist ]
if not dlist
then
error( 'cannot find delay list from event list.' )
end
local result = { }
local resultn = 1
for k, d in ipairs( dlist )
do
local s1, s2
if mutator
then
s1, s2 = mutator( d.etype, d.path, d.path2 )
else
s1, s2 = d.path, d.path2
end
result[ resultn ] = s1
resultn = resultn + 1
if s2
then
result[ resultn ] = s2
resultn = resultn + 1
end
end
return result
end,
--
-- Returns the size of the eventlist
--
size = function( elist )
local dlist = e2d[ elist ]
if not dlist then
return 0
else
return #dlist
end
end,
--
-- Returns the list of events
--
getList = function( elist )
local dlist = e2d[ elist ]
if not dlist then
return {}
else
return dlist
end
end,
}
--
-- Retrievs event list fields for the user script
--
local eventListMeta =
{
__index = function
(
elist,
func
)
if func == 'isList'
then
return true
end
if func == 'config'
then
return e2d[ elist ].sync.config
end
local f = eventListFuncs[ func ]
if not f
then
error(
'event list does not have function "' .. func .. '"',
2
)
end
return function
( ... )
return f( elist, ... )
end
end
}
--
-- Table of all inlets with their syncs.
--
local inlets = { }
--
-- Allows the garbage collector to remove entries.
--
setmetatable( inlets, { __mode = 'v' } )
--
-- Encapsulates a delay into an event for the user script.
--
local function d2e
(
delay -- delay to encapsulate
)
-- already created?
local eu = e2d2[ delay ]
if delay.etype ~= 'Move'
then
if eu then return eu end
local event = { }
setmetatable( event, eventMeta )
e2d[ event ] = delay
e2d2[ delay ] = event
return event
else
-- moves have 2 events - origin and destination
if eu then return eu[1], eu[2] end
local event = { move = 'Fr' }
local event2 = { move = 'To' }
setmetatable( event, eventMeta )
setmetatable( event2, eventMeta )
e2d[ event ] = delay
e2d[ event2 ] = delay
e2d2[ delay ] = { event, event2 }
-- move events have a field 'move'
return event, event2
end
end
--
-- Encapsulates a delay list into an event list for the user script.
--
local function dl2el
(
dlist
)
local eu = e2d2[ dlist ]
if eu then return eu end
local elist = { }
setmetatable( elist, eventListMeta )
e2d [ elist ] = dlist
e2d2[ dlist ] = elist
return elist
end
--
-- The functions the inlet provides.
--
local inletFuncs =
{
--
-- Adds an exclude.
--
addExclude = function
(
sync, -- the sync of the inlet
pattern -- exlusion pattern to add
)
sync:addExclude( pattern )
end,
--
-- Appens a filter.
--
appendFilter = function
(
sync, -- the sync of the inlet
rule, -- '+' or '-'
pattern -- exlusion pattern to add
)
sync:appendFilter( rule, pattern )
end,
--
-- Removes an exclude.
--
rmExclude = function
(
sync, -- the sync of the inlet
pattern -- exlusion pattern to remove
)
sync:rmExclude( pattern )
end,
--
-- Gets the list of excludes in their
-- rsync-like patterns form.
--
getExcludes = function
(
sync -- the sync of the inlet
)
-- creates a copy
local e = { }
local en = 1;
for k, _ in pairs( sync.excludes.list )
do
e[ en ] = k;
en = en + 1;
end
return e;
end,
--
-- Gets the list of filters and excldues
-- as rsync-like filter/patterns form.
--
getFilters = function
(
sync -- the sync of the inlet
)
-- creates a copy
local e = { }
local en = 1;
-- first takes the filters
if sync.filters
then
for _, entry in ipairs( sync.filters.list )
do
e[ en ] = entry.rule .. ' ' .. entry.pattern;
en = en + 1;
end
end
-- then the excludes
for k, _ in pairs( sync.excludes.list )
do
e[ en ] = '- ' .. k;
en = en + 1;
end
return e;
end,
--
-- Returns true if the sync has filters
--
hasFilters = function
(
sync -- the sync of the inlet
)
return not not sync.filters
end,
--
-- Creates a blanketEvent that blocks everything
-- and is blocked by everything.
--
createBlanketEvent = function
(
sync -- the sync of the inlet
)
return d2e( sync:addBlanketDelay( ) )
end,
--
-- Creates a blanketEvent that blocks everything
-- and is blocked by everything.
--
createFullEvent = function
(
sync, -- the sync of the inlet
path -- path for the full event
)
-- return d2e( sync:delay("Full", timestamp, path, nil) )
return d2e( sync:addFullDelay(path) )
end,
--
-- Discards a waiting event.
--
discardEvent = function
(
sync,
event
)
local delay = e2d[ event ]
if delay.status ~= 'wait'
then
log(
'Error',
'Ignored cancel of a non-waiting event of type ',
event.etype
)
return
end
sync:removeDelay( delay )
end,
--
-- Gets the next not blocked event from queue.
--
getEvent = function
(
sync
)
return d2e( sync:getNextDelay( now( ) ) )
end,
--
-- Gets all events that are not blocked by active events.
--
getEvents = function
(
sync, -- the sync of the inlet
test -- if not nil use this function to test if to include an event
)
local dlist = sync:getDelays( test )
return dl2el( dlist )
end,
--
-- Returns the configuration table specified by sync{ }
--
getConfig = function( sync )
-- TODO give a readonly handler only.
return sync.config
end,
--
-- Returns the sync for this Inlet
--
getSync = function( sync )
return sync
end,
--
-- Substitutes parameters in arguments
--
getSubstitutionData = function( sync, event, data)
return sync.getSubstitutionData(sync, event, data)
end,
}
--
-- Forwards access to inlet functions.
--
local inletMeta =
{
__index = function
(
inlet,
func
)
local f = inletFuncs[ func ]
if not f
then
error( 'inlet does not have function "'..func..'"', 2 )
end
return function( ... )
return f( inlets[ inlet ], ... )
end
end,
}
--
-- Creates a new inlet for a sync.
--
local function newInlet
(
sync -- the sync to create the inlet for
)
-- Lsyncd runner controlled variables
local inlet = { }
-- sets use access methods
setmetatable( inlet, inletMeta )
inlets[ inlet ] = sync
return inlet
end
--
-- Returns the delay from a event.
--
local function getDelayOrList
(
event
)
return e2d[ event ]
end
--
-- Returns the sync from an event or list
--
local function getSync
(
event
)
return e2d[ event ].sync
end
--
-- Public interface.
--
return {
getDelayOrList = getDelayOrList,
d2e = d2e,
dl2el = dl2el,
getSync = getSync,
newInlet = newInlet,
}
end )( )
--
-- A set of exclude patterns.
--
local Excludes = ( function
( )
--
-- Turns a rsync like file pattern to a lua pattern.
-- ( at best it can )
--
local function toLuaPattern
(
p -- the rsync like pattern
)
local o = p
p = string.gsub( p, '%%', '%%%%' )
p = string.gsub( p, '%^', '%%^' )
p = string.gsub( p, '%$', '%%$' )
p = string.gsub( p, '%(', '%%(' )
p = string.gsub( p, '%)', '%%)' )
p = string.gsub( p, '%.', '%%.' )
p = string.gsub( p, '%[', '%%[' )
p = string.gsub( p, '%]', '%%]' )
p = string.gsub( p, '%+', '%%+' )
p = string.gsub( p, '%-', '%%-' )
p = string.gsub( p, '%?', '[^/]' )
p = string.gsub( p, '%*', '[^/]*' )
-- this was a ** before
p = string.gsub( p, '%[%^/%]%*%[%^/%]%*', '.*' )
p = string.gsub( p, '^/', '^/' )
if p:sub( 1, 2 ) ~= '^/'
then
-- if does not begin with '^/'
-- then all matches should begin with '/'.
p = '/' .. p;
end
log( 'Exclude', 'toLuaPattern "', o, '" = "', p, '"' )
return p
end
--
-- Adds a pattern to exclude.
--
local function add
(
self,
pattern -- the pattern to exclude
)
if self.list[ pattern ]
then -- already in the list
return
end
local lp = toLuaPattern( pattern )
self.list[ pattern ] = lp
end
--
-- Removes a pattern to exclude.
--
local function remove
(
self, -- self
pattern -- the pattern to remove
)
-- already in the list?
if not self.list[ pattern ]
then
log(
'Normal',
'Removing not excluded exclude "' .. pattern .. '"'
)
return
end
self.list[ pattern ] = nil
end
--
-- Adds a list of patterns to exclude.
--
local function addList
(
self,
plist
)
for _, v in ipairs( plist )
do
add( self, v )
end
end
--
-- Loads the excludes from a file.
--
local function loadFile
(
self, -- self
file -- filename to load from
)
local f, err = io.open( file )
if not f
then
log( 'Error', 'Cannot open exclude file "', file,'": ', err )
return terminate( -1 )
end
for line in f:lines()
do
-- lsyncd 2.0 does not support includes
if not string.match( line, '^%s*%+' )
and not string.match( line, '^%s*#' )
and not string.match( line, '^%s*$' )
then
local p = string.match( line, '%s*-?%s*(.*)' )
if p
then
add( self, p )
end
end
end
f:close( )
end
--
-- Tests if 'path' is excluded.
--
local function test
(
self, -- self
path -- the path to test
)
if path:byte( 1 ) ~= 47
then
error( 'Paths for exlusion tests must start with \'/\'' )
end
for _, p in pairs( self.list )
do
if p:byte( -1 ) == 36
then
-- ends with $
if path:match( p )
then
return true
end
else
-- ends either end with / or $
if path:match( p .. '/' )
or path:match( p .. '$' )
then
return true
end
end
end
return false
end
--
-- Cretes a new exclude set.
--
local function new
( )
return {
list = { },
-- functions
add = add,
addList = addList,
loadFile = loadFile,
remove = remove,
test = test,
}
end
--
-- Public interface.
--
return { new = new }
end )( )
--
-- A set of filter patterns.
--
-- Filters allow excludes and includes
--
local Filters = ( function
( )
--
-- Turns a rsync like file pattern to a lua pattern.
-- ( at best it can )
--
local function toLuaPattern
(
p -- the rsync like pattern
)
local o = p
p = string.gsub( p, '%%', '%%%%' )
p = string.gsub( p, '%^', '%%^' )
p = string.gsub( p, '%$', '%%$' )
p = string.gsub( p, '%(', '%%(' )
p = string.gsub( p, '%)', '%%)' )
p = string.gsub( p, '%.', '%%.' )
p = string.gsub( p, '%[', '%%[' )
p = string.gsub( p, '%]', '%%]' )
p = string.gsub( p, '%+', '%%+' )
p = string.gsub( p, '%-', '%%-' )
p = string.gsub( p, '%?', '[^/]' )
p = string.gsub( p, '%*', '[^/]*' )
-- this was a ** before
p = string.gsub( p, '%[%^/%]%*%[%^/%]%*', '.*' )
p = string.gsub( p, '^/', '^/' )
if p:sub( 1, 2 ) ~= '^/'
then
-- if does not begin with '^/'
-- then all matches should begin with '/'.
p = '/' .. p;
end
log( 'Filter', 'toLuaPattern "', o, '" = "', p, '"' )
return p
end
--
-- Appends a filter pattern
--
local function append
(
self, -- the filters object
line -- filter line
)
local rule, pattern = string.match( line, '%s*([+|-])%s*(.*)' )
if not rule or not pattern
then
log( 'Error', 'Unknown filter rule: "', line, '"' )
terminate( -1 )
end
local lp = toLuaPattern( pattern )
table.insert( self. list, { rule = rule, pattern = pattern, lp = lp } )
end
--
-- Adds a list of patterns to exclude.
--
local function appendList
(
self,
plist
)
for _, v in ipairs( plist )
do
append( self, v )
end
end
--
-- Loads the filters from a file.
--
local function loadFile
(
self, -- self
file -- filename to load from
)
local f, err = io.open( file )
if not f
then
log( 'Error', 'Cannot open filter file "', file, '": ', err )
return terminate( -1 )
end
for line in f:lines( )
do
if string.match( line, '^%s*#' )
or string.match( line, '^%s*$' )
then
-- a comment or empty line: ignore
else
append( self, line )
end
end
f:close( )
end
--
-- Tests if 'path' is filtered.
--
local function test
(
self, -- self
path -- the path to test
)
if path:byte( 1 ) ~= 47
then
error( 'Paths for filter tests must start with \'/\'' )
end
for _, entry in ipairs( self.list )
do
local rule = entry.rule
local lp = entry.lp -- lua pattern
if lp:byte( -1 ) == 36
then
-- ends with $
if path:match( lp )
then
return rule == '-'
end
else
-- ends either end with / or $
if path:match( lp .. '/' )
or path:match( lp .. '$' )
then
return rule == '-'
end
end
end
-- nil means neither a positivie
-- or negative hit, thus excludes have to
-- be queried
return nil
end
--
-- Cretes a new filter set.
--
local function new
( )
return {
list = { },
-- functions
append = append,
appendList = appendList,
loadFile = loadFile,
test = test,
}
end
--
-- Public interface.
--
return { new = new }
end )( )
--
-- Holds information about one observed directory including subdirs.
--
local Sync = ( function
( )
--
-- Syncs that have no name specified by the user script
-- get an incremental default name 'Sync[X]'
--
local nextDefaultName = 1
--
-- Adds an exclude.
--
local function addExclude
(
self,
pattern
)
return self.excludes:add( pattern )
end
--
-- Appends a filter line to the Sync
--
local function appendFilter
(
self,
line
)
if not self.filters then self.filters = Filters.new( ) end
return self.filters:append( line )
end
--
-- Removes an exclude.
--
local function rmExclude
(
self,
pattern
)
return self.excludes:remove( pattern )
end
--
-- Removes a delay.
--
local function removeDelay
(
self,
delay
)
if self.delays[ delay.dpos ] ~= delay
then
error( 'Queue is broken, delay not at dpos' )
end
self.delays:remove( delay.dpos )
-- frees all delays blocked by this one.
if delay.blocks
then
for _, vd in pairs( delay.blocks )
do
vd.status = 'wait'
end
end
end
--
-- Returns true if the relative path is excluded or filtered
--
local function testFilter
(
self, -- the Sync
path -- the relative path
)
-- never filter the relative root itself
-- ( that would make zero sense )
if path == '/' then return false end
local filter = self.filters and self.filters:test( path )
if filter ~= nil then return filter end
-- otherwise check excludes if concerned
return self.excludes:test( path )
end
--
-- Returns true if this Sync concerns about 'path'.
--
local function concerns
(
self, -- the Sync
path -- the absolute path
)
-- not concerned if watch rootdir doesn't match
if not path:starts( self.source )
then
return false
end
-- a sub dir and not concerned about subdirs
if self.config.subdirs == false
and path:sub( #self.source, -1 ):match( '[^/]+/?' )
then
return false
end
return not testFilter( self, path:sub( #self.source ) )
end
--
-- Collects a child process.
--
local function collect
(
self, -- the sync
pid, -- process id of collected child process
exitcode -- exitcode of child process
)
local delay = self.processes[ pid ]
-- not a child of this sync?
if not delay then
return false
end
if delay.status
then
log( 'Delay', 'collected an event' )
if delay.status ~= 'active'
then
error( 'collecting a non-active process' )
end
local rc = self.config.collect(
InletFactory.d2e( delay ),
exitcode
)
if rc == 'die'
then
log( 'Error', 'Critical exitcode.' )
terminate( -1 )
elseif rc ~= 'again'
then
-- if its active again the collecter restarted the event
removeDelay( self, delay )
log(
'Delay',
'Finish of ',
delay.etype,
' on ',
self.source,delay.path,
' = ',
exitcode
)
-- sets the initDone after the first success
self.initDone = true
else
-- sets the delay on wait again
local alarm = self.config.delay
-- delays at least 1 second
if alarm < 1 then alarm = 1 end
delay:wait( now( ) + alarm )
end
else
log( 'Delay', 'collected a list' )
local rc = self.config.collect(
InletFactory.dl2el( delay ),
exitcode
)
if rc == 'die'
then
log( 'Error', 'Critical exitcode.' );
terminate( -1 )
elseif rc == 'again'
then
-- sets the delay on wait again
local alarm = self.config.delay
-- delays are at least 1 second
if alarm < 1 then alarm = 1 end
alarm = now() + alarm
for _, d in ipairs( delay )
do
d:wait( alarm )
end
else
for _, d in ipairs( delay )
do
removeDelay( self, d )
end
end
log( 'Delay','Finished list = ',exitcode )
end
self.processes[ pid ] = nil
-- we handled this process
return true
end
--
-- Stacks a newDelay on the oldDelay,
-- the oldDelay blocks the new Delay.
--
-- A delay can block 'n' other delays,
-- but is blocked at most by one, the latest delay.
--
local function stack
(
oldDelay,
newDelay
)
newDelay:blockedBy( oldDelay )
end
--
-- Puts an action on the delay stack.
--
local function delay
(
self, -- the sync
etype, -- the event type
time, -- time of the event
path, -- path of the event
path2 -- desitination path of move events
)
log(
'Function',
'delay( ',
self.config.name, ', ',
etype, ', ',
path, ', ',
path2,
' )'
)
--
-- In case new directories were created
-- looks through this directories and makes create events for
-- new stuff found in there.
--
local function recurse
( )
if etype == 'Create' and path:byte( -1 ) == 47
then
local entries = lsyncd.readdir( self.source .. path )
if entries
then
for dirname, isdir in pairs( entries )
do
local pd = path .. dirname
if isdir then pd = pd..'/' end
log( 'Delay', 'Create creates Create on ', pd )
delay( self, 'Create', time, pd, nil )
end
end
end
end
-- exclusion tests
if not path2
then
-- simple test for single path events
if testFilter( self, path )
then
log( 'Filter', 'filtered ', etype, ' on "', path, '"' )
return
end
else
-- for double paths ( move ) it might result into a split
local ex1 = testFilter( self, path )
local ex2 = testFilter( self, path2 )
if ex1 and ex2
then
log(
'Filter',
'filtered "', etype, ' on "', path,
'" -> "', path2, '"'
)
return
elseif not ex1 and ex2
then
-- splits the move if only partly excluded
log(
'Filter',
'filtered destination transformed ',
etype,
' to Delete ',
path
)
delay( self, 'Delete', time, path, nil )
return
elseif ex1 and not ex2
then
-- splits the move if only partly excluded
log(
'Filter',
'filtered origin transformed ',
etype,
' to Create.',
path2
)
delay( self, 'Create', time, path2, nil )
return
end
end
if etype == 'Move'
and not self.config.onMove
then
-- if there is no move action defined,
-- split a move as delete/create
-- layer 1 scripts which want moves events have to
-- set onMove simply to 'true'
log( 'Delay', 'splitting Move into Delete & Create' )
delay( self, 'Delete', time, path, nil )
delay( self, 'Create', time, path2, nil )
return
end
-- creates the new action
local alarm
if time and self.config.delay
then
alarm = time + self.config.delay
else
alarm = now( )
end
-- new delay
local nd = Delay.new( etype, self, alarm, path, path2 )
if nd.etype == 'Init' or nd.etype == 'Blanket' or nd.etype == 'Full'
then
-- always stack init or blanket events on the last event
log(
'Delay',
'Stacking ',
nd.etype,
' event.'
)
if self.delays:size( ) > 0
then
stack( self.delays:last( ), nd )
end
nd.dpos = self.delays:push( nd )
recurse( )
return
end
-- detects blocks and combos by working from back until
-- front through the fifo
for il, od in self.delays:qpairsReverse( )
do
-- asks Combiner what to do
local ac = Combiner.combine( od, nd )
if ac
then
Combiner.log( ac, od, nd )
if ac == 'remove'
then
self.delays:remove( il )
elseif ac == 'stack'
then
stack( od, nd )
nd.dpos = self.delays:push( nd )
elseif ac == 'toDelete,stack'
then
if od.status ~= 'active'
then
-- turns olddelay into a delete
local rd = Delay.new( 'Delete', self, od.alarm, od.path )
self.delays:replace( il, rd )
rd.dpos = il
-- and stacks delay2
stack( rd, nd )
else
-- and stacks delay2
stack( od, nd )
end
nd.dpos = self.delays:push( nd )
elseif ac == 'absorb'
then
-- nada
elseif ac == 'replace'
then
if od.status ~= 'active'
then
self.delays:replace( il, nd )
nd.dpos = il
else
stack( od, nd )
nd.dpos = self.delays:push( nd )
end
elseif ac == 'split'
then
delay( self, 'Delete', time, path, nil )
delay( self, 'Create', time, path2, nil )
else
error( 'unknown result of combine()' )
end
recurse( )
return
end
il = il - 1
end
if nd.path2
then
log( 'Delay', 'New ', nd.etype, ': ', nd.path, ' -> ', nd.path2 )
else
log( 'Delay', 'New ', nd.etype, ': ', nd.path )
end
-- no block or combo
nd.dpos = self.delays:push( nd )
recurse( )
end
local function updateNextCronAlarm(self, timestamp)
if timestamp == nil then
timestamp = now()
end
local nalarm = nil
for i, c in ipairs(self.cron) do
local na = c:get_next_occurrence(timestamp.seconds)
if nalarm == nil or nalarm > na then
nalarm = na
end
end
if nalarm ~= nil then
self.nextCronAlarm = lsyncd.jiffies_from_seconds(nalarm)
end
end
--
-- Returns the soonest alarm for this Sync.
--
local function getAlarm
(
self
)
if self.processes:size( ) >= self.config.maxProcesses
then
return false
end
local rv = false
if self.cron ~= nil and self.nextCronAlarm == false then
updateNextCronAlarm(self)
end
-- first checks if more processes could be spawned
if self.processes:size( ) > self.config.maxProcesses
then
return false
end
-- finds the nearest delay waiting to be spawned
for _, d in self.delays:qpairs( )
do
if d.status == 'wait'
then
if type(d.alarm) == "boolean" and d.alarm == true then
return true
end
if type(d.alarm) == "userdata" then
if rv == false or
d.alarm < rv then
rv = d.alarm
end
end
end
end
if rv == false and self.nextCronAlarm ~= false then
rv = self.nextCronAlarm
elseif self.nextCronAlarm ~= false and self.nextCronAlarm < rv then
rv = self.nextCronAlarm
end
-- nothing to spawn
return rv
end
--
-- Gets all delays that are not blocked by active delays.
--
local function getDelays
(
self, -- the sync
test -- function to test each delay
)
local dlist = { sync = self }
local dlistn = 1
local blocks = { }
--
-- inheritly transfers all blocks from delay
--
local function getBlocks
(
delay
)
blocks[ delay ] = true
if delay.blocks
then
for _, d in ipairs( delay.blocks )
do
getBlocks( d )
end
end
end
for _, d in self.delays:qpairs( )
do
local tr = true
if test
then
tr = test( InletFactory.d2e( d ) )
end
if tr == 'break' then break end
if d.status == 'active' or not tr
then
getBlocks( d )
elseif not blocks[ d ]
then
dlist[ dlistn ] = d
dlistn = dlistn + 1
end
end
return dlist
end
--
-- Creates new actions
--
local function invokeActions
(
self,
timestamp
)
log(
'Function',
'invokeActions( "',
self.config.name, '", ',
timestamp,
' )'
)
if self.disabled
then
return
end
-- tunnel configured but not up
if self.config.tunnel and
self.config.tunnel:isReady() == false then
log('Tunnel', 'Tunnel for Sync ', self.config.name, ' not ready. Blocking events')
self.config.tunnel:blockSync(self)
return
end
if self.processes:size( ) >= self.config.maxProcesses
then
-- no new processes
return
end
if self.nextCronAlarm ~= false and self.nextCronAlarm < timestamp then
-- time fo a full sync
log('Info', 'Crontab triggered full sync')
self.inlet.createFullEvent("/")
updateNextCronAlarm(self, timestamp)
end
for _, d in self.delays:qpairs( )
do
-- if reached the global limit return
if uSettings.maxProcesses
and processCount >= uSettings.maxProcesses
then
log('Alarm', 'at global process limit.')
return
end
if self.delays:size( ) < self.config.maxDelays
then
-- time constrains are only concerned if not maxed
-- the delay FIFO already.
if d.alarm ~= true and timestamp < d.alarm
then
-- reached point in stack where delays are in future
return
end
end
if d.status == 'wait'
then
-- found a waiting delay
if d.etype == 'Init' then
self.config.init( InletFactory.d2e( d ) )
elseif d.etype == 'Full' and self.config.full then
self.config.full( InletFactory.d2e( d ) )
else
self.config.action( self.inlet )
end
if self.processes:size( ) >= self.config.maxProcesses
then
-- no further processes
return
end
end
end
end
--
-- Gets the next event to be processed.
--
local function getNextDelay
(
self,
timestamp
)
for i, d in self.delays:qpairs( )
do
if self.delays:size( ) < self.config.maxDelays
then
-- time constrains are only concerned if not maxed
-- the delay FIFO already.
if d.alarm ~= true and timestamp < d.alarm
then
-- reached point in stack where delays are in future
return nil
end
end
if d.status == 'wait'
then
-- found a waiting delay
return d
end
end
end
--
-- Adds and returns a blanket delay thats blocks all.
-- Used as custom marker.
--
local function addBlanketDelay
(
self
)
local newd = Delay.new( 'Blanket', self, true, '' )
newd.dpos = self.delays:push( newd )
return newd
end
--
-- Adds an full delay that will initiate a full transfer.
--
local function addFullDelay
(
self,
path
)
local newd = Delay.new( 'Full', self, true, path )
newd.dpos = self.delays:push( newd )
return newd
end
--
-- Adds and returns a blanket delay thats blocks all.
-- Used as startup marker to call init asap.
--
local function addInitDelay
(
self
)
local newd = Delay.new( 'Init', self, true, '' )
newd.dpos = self.delays:push( newd )
return newd
end
--
-- Writes a status report about delays in this sync.
--
local function statusReport
(
self,
f
)
local spaces = ' '
f:write( self.config.name, ' source=', self.source, '\n' )
f:write( 'There are ', self.delays:size( ), ' delays\n')
for i, vd in self.delays:qpairs( )
do
local st = vd.status
f:write( st, string.sub( spaces, 1, 7 - #st ) )
f:write( vd.etype, ' ' )
f:write( vd.path )
if vd.path2
then
f:write( ' -> ',vd.path2 )
end
f:write('\n')
end
f:write( 'Filtering:\n' )
local nothing = true
if self.filters
then
for _, e in pairs( self.filters.list )
do
nothing = false
f:write( e.rule, ' ', e.pattern,'\n' )
end
end
if #self.excludes.list > 0
then