### Custom Rsync Configuration Example Source: https://lsyncd.github.io/lsyncd/manual/config/layer4 An example of how to configure Lsyncd to use a specific Rsync binary and custom options like archive and compress. This allows for fine-tuning Rsync behavior for specific synchronization needs. ```lua sync { default.rsync, source = "/home/user/src/", target = "foohost.com:~/trg/", delay = 15, rsync = { binary = "/usr/local/bin/rsync", archive = true, compress = true } } ``` -------------------------------- ### Compile Lsyncd Source: https://lsyncd.github.io/lsyncd/manual/building Run these commands in the unpacked source directory to configure, build, and install Lsyncd. Ensure all requirements are met before proceeding. ```bash cmake . make sudo make install ``` -------------------------------- ### Start lsyncd Synchronization Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Initiates the lsyncd synchronization process, applying the 'convert' action to the 'magicdir' source directory without recursion. ```lua sync{convert, source="magicdir", recursive=false} ``` -------------------------------- ### Initialize Event Handling Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Starts the action function, which receives an 'inlet' object to get event details. This uses lsyncd's layer 1 interface. ```lua action = function(inlet) local event = inlet.getEvent() ``` -------------------------------- ### Log File Moves Source: https://lsyncd.github.io/lsyncd/manual/config/layer2 This example shows how to log details about file move operations. The `onMove` function receives two event objects: one for the origin and one for the destination, allowing you to track the movement path. ```lua tattleMove = { onMove = function(oEvent, dEvent) log("Normal", "A moved happened from ", oEvent.pathname, " to ", dEvent.pathname) end, } ``` -------------------------------- ### Full Auto-Image-Magic Script Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic This is the complete lsyncd script for the Auto-Image-Magic example. It handles image conversion on create and modify events, and deletion of all formats on delete events. ```lua local formats = { jpg = true, gif = true, png = true } convert = { delay = 0, maxProcesses = 99, action = function(inlet) local event = inlet.getEvent() if event.isdir then -- ignores events on dirs inlet.discardEvent(event) return end -- extract extension and basefilename local p = event.pathname local ext = string.match(p, ".*%.([^.]+)$) local base = string.match(p, "(.*)%.[^.]+$") if not formats[ext] then -- an unknown extenion log("Normal", "not doing something on ."..ext) inlet.discardEvent(event) return end -- autoconvert on create and modify if event.etype == "Create" or event.etype == "Modify" then -- builds one bash command local cmd = "" -- do for all other extensions for k, _ in pairs(formats) do if k ~= ext then -- excludes files to be created, so no -- followup actions will occur inlet.addExclude(base..'.'..k) if cmd ~= "" then cmd = cmd .. " && " end cmd = cmd.. '/usr/bin/convert "'..event.source..p..'" "'..event.source..base..'.'..k.. '" || /bin/true' end end log("Normal", "Converting "..p) spawnShell(event, cmd) return end -- deletes all formats if you delete one if event.etype == "Delete" then -- builds one bash command local cmd = "" -- do for all other extensions for k, _ in pairs(formats) do if k ~= ext then -- excludes files to be deleted, so no -- followup actions will occur inlet.addExclude(base..'.'..k) if cmd ~= "" then cmd = cmd .. " && " end cmd = cmd.. 'rm "'..event.source..base..'.'..k.. '" || /bin/true' end end log("Normal", "Deleting all "..p) spawnShell(event, cmd) return end -- ignores other events. inlet.discardEvent(event) end, ----- -- Removes excludes when convertions are finished -- collect = function(event, exitcode) local p = event.pathname local ext = string.match(p, ".*%.([^.]+)$) local base = string.match(p, "(.*)%.[^.]+$") local inlet = event.inlet if event.etype == "Create" or event.etype == "Modify" or event.etype == "Delete" then for k, _ in pairs(formats) do inlet.rmExclude(base..'.'..k) end end end, } sync{convert, source="magicdir", recursive=false} ``` -------------------------------- ### Insist on Syncing Despite Initial Failure Source: https://lsyncd.github.io/lsyncd/manual/invoking The -insist flag ensures Lsyncd attempts to start and sync even if the initial synchronization fails, useful for production environments where targets might be temporarily unavailable. This can also be set in the config file. ```bash lsyncd -insist -rsync /home/USER/src remotehost:dst ``` -------------------------------- ### Configure onStartup script Source: https://lsyncd.github.io/lsyncd/manual/config/layer3 Defines a bash script to execute upon Lsyncd startup, ensuring the source directory is not empty before copying. ```lua onStartup = '[[if [ "$(ls -A ^source)" ]; then cp -r ^source* ^target; fi]], ``` -------------------------------- ### Display Lsyncd Help Source: https://lsyncd.github.io/lsyncd/manual/invoking Use --help or -help to display the synopsis of Lsyncd's command line options. The double hyphen is redundant. ```bash lsyncd --help ``` ```bash lsyncd -help ``` -------------------------------- ### Configure default.direct for local synchronization Source: https://lsyncd.github.io/lsyncd/manual/config/layer4 Optimizes local directory synchronization by using system cp, rm, and mv commands instead of rsync after the initial sync. ```lua sync { default.direct, source = "/home/user/src/", target = "/home/user/trg/" } ``` -------------------------------- ### Default Initialization Function Source: https://lsyncd.github.io/lsyncd/manual/config/layer1 The default init function that handles onStartup logic for sync configurations. ```lua ----- -- called on (re)initalizing of lsyncd. -- init = function( inlet ) local config = inlet.getConfig( ) -- calls a startup if provided by user script. if type( config.onStartup ) == "function" then local event = inlet.createBlanketEvent( ) config.onStartup( event ) if event.status == 'wait' then -- user script did not spawn anything -- thus the blanket event is deleted again. inlet.discardEvent( event ) end end end, ``` -------------------------------- ### Configure default.rsyncssh with minimal parameters Source: https://lsyncd.github.io/lsyncd/manual/config/layer4 A basic configuration for rsyncssh requiring only source, host, and targetdir. ```lua sync { default.rsyncssh, source = "/home/user/src/", host = "foohost.com", targetdir = "~/trg/", } ``` -------------------------------- ### Action and Init Hooks Source: https://lsyncd.github.io/lsyncd/manual/config/layer1 Standard hooks for defining custom sync behavior. ```APIDOC ## Action and Init Hooks ### Description Customizable functions for handling sync logic. ### Hooks - **action(inlet)** - Called when events are ready. Used to spawn processes or handle events manually. - **init(inlet)** - Called on initialization of each sync. Used for setup tasks like onStartup. ``` -------------------------------- ### Rsync Initialization Logic Source: https://lsyncd.github.io/lsyncd/manual/config/layer1 An initialization function for rsync that ensures the target path ends with a slash and triggers a recursive startup sync. ```lua ----- -- Spawns the recursive startup sync -- init = function( inlet ) local config = inlet.getConfig( ) local event = inlet.createBlanketEvent( ) if string.sub(config.target, -1) ~= "/" then config.target = config.target .. "/" end log("Normal", "recursive startup rsync: ", config.source, " -> ", config.target) spawn(event, "/usr/bin/rsync", "--delete", config.rsync._computed .. "r", config.source, config.target ) end, ``` -------------------------------- ### Configure Lsyncd Daemon Settings Source: https://lsyncd.github.io/lsyncd/manual/config/file Use the `settings` call to configure daemon-wide settings such as log file location, status file updates, and whether to detach as a daemon. Ensure the correct syntax is used, especially when upgrading from older versions. ```lua settings { logfile = "/tmp/lsyncd.log", statusFile = "/tmp/lsyncd.status", nodaemon = true, } ``` -------------------------------- ### Configure default rsync sync Source: https://lsyncd.github.io/lsyncd/manual/config/layer4 Basic configuration for syncing a local directory using the default rsync behavior. ```lua sync { default.rsync, source = "DIRNAME", target = "DIRNAME" } ``` -------------------------------- ### Basic Bash Sync Configuration Source: https://lsyncd.github.io/lsyncd/manual/examples A simple lsyncd configuration for basic file synchronization using bash. ```bash sync{bash, source="/home/lonewolf/teste1", target="/home/lonewolf/teste2"} ``` -------------------------------- ### Create a basic rsync wrapper script Source: https://lsyncd.github.io/lsyncd/faq/postscript A bash script that executes the rsync binary and runs custom commands based on the exit status. ```bash #!/bin/bash /usr/bin/rsync "$@" result=$? ( if [ $result -eq 0 ]; then echo "my commands"; fi ) >/dev/null 2>/dev/null drop it. if event.status == "wait" then inlet.discardEvent( event ) end end, ``` -------------------------------- ### Define Supported Image Formats Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic This Lua table defines the image file extensions that the script will process. Keys are the extensions, and values are set to true. ```lua local formats = { jpg = true, gif = true, png = true, } ``` -------------------------------- ### Create an advanced rsync wrapper with STDIN preservation Source: https://lsyncd.github.io/lsyncd/faq/postscript A bash script that captures STDIN to a temporary file before calling rsync, allowing post-processing of the file list. ```bash #!/bin/bash #create unique temp file to store incoming STDIN _TMP_FILE=$(mktemp -q /tmp/lsd-rsync.XXXXXXXXXX || exit 1) #Set trap to automatically clean up the temp file on exit trap 'rm -f -- "$_TMP_FILE"' EXIT #get last argument (TARGET) and next to last (SOURCE) _SOURCE=${@: -2:1} _TARGET=${@: -1:1} #save the current STDIN with \0 (NUL) chars to a file, or we'll lose the original STDIN after calling rsync cat - >$_TMP_FILE #execute rsync with arguments and inject STDIN with NUL delimited chars /usr/bin/rsync "$@" <$_TMP_FILE result=$? ( # ... # Do anything you need with our saved STDIN as $_TMP_FILE, $_SOURCE, $_TARGET, etc. # ... # for example # replace \0 (NUL) chars with tabs in our stdin saved as a file # sed -i 's/\x0/\t/g' $_TMP_FILE # pass this new file to other script, etc. ) ``` -------------------------------- ### Extract File Extension and Base Name Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Uses Lua string matching to extract the file extension and the base name (filename without extension) from the event's pathname. ```lua -- extract extension and basefilename local p = event.pathname local ext = string.match(p, ".*%.([^.]+)$) local base = string.match(p, "(.*)%.[^.]+$") ``` -------------------------------- ### Append Conversion Command Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Appends the command to convert the source image to another format. It uses '&&' to chain commands and '|| /bin/true' to allow subsequent commands to run even if one fails. ```lua if cmd ~= "" then cmd = cmd .. " && " ``` -------------------------------- ### Handle Delete Events Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic This block executes when a file is deleted. It constructs a bash command to remove all converted versions of that file. ```lua -- deletes all formats if you delete one if event.etype == "Delete" then -- builds one bash command local cmd = "" -- do for all other extensions for k, _ in pairs(formats) do if k ~= ext then -- excludes files to be deleted, so no -- followup actions will occur inlet.addExclude(base..'.'..k) if cmd ~= "" then cmd = cmd .. " && " end cmd = cmd.. 'rm "'..event.source..base..'.'..k.. '" || /bin/true' end end log("Normal", "Deleting all "..p) spawnShell(event, cmd) return end ``` -------------------------------- ### Run Lsyncd in Foreground Mode Source: https://lsyncd.github.io/lsyncd/manual/invoking Use the -nodaemon flag to prevent Lsyncd from detaching and becoming a daemon. Log messages are printed to stdout and stderr, and the working directory is not changed to '/'. Relative targets work in this mode. ```bash lsyncd -nodaemon CONFIGFILE ``` -------------------------------- ### Sync with RsyncSSH for Local Moves Source: https://lsyncd.github.io/lsyncd/manual/invoking Use -rsyncssh to leverage SSH commands for moving directories and files locally on the target, avoiding deletion and retransfer. Specify the local source, remote host (optionally with user), and target directory. ```bash lsyncd -rsyncssh /home/USER/src REMOTEHOST TARGETDIR ``` -------------------------------- ### Move Files or Directories with Lsyncd Source: https://lsyncd.github.io/lsyncd/manual/config/layer3 Configures Lsyncd to move files or directories within the target directory using Lsyncd variables to specify the origin and destination paths. ```lua onMove = "mv ^o.targetPathname ^d.targetPathname", ``` -------------------------------- ### Configure Lsyncd Tunnel Source: https://lsyncd.github.io/lsyncd/manual/config/layer4 Defines a tunnel using the tunnel function to manage external programs for data transfer. ```lua sync { default.rsync, tunnel = tunnel { command = {"ssh", "-N", "-L", "localhost:5432:localhost:873", "tunnel@testmachine"}, } target = "rsync://localhost:5432/projects", source = "/home/user/src/", } ``` -------------------------------- ### Set Lsyncd Action Delay Source: https://lsyncd.github.io/lsyncd/manual/config/layer3 Configures Lsyncd to aggregate changes for a specified duration before executing actions. A comma is required to separate entries within the configuration table. ```lua delay = 5, ``` -------------------------------- ### Define custom exit codes Source: https://lsyncd.github.io/lsyncd/manual/config/layer3 Maps specific process exit codes to Lsyncd actions such as respawning or termination. ```lua exitcodes = {[0] = "ok", [1] = "again", [2] = "die"} ``` -------------------------------- ### Inlet Functions Source: https://lsyncd.github.io/lsyncd/manual/config/layer1 Functions available within the inlet object to manage events and configuration during the action phase. ```APIDOC ## Inlet Functions ### Description Functions provided to the `action` and `init` hooks to interact with the event queue and sync configuration. ### Functions - **inlet.getEvent()** - Retrieves the next event. Returns origin and destination for move events. - **inlet.getEvents(test)** - Returns a list of all ready events. Optional `test` function filters events. - **inlet.discardEvent()** - Discards the current event. - **inlet.getConfig()** - Returns the configuration of the current sync. - **inlet.addExclude(pattern)** - Adds an exclusion pattern to the sync. - **inlet.rmExclude(pattern)** - Removes an exclusion pattern from the sync. - **inlet.createBlanketEvent()** - Creates a blanket event on the Delay FIFO, used for onStartup. ``` -------------------------------- ### Event List Functions Source: https://lsyncd.github.io/lsyncd/manual/config/layer1 Functions available on event lists returned by inlet.getEvents(). ```APIDOC ## Event List Functions ### Description Methods to extract path information from a collection of events. ### Functions - **elist.getPaths(delimiter)** - Returns a string of paths separated by the specified delimiter (default: \n). - **elist.getSourcePaths(delimiter)** - Returns a string of source paths separated by the specified delimiter (default: \n). ``` -------------------------------- ### Add Exclusion for Converted Files Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Excludes the newly created converted files from triggering further events. This prevents infinite loops. ```lua -- excludes files to be created, so no -- followup actions will occur inlet.addExclude(base..'.'..k) ``` -------------------------------- ### Define a class in Lua Source: https://lsyncd.github.io/lsyncd/appendices/devdocs Uses an immediately invoked function expression to encapsulate private variables and expose a public interface. ```lua MyClass = (function() local private = "only visible here" local function new() return {foo="bar"} end -- public interface return { new = new } end)() ``` -------------------------------- ### Delete All Image Formats Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Generates a bash command to delete all image formats except the one that triggered the event. It uses 'inlet.addExclude' to prevent recursive deletion of the files being removed. ```lua -- deletes all formats if you delete one if event.etype == "Delete" then -- builds one bash command local cmd = "" -- do for all other extensions for k, _ in pairs(formats) do if k ~= ext then -- excludes files to be deleted, so no -- followup actions will occur inlet.addExclude(base..'.'..k) if cmd ~= "" then cmd = cmd .. " && " end cmd = cmd.. 'rm "'..event.source..base..'.'..k.. '" || /bin/true' end end log("Normal", "Deleting all "..p) spawnShell(event, cmd) return end ``` -------------------------------- ### Default Rsync Command Source: https://lsyncd.github.io/lsyncd/manual/config/layer4 The default command Lsyncd uses to invoke Rsync. It includes options for preserving file attributes, deleting extraneous files, and using a filter list transmitted via a pipe. ```bash /usr/bin/rsync -ltsd --delete --include-from=- --exclude=* SOURCE TARGET ``` -------------------------------- ### Ignore Directory Events Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic This code explicitly discards events related to directories, as the script only processes files. It's necessary when using the layer 1 interface. ```lua if event.isdir then -- ignores events on dirs inlet.discardEvent(event) return end ``` -------------------------------- ### Define the Lsyncd collect function Source: https://lsyncd.github.io/lsyncd/manual/config/layer1 This function is invoked when a child process finishes. It processes exit codes to log status messages and determine if the agent should retry or terminate. ```lua collect = function(agent, exitcode) local config = agent.config if not agent.isList and agent.etype == "Blanket" then if exitcode == 0 then log("Normal", "Startup of '",agent.source,"' finished.") elseif config.exitcodes and config.exitcodes[exitcode] == "again" then log("Normal", "Retrying startup of '",agent.source,"' a.") return "again" else log("Error", "Failure on startup of '",agent.source,"' a.") terminate(-1) -- ERRNO end return end local rc = config.exitcodes and config.exitcodes[exitcode] if rc == "die" then return rc end if agent.isList then if rc == "again" then log("Normal", "Retrying a list on exitcode = ",exitcode) else log("Normal", "Finished a list = ",exitcode) end else if rc == "again" then log("Normal", "Retrying ",agent.etype, " on ",agent.sourcePath," = ",exitcode) else log("Normal", "Finished ",agent.etype, " on ",agent.sourcePath," = ",exitcode) end end return rc end, ``` -------------------------------- ### Discard Unhandled Events Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Ignores events that are not explicitly handled by the current configuration. This ensures that only relevant events trigger actions. ```lua -- ignores other events. inlet.discardEvent(event) end, ``` -------------------------------- ### Remove Exclusions After Conversion Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic The 'collect' function is called after an action finishes. It removes the exclusions added earlier for converted files, allowing them to be processed if necessary. ```lua collect = function(event, exitcode) local p = event.pathname local ext = string.match(p, ".*%.([^.]+)$) local base = string.match(p, "(.*)%.[^.]+$") local inlet = event.inlet if event.etype == "Create" or event.etype == "Modify" or event.etype == "Delete" then for k, _ in pairs(formats) do inlet.rmExclude(base..'.'..k) end end end, ``` -------------------------------- ### Remove Excludes After Conversion Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Cleans up by removing temporary excludes that were added during image conversion. This function is called when the conversion process finishes. ```lua -- Removes excludes when convertions are finished -- collect = function(event, exitcode) local p = event.pathname local ext = string.match(p, ".*%.([^ .]+)$) local base = string.match(p, "(.*)%.[^ .]+$") local inlet = event.inlet if event.etype == "Create" or event.etype == "Modify" or event.etype == "Delete" then for k, _ in pairs(formats) do inlet.rmExclude(base..'.'..k) end end end, ``` -------------------------------- ### Discard Unhandled Events Source: https://lsyncd.github.io/lsyncd/manual/examples/auto-image-magic Any event type not explicitly handled (Create, Modify, Delete) is discarded to prevent unintended actions. ```lua -- ignores other events. inlet.discardEvent(event) end, ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.