Package: watiba
WatibaVersion:0.6.59Date: 2021/12/04Watiba, pronounced wah-TEE-bah, is a lightweight Python pre-compiler for embedding Linux shell
commands within Python applications.  It is similar to other languages' syntactical enhancements where
XML or HTML is integrated into a language such as JavaScript.  That is the concept applied here but integrating
BASH shell commands with Python.As you browse this document, you'll find Watiba is rich with features for shell command integration with Python.Features:Shell command integration with Python codeIn-line access to shell command resultsCurrent directory context maintained across commands throughout your Python codeAsync/promise support for integrated shell commandsRemote shell command executionRemote shell command chaining and pipingTable of ContentsUsageDirectory ContextCommands as VariablesCommand ResultsAsynchronous Spawning and PromisesUseful Properties in PromiseSpawn ControllerJoin, Wait or WatchThe Promise TreeThreadsRemote ExecutionChange SSH port for remote executionCommand HooksCommand ChainingCommand Chain Piping (Experimental)InstallationPre-compilingCode ExamplesUsageWatiba files, suffixed with ".wt", are Python programs containing embedded shell commands.
Shell commands are expressed within backtick characters emulating BASH's original capture syntax.
They can be placed in any Python statement or expression.  Watiba keeps track of the current working directory
after the execution of any shell command so that all subsequent shell commands keep context.  For example:Basic example of embedded commands:#!/usr/bin/python3

# Typical Python program

if __name__ == "__main__":

    # Change directory context
    `cd /tmp`
    
    # Directory context maintained
    for file in `ls -lrt`.stdout:  # In-line access to command results
        print(f"File in /tmp: {file}")This loop will display the file list from /tmp. Thels -lrtis run in the
context of previouscd /tmp.Commands Expressed as VariablesCommands within backticks canbea variable, but cannot contain snippets of Python code or Python variables.
The statement within the backticksmustbe either a pure shell command or a Python variable containing a pure
shell command.  To execute commands in a Python variable, prefix the variable name between backticks with a dollar sign.A command variable is denoted by prepending a dollar sign on the variable name within backticks:# Set the Python variable to the command
cmdA = 'echo "This is a line of output" > /tmp/blah.txt'
cmdB = 'cat /tmp/blah.txt'

# Execute first command
`$cmdA`  # Execute the command within Python variable cmdA

# Execute second command
for line in `$cmdB`.stdout:
    print(line)This example demonstrates keeping dir context and executing a command by variable:#!/usr/bin/python3

if __name__ == "__main__":
    # Change CWD to /tmp
    `cd /tmp`
    
    # Set a command string
    my_cmd = "tar -zxvf tmp.tar.gz"
    
    # Execute that command and save the command results in variable "w"
    w = `$my_cmd`
    if w.exit_code == 0:
        for l in w.stderr:
            print(l)These constructs arenotsupported:file_name = "blah.txt"

# Python variable within backticks
`touch file_name`  # NOT SUPPORTED!

# Attempting to access Python variable with dollar sign
`touch $file_name` # NOT SUPPORTED!

# Python within backticks is NOT SUPPORTED!
`if x not in l: ls -lrt x`Directory ContextAn important Watiba usage point is directory context is kept for dispersed shell commands.
Any command that changes the shell's CWD is discovered and kept by Watiba.  Watiba achieves
this by tagging a&& echo pwdto the user's command, locating the result in the command's STDOUT,
and finally setting the Python environment to that CWD withos.chdir(dir).  This is automatic and
opaque to the user.  The user will not see the results of the generated suffix.  If theechosuffix presents a problem for the user, it can be eliminated by prefixing the leading backtick with a
dash.  The dash turns off the context tracking by not suffixing the command and so causes Watiba to
lose its context.  However, the context is maintainedwithinthe set of commands in the backticks just not
when it returns.  For example,out = -`cd /tmp && ls -lrt`honors thecdwithin the scope
of that execution line, but not for any backticked commands that follow later in your code.Warning!The dash will cause Watiba to lose its directory context should the command
cause a CWD change either explicitly or implicitly.Example:`cd /tmp`  # Context will be kept

# This will print from /home/user, but context is NOT kept  
for line in -`cd /home/user && ls -lrt`.stdout:
    print(line) 

# This will print from /tmp, not /home/user
for line in `ls -lrt`.stdout:
    print(line)Command ResultsThe results of the command issued in backticks are available in the properties
of the object returned by Watiba.  Following are those properties:PropertyData TypeDescriptionstdoutListSTDOUT lines from the command normalized for displaystderrListSTDERR lines from the command normalized for displayexit_codeIntegerExit code value from commandcwdStringCurrent working directoryaftercommand was executedTechnically, the returned object for any shell command is defined in the WTOutput class.Asynchronous Spawning and PromisesShell commands can be executed asynchronously with a defined resolver callback block.  Eachspawnexpression creates
and runs a new OS thread. The resolver is a callback block that follows the Watibaspawnexpression.  The spawn
feature is executed when aspawn `cmd` args: resolver blockcode block is encountered. The
resolver is passed the results in the promise object. (The promise structure contains the properties
defined in section"Results from Spawned Commands"Thespawnexpression also returns apromiseobject
to the caller ofspawn.  The promise object is passed to theresolver blockin argumentpromise.  The
outer code can check its state with a call toresolved()on thereturnedpromise object.  Output from the command
is found inpromise.output.  The examples throughout this README and in theexamples.wtfile make this clear.Useful properties in promise structureA promise is either returned in assignment from outermost spawn, or passed to child spawns in argument "promise".PropertyData TypeDescriptionhostStringHost name on which spawned command ranchildrenListChildren promises for this promise nodeparentReferenceParent promise node of child promise. None if root promise.commandStringShell command issued for this promiseresolved()MethodCall to find out if this promise is resolvedresolve_parent()MethodCall inside resolver block to resolve parent promisetree_dump()MethodCall to show the promise tree.  Takes subtree argument otherwise it defaults to the root promisejoin()MethodCall to wait on on promise and all its childrenwait()MethodCall to wait on just this promisewatch()MethodCall to create watcher on this promisestart_timeTimeTime that spawned command startedend_timeTimeTime that promise resolvedExample of simple spawn:prom = spawn `tar -zcvf big_file.tar.gz some_dir/*`:
    # Resolver block to which "promise" and "args" is passed...
    print(f"{promise.command} completed.")
    return True  # Resolve promise

# Do other things while tar is running
# Finally wait for tar promise to resolve
prom.join()Spawn ControllerAll spawned threads are managed by Watiba's Spawn Controller.  The controller watches for too many threads and
incrementally slows down each thread start when that threshold is exceeded until either all the promises in the tree
resolve, or an expiration count is reached, at which time an exception is thrown on the last spawned command.This exception is raised by the default error method. This method as well as other spawn controlling parameters
can be overridden.  The controller's purpose is to not allow run away threads and provide signaling of possible
hung threads.spawn-ctlexample:# Only allow 20 spawns max, 
# and increase slowdown by 1/2 second each 3rd cycle
...python code...
spawn-ctl {"max":20, "sleep-increment":.500}Spawn control parameters:Key NameData TypeDescriptionDefaultmaxIntegerThe maximum number of spawned commands allowed before the controller enters slowdown mode10sleep-floorIntegerSeconds ofstartingsleep value when the controller enters slowdown mode.125 (start at 1/8th second pause)sleep-incrementIntegerSeconds theamountof seconds sleep will increase every 3rd cycle when in slowdown 
      mode.125 (Increase pause 1/8th second every 3rd cycle)sleep-ceilingIntegerSeconds thehighestlength sleep value allowed when in slowdown mode  
      (As slow as it will get)3 (won't get slower than 3 second pauses)expireIntegerTotal number of slowdown cycles allowed before the error method is calledNo expirationerrorMethodCallback method invoked when slowdown mode expires. Use this to catch hung commands.
            This method is passed 2 arguments:promise- The promise attempting execution at the time of expirationcount- The thread count (unresolved promises) at the time of expirationGeneric error handler.  Just throwsWTSpawnExceptionthat hold propertiespromiseandmessagespawn-ctlonly overrides the values it sets and does not affect values not specified.spawn-ctlstatements can
set whichever values it wants, can be dispersed throughout your code (i.e. multiplespawn-ctlstatements) and
only affects subsequent spawn expressions.Notes:Arguments can be passed to the resolver by specifying a trailing variable after the command.  If the arguments
variable is omitted, an empty dictionary, i.e. {}, is passed to the resolver inargs.Warning!Python threading does not deep copy objects passed as arguments to threads.  What you place inargsof the spawn expression will only be shallow copied so if there are references to other objects, it's not likely to
survive the copy.The resolver must returnTrueto set the promise to resolved, orFalseto leave it unresolved.A resolver can also set the promise to resolved by callingpromise.set_resolved().  This is handy in cases where
a resolver has spawned another command and doesn't want the outer promise resolved until the inner resolvers are done.
To resolve an outer, i.e. parent, resolver issuepromise.resolve_parent().  Then the parent resolver can returnFalseat the end of its block so it leaves the resolved determination to the inner resolver block.Each promise object holds its OS thread object in propertythreadand its thread id in propertythread_id. This
can be useful for controlling the thread directly.  For example, to signal a kill.spawn-ctlhas no affect onjoin,wait, orwatch.  This is becausespawn-ctlestablishes an upper end
throttle on the overall spawning process.  When the number of spawns hits the max value, throttling (i.e. slowdown
mode) takes affect and will expire if none of the promises resolve.  Conversely, the arguments used byjoin,waitandwatchcontrol the sleep cycle and expiration of just those calls, not the spawned threads as a whole. When
an expiration is set for, say,join, then that join will expire at that time.  When an expiration is set inspawn-ctl, then if all the spawned threads as a whole don't resolve in time then an expiration function is called.Spawn Syntax:my_promise = spawn `cmd` [args]:
    resolver block (promise, args)
    args passed in args
    return resolved or unresolved (True or False)Spawn with resolver arguments omitted:my_promise = spawn `cmd`:
    resolver block (promise, args)
    return resolved or unresolved (True or False)Simple spawn example:p = spawn `tar -zcvf /tmp/file.tar.gz /home/user/dir`:
    # Resolver block to which "promise" and "args" are passed
    # Resolver block is called when spawned command has completed
    for line in promise.output.stderr:
        print(line)
    
    # This marks the promise resolved
    return True
    
# Wait for spawned command to resolve (not merely complete)
try:
    p.join({"expire": 3})
    print("tar resolved")
except Exception as ex:
    print(ex.args)Example of file that overrides spawn controller parameters:#!/usr/bin/python3
def spawn_expired(promise, count):
    print("I do nothing just to demonstrate the error callback.")
    print(f"This command failed {promise.command} at this threshold {count}")
    
    raise Exception("Too many threads.")
    
if __name__ == "__main__":
    # Example showing default values
    parms = {"max": 10, # Max number of threads allowed before slowdown mode
         "sleep-floor": .125,  # Starting sleep value
         "sleep-ceiling": 3,  # Maximum sleep value
         "sleep-increment": .125,  # Incremental sleep value
         "expire": -1,  # Default: no expiration
         "error": spawn_expired  # Method called upon slowdown expiration
    }
     
    # Set spawn controller parameter values
    spawn-ctl parmsJoin, Wait, or WatchOnce commands are spawned, the caller can wait forallpromises, including inner or child promises, to complete, or
the caller can wait for just a specific promise to complete.  To wait for allchildpromises including
the promise on which you're calling this method, calljoin().  It will wait for that promise and all its children. To
wait for just one specific promise, callwait()on the promise of interest.  To wait forallpromises in
the promise tree, calljoin()on the root promise.joinandwaitcan be controlled through parameters.  Each are iterators paused with a sleep method and will throw
an expiration exception should you set a limit for iterations.  If an expiration value is not set,
no exception will be thrown and the cycle will run only until the promise(s) are resolved.joinandwaitare not
affected byspawn-ctl.watchis called to establish a separate asynchronous thread that will call back a function of your choosing should
the command the promise is attached to time out.  This is different thanjoinandwaitin thatwatchis not synchronous
and does not pause.  This is used to keep an eye on a spawned command and take action should it hang.  Your watcher
function is passed the promise on which the watcher was attached, and the arguments, if any, from the spawn expression.
If your command does not time out (i.e. hangs and expires), the watcher thread will quietly go away when the promise
is resolved.watchexpiration is expressed inseconds, unlikejoinandwaitwhich are expressed as totaliterationspaused at the sleep value.watch's polling cycle pause is .250 seconds, so the expiration value is
multiplied by 4.  The default expiration is 15 seconds.Examples:# Spawn a thread running this command
p = spawn `ls -lrt`:
    ## resolver block ##
    return True
    
# Wait for promises, pause for 1/4 second each iteration, and throw an exception after 4 iterations 
(1 second)
try:
    p.join({"sleep": .250, "expire": 4})
except Exception as ex:
    print(ex.args)

# Wait for this promise, pause for 1 second each iteration, and throw an exception after 5 iterations 
(5 seconds)
try:
    p.wait({"sleep": 1, "expire": 5})
except Exception as ex:
    print(ex.args)
 
# My watcher function (called if spawned command never resolves by its experation period)
def watcher(promise, args):
    print(f"This promise is likely hung: {promise.command}")
    print(f"and I still have the spawn expression's args: {args}")

p = spawn `echo "hello" && sleep 5` args:
    print(f"Args passed to me: {args}")
    return True

# Attach a watcher to this thread.  It will be called upon experation.
p.watch(watcher)
print("watch() does not pause like join or wait")

# Attach a watcher that will expire in 5 seconds
p.watch(watcher, {"expire": 5})joinsyntaxpromise.join({optional args})
Where args is a Python dictionary with the following options:
    "sleep" - seconds of sleep for each iteration (fractions such as .5 are honored)
        default: .5 seconds
    "expire" - number of sleep iterations until an excpetions is raised
        default: no expiration
Note: "args" is optional and can be omittedExample of joining parent and children promises:p = spawn `ls *.txt`:
    for f in promise.output.stdout:
        cmd = f"tar -zcvf {f}.tar.gz {f}"
        spawn `$cmd` {"file":f}:
            print(f"{f} completed")
            promise.resolve_parent()
            return True
    return False

# Wait for all commands to complete
try:
    p.join({"sleep":1, "expire":20})
except Exception as ex:
    print(ex.args)waitsyntaxpromise.wait({optional args})
Where args is a Python dictionary with the following options:
    "sleep" - seconds of sleep for each iteration (fractions such as .5 are honored)
        default: .5 seconds
    "expire" - number of sleep iterations until an excpetions is raised
        default: no expiration
Note: "args" is optional and can be omittedExample of waiting on just the parent promise:p = spawn `ls *.txt`:
    for f in promise.output.stdout:
        cmd = f"tar -zcvf {f}.tar.gz {}"
        spawn `$cmd` {"file":f}:
            print(f"{f} completed")
            promise.resolve_parent() # Wait completes here
            return True
    return False

# Wait for just the parent promise to complete
try:
    p.wait({"sleep":1, "expire":20})
except Exception as ex:
    print(ex.args)watchsyntaxpromise.watch(callback, {optional args})
Where args is a Python dictionary with the following options:
    "sleep" - seconds of sleep for each iteration (fractions such as .5 are honored)
        default: .5 seconds
    "expire" - number of sleep iterations until an excpetions is raised
        default: no expiration
Note: "args" is optional and can be omittedExample of creating a watcher:# Define watcher method.  Called if command times out (i.e. expires)
def time_out(promise, args):
    print(f"Command {promise.command} timed out.")

# Spawn a thread running some command that hangs
p = spawn `long-running.sh`:
    print("Finally completed.  Watcher method won't be called.")
    return True
 
p.watch(time_out)  # Does not wait.  Calls method "time_out" if this promise expires (i.e. command hangs)
 
# Do other things...The Promise TreeEachspawnissued inserts its promise object into the promise tree.  The outermostspawnwill generate the root
promise and each innerspawnwill be among its children.  There's no limit to how far it can nest.waitonly applies
to the promise on which it is called and is how it is different thanjoin.waitdoes not consider any other
promise state but the one it's called for, whereasjoinconsiders the one it's called forandanything below it
in the tree.The promise tree can be printed with thedump_tree()method on the promise.  This method is intended for
diagnostic purposes where it must be determined why spawned commands hung.dump_tree(subtree)accepts
a subtree promise as an argument.  If no arguments are passed,dump_tree()dumps from the root promise on down.# Simple example with no child promises
p = spawn `date`:
    return True
    
p.tree_dump()  # Dump tree from root
# or
p.tree_dump(subtree_promise)  # Dump tree from node in argumentExample dumping tree from subtree node:# Complex example with child and grandchild promises
# Demonstrates how to dump the promise tree from various points within it
p = spawn `date`:
    # Spawn child command (child promise)
    spawn `pwd`:
        # Spawn a grandchild to the parent promise
        spawn `python --version`:
            promise.tree_dump(promise)  # Dump the subtree from this point down
            return False
    # Spawn another child
     spawn `echo "blah"`:
         # Resolve parent promise
         promise.resolve_parent()
         # Resolve child promise
        return True
    # Do NOT resolve parent promise, let child do that
    return False
    
p.join()
p.tree_dump(p.children[0])  # Dump subtree from first child on down
p.tree_dump(p.children[1])  # Dump subtree from the second child
p.tree_dump(p.children[0].children[0]) # Dump subtree from the grandchild 

# Dump all children
for c in p.children:
    p.tree_dump(c)Parent and child joins shown in these two examples:root_promise = spawn `ls -lr`:
    for file in promise.stdout:
        t = f"touch {file}"
        spawn `$t` {"file" file}:  # This promise is a child of root
            print(f"{file} updated".)
            spawn `echo "done" > /tmp/done"`:  # Another child promise (root's grandchild)
                print("Complete")
                promise.resolve_parent()
                return True
            promise.resolve_parent()
            return False
    return False

root_promise.join()  # Wait on the root promise and all its children.  Thus, waiting for everything.root_promise = spawn `ls -lr`:
    for file in promise.output.stdout:
        t = f"touch {file}"
        spawn `$t` {"file" file}:  # This promise is a child of root
            print(f"{promise.args['file'])} updated")
            promise.join() # Wait for this promise and its children but not its parent (root)
            spawn `echo "done" > /tmp/done"`:
                print("Complete")Resolving a parent promise:p = spawn `ls -lrt`:
    for f in promise.output.stdout:
        cmd = f"touch {f}"
        # Spawn command from this resolver and pass our promise
        spawn `$cmd`:
            print("Resolving all promises")
            promise.resolve_parent() # Resolve parent promise here
            return True # Resolve child promise
        return False # Do NOT resolve parent promise here
p.join()  # Wait for ALL promises to be resolvedResults from Spawned CommandsSpawned commands return their results in thepromise.outputproperty of thepromiseobject passed to
the resolver block, and in the spawn expression if there is an assignment in that spawn expression.The result properties can then be accessed as followed:PropertyData TypeDescriptionpromise.output.stdoutListSTDOUT lines from the command normalized for displaypromise.output.stderrListSTDERR lines from the command normalized for displaypromise.output.exit_codeIntegerExit code value from commandpromise.output.cwdStringCurrent working directoryaftercommand was executedNotes:Watiba backticked commands can exist within the resolverOtherspawnblocks can be embedded within a resolver (recursion allowed)The command within thespawndefinition can be a variable
(The same rules apply as for all backticked shell commands.  This means the variable must contain
pure shell commands.)The leading dash to ignore CWDcannotbe used in thespawnexpressionThepromise.outputobject is not available untilpromise.resolved()returns TrueSimple example with the shell command as a Python variable:#!/usr/bin/python3

# run "date" command asynchronously 
d = 'date "+%Y/%m/%d"'
spawn `$d`:
    print(promise.output.stdout[0])
    return TrueExample with shell commands executed within resolver block:#!/usr/bin/python3

print("Running Watiba spawn with wait")
`rm /tmp/done`

# run "ls -lrt" command asynchronously 
p = spawn `ls -lrt`:
    print(f"Exit code: {promise.output.exit_code}")
    print(f"CWD: {promise.output.cwd}")
    print(f"STDERR: {promise.output.stderr}")

    # Loop through STDOUT from command
    for l in promise.output.stdout:
        print(l)
    `echo "Done" > /tmp/done`

    # Resolve promise
    return True

# Pause until spawn command is complete
p.wait()
print("complete")ThreadsEach promise produced from aspawnexpression results in one OS thread.  To access the
number of threads your code has spawned collectively, you can do the following:num_of_spawns = promise.spawn_count()  # Returns number of nodes in the promise tree
num_of_resolved_promises = promise.resolved_count() # Returns the number of promises resolved in treeRemote ExecutionShell commands can be executed remotely.  This is achieved though the SSH command, issued by Watiba, and has the
following requirements:OpenSSH is installed on the local and remote hostsThe local SSH key is in the remote'sauthorized_keysfile.The details of this
process is beyond the scope of this README.  For those instructions, consultwww.ssh.comMake sure that SSH'ing to the target host does not cause any prompts.Test that your SSH environment is setup first by manually entering:ssh {user}@{host} "ls -lrt"

# For example
ssh rwalk@walkubu "ls -lrt"

# If SSH prompts you, then Watiba remote execution cannot function.To execute a command remotely, a@hostparameter is suffixed to the backticked command.  The host name can be a
literal or a variable.  To employ a variable, prepend a$to the name following@such as@$var.Change SSH port for remote executionTo change the default SSH port 22 to a custom value, add to your Watiba code:watiba-ctl {"ssh-port": custom port}Example:watiba-ctl {"ssh-port": 2233}Examples:p = spawn `ls -lrt`@remoteserver {parms}:
    for line in promise.output.stdout:
        print(line)
    return Trueremotename = "serverB"
p = spawn `ls -lrt`@$remotename {parms}:
    for line in p.output.stdout:
        print(line)
    return Trueout = `ls -lrt`@remoteserver
for line in out.stdout:
    print(line)remotename = "serverB"
out = `ls -lrt`@$remotename
for line in out.stdout:
    print(line)Command HooksHooks are pre- or -post functions that are attached to acommandpattern, which is a regular expression (regex).  Anytime Watiba encounters a command
that matches the pattern for the hook, the hook function is called.All commands, spawned, remote, or local, can have Python functions executedbeforeexection, by default, orpost hooksthat are runafterthe command.  (Note: Post hooks are not run for spwaned commands because the resolver function is a post hook itself.)  These functions can be passed arguments, too.Command Hook Expressions# Run before commands that match that pattern
hook-cmd "pattern" hook-function parms

# Run before commands that match that pattern, but is non-recursive
hook-cmd-nr "pattern" hook-function parms 

# Run after commands that match that pattern
post-hook-cmd "pattern" hook-function parms

# Run after commands that match that pattern, but is non-recursive
post-hook-cmd-nr "pattern" hook-function parmsHook RecursionHooks, which are nothing more than Python functions called before or after a command is run, can issue their own commands and, thus, cause the hook
to be recursively called.  However, if the command in the hook block of code matches a command pattern that causes that same hook function to be run again,
an infinte loop can occur.  To prevent that, use the-nrsuffix on the Watiba hook expression. (-nr stands for non-recursive.)  This will ensure that
the hook cannot be re-invoked for any commands that are within it.To attach a hook:
1. Code one or more Python functions that will be the hooks.  At the end of each hook, you must return True if the hook was successful, or False
if something wrong.
2. Use the _hook-cmd_ expression to attach those hooks to a command
pattern, which is a regular expression
3. To remove the hooks, use the _remove-hooks "pattern"_ expression.  If a pattern, i.e. command regex pattern, is omitted, then all command hooks are removed.hook-cmd "command pattern" function parmsThe first parameter always passed to the hook function is the Pythonmatchobject from the command match.  This is provided so the hook has access
to the tokens on the command should it need them.Example:def my_hook(match, parms):
    print(match.groups())
    print(f'Tar file name is {match.group(1)}')
    print(parms["parmA"])
    print(parms["parmB"])
    return True  # Successful execution

def your_hook(match, parms):
    # This hook doesn't need the match object, so ignores it
    print(parms["something"])
    if parms["something-else"] != "blah":
        return False # Failed execution
    return True # Successful excution


# Add first hook to my tar command
hook-cmd "tar -zcvf (\S.*)" my_hook: {"parmA":"A", "parmB":"B"}

# Add another hook to my tar command
hook-cmd "tar -zcvf (\S.*)" your_hook: {"parmD":1, "parmE":"something"}

# Spawn command, but hooks will be invoked first...
spawn `tar -zcvf files.tar.gz /tmp/files/* `:
    # Resolver code block
    return True  # Resolve promiseYour parameters are whatever is valid for Python.  These are simply passed to their attached functions, essentially each one's key is the function name, as specified.Where are the hooks run for spawned commands?All hooks run under the thread of the issuer on the local host, not the target thread.Where are the hooks run for remote commands?As with spawned commands, all hooks are issued on the local host, not the remote.  Note that you
can have remote backticked commands in your hook and that will run those remotely.  If your remote command matches a hook(s) pattern, then those hooks will be run.  This means if your command pattern for the first remote call runs a hook that contains another remote command that matches that same command pattern, then the hook is run again.  Since this can lead to infinte hook loops, Watiba offers a non-recursive definition for the command pattern.  Note that this non-recursive setting
only applies to the command pattern and not the hook function itself.  So ifhookAis run for two different command patterns, say, "ls -lrt" and "ls -laF" you can
make one non-recusrive and still run the same hook for both commands.  For the recursive command pattern, the hook has no limit to its recursion.  For non-recursive,
it will only be called once during the recursion process.To set a command pattern as non-recursive, usehook-cmd-nr.Example using a variation on a previous example:def my_hook(match, parms)
    `tar -zcvf /tmp/files`  # my_hook will NOT because for this command even though it matches
    print("Will be called only once!")
    return True

# Note the "-nr" on the expression.  That's for non-recursive
hook-cmd-nr "tar -zcvf (\S.*)" my_hook: {"parmA":"A", "parmB":"B"}

# my_hook will be called before this command runs
` tar -zcvf tarball.tar.gz /home/user/files.*`Command ChainingWatiba extends its remote command execution to chaining commands across multiple remote hosts.  This is achieved
by thechainexpression.  This expression will execute the backticked command across a list of hosts, passed by
the user, sequentially, synchronously until the hosts list is exhausted, or the command fails.chainreturns a
Python dictionary where the keys are the host names and the values the WTOutput from the command run on that host.Chain ExceptionThechainexpression raises a WTChainException on the first failed command.  The exception raised
has the following properties:WTChainException:PropertyData TypeDescriptioncommandStringCommand that failedhostStringHost where command failedmessageStringError messageoutputWTOutput structure:stdoutstderrexit_codecwdOutput from commandImport this exception to catch it:from watiba import WTChainExceptionExamples:from watiba import WTChainException

try:
    out = chain `tar -zcvf backup/file.tar.gz dir/*` {"hosts", ["serverA", "serverB"]}
    for host,output in out.items():
        print(f'{host} exit code: {output.exit_code}')
        for line in output.stderr:
            print(line)
 except WTChainException(ex):
    print(f"Error: {ex.message}")
    print(f"  host: {ex.host} exit code: {ex.output.exit_code} command: {ex.command})Command Chain Piping (Experimental)Thechainexpression supports piping STDOUT and/or STDERR to other commands executed on remote servers.  Complex
arrangements can be constructed through the Python dictionary passed to thechainexpression.  The dictionary
contents function as follows:"hosts": [server, server, ...]   This entry instructionschainon which hosts the backticked command will run.
This is a required entry."stdout": {server:command, server:command, ...}
This is an optional entry."stderr": {server:command, server:command, ...}
This is an optional entry.Just like achainexpression that does not pipe output, the return object is a dictionary of WTOutput object keyed
by the host name from thehostslist andnotfrom the commands recieving the piped output.If any command fails, a WTChainException is raised.  Import this exception to catch it:from watiba import WTChainExceptionNote:The piping feature is experimental as of this release, and a better design will eventually
supercede it.Examples:from watiba import WTChainException

# This is a simple chain with no piping
try:
    args = {"hosts": ["serverA", "serverB", "serverC"]}
    out = chain `ls -lrt dir/` args
    for host, output in out.items():
        print(f'{host} exit code: {output.exit_code}')
except WTChainException as ex:
    print(f'ERROR: {ex.message}, {ex.host}, {ex.command}, {ex.output.stderr}')# This is a more complex chain that runs the "ls -lrt" command on each server listed in "hosts"
# and pipes the STDOUT output from serverC to serverV and serverD, to those commands, and serverB's STDERR
# to serverX and its command
try:
    args = {"hosts": ["serverA", "serverB", "serverC"],
                "stdout": {"serverC":{"serverV": "grep something", "serverD":"grep somethingelse"}},
                "stderr": {"serverB":{"serverX": "cat >> /tmp/serverC.err"}}
           }
    out = chain `ls -lrt dir/` args
    for host, output in out.items():
        print(f'{host} exit code: {output.exit_code}')
except WTChainException as ex:
    print(f'ERROR: {ex.message}, {ex.host}, {ex.command}, {ex.output.stderr}')####How does this work?
Watiba will run the backticked command in the expression on each host listed inhosts, in sequence and synchronously.
If there is a "stdout" found in the arguments, then it will name the source host as the key, i.e. the host from which
STDOUT will be read, and fed to each host and command listed under that host.  This is true for STDERR as well.The method in which Watiba feeds the piped output is through a anechocommand shell piped to the command to be run
on that host.  So, "stdout": {"serverC":{"serverV": "grep something"}} causes Watiba to read each line of STDOUT from
serverC and issueecho "$line" | grep somethingon serverV.  It is piping from serverC to serverV.InstallationPIPIf you installed this as a Python package, e.g. pip, then the pre-compiler,watiba-c,
will be placed in your system's PATH by PIP.GITHUBIf you cloned this from github, you'll still need to install the package with pip, first, for the
watbia module.  Follow these steps to install Watiba locally.# Watiba package required
python3 -m pip install watibaPre-compilingTest that the pre-compiler functions in your environment:watiba-c versionFor example:rwalk@walkubu:~$ watiba-c version
Watiba 0.3.26To pre-compile a .wt file:watiba-c my_file.wt > my_file.py
chmod +x my_file.py
./my_file.pyWheremy_file.wtis your Watiba code.Code Examplesmy_file.wt#!/usr/bin/python3

# Stand alone commands.  One with directory context, one without

# This CWD will be active until a subsequent command changes it
`cd /tmp`

# Simple statement utilizing command and results in one statement
print(`cd /tmp`.cwd)

# This will not change the Watiba CWD context, because of the dash prefix, but within 
# the command itself the cd is honored.  file.txt is created in /home/user/blah but
# this does not impact the CWD of any subsequent commands.  They
# are still operating from the previous cd command to /tmp
-`cd /home/user/blah && touch file.txt`

# This will print "/tmp" _not_ /home because of the leading dash on the command
print(f"CWD is not /home: {-`cd /home`.cwd)}"

# This will find text files in /tmp/, not /home/user/blah  (CWD context!)
w=`find . -name '*.txt'`
for l in w.stdout:
    print(f"File: {l}")


# Embedding commands in print expressions that will print the stderr output, which tar writes to
print(`echo "Some textual comment" > /tmp/blah.txt && tar -zcvf /tmp/blah.tar.gz /tmp`).stdout)

# This will print the first line of stdout from the echo
print(`echo "hello!"`.stdout[0])

# Example of more than one command in a statement line
if len(`ls -lrt`.stdout) > 0 or len(-`cd /tmp`.stdout) > 0:
    print("You have stdout or stderr messages")


# Example of a command as a Python varible and
#  receiving a Watiba object
cmd = "tar -zcvf /tmp/watiba_test.tar.gz /mnt/data/git/watiba/src"
cmd_results = `$cmd`
if cmd_results.exit_code == 0:
    for l in cmd_results.stderr:
        print(l)

# Simple reading of command output
#  Iterate on the stdout property
for l in `cat blah.txt`.stdout:
    print(l)

# Example of a failed command to see its exit code
xc = `lsvv -lrt`.exit_code
print(f"Return code: {xc}")

# Example of running a command asynchronously and resolving promise
spawn `cd /tmp && tar -zxvf tarball.tar.gz`:
    for l in promise.output.stderr:
        print(l)
    return True  # Mark promise resolved


# List dirs from CWD, iterate through them, spawn a tar command
# then within the resolver, spawn a move command
# Demonstrates spawns within resolvers
for dir in `ls -d *`.stdout:
    tar = "tar -zcvf {}.tar.gz {}"
    prom = spawn `$tar` {"dir": dir}:
        print(f"{}args['dir'] tar complete")
        mv = f"mv -r {args['dir']}/* /tmp/."
        spawn `$mv`:
            print("Move done")
            # Resolve outer promise
            promise.resolve_parent()
            return True
        # Do not resolve this promise yet.  Let the inner resolver do it
        return False
    prom.join()