Locks
Orchestrator runs many workflows at once. Usually that’s what you want. It goes wrong when two runs change the same thing at the same time: both read a counter that says 7, both write 8, and one run’s work is lost. The same happens with a shared file, a pool of IP addresses, a ticket number, or a vCenter folder two runs try to create at the same moment.
A lock makes runs take turns. Before a run touches the shared thing, it asks Orchestrator for a lock with a name everyone agrees on. If another run holds it, it waits. When it’s done, it gives the lock back, and the next run goes. In this recipe you watch five runs lose updates to a counter, fix it with a lock, and then deal with the part that bites in production: a run that fails while it holds a lock.
Getting ready
- Recipe 3.8, if you haven’t started workflows from a script before: this recipe starts five runs at once from a small workflow.
- The folders VCF Orchestrator Guide/Chapter 7 under Library > Workflows and under Assets > Configurations.
- Recipe 4.7, if you haven’t worked with configuration elements from scripts before.
How to do it
A shared counter
- Go to Assets > Configurations, open VCF Orchestrator Guide/Chapter 7, and click New Configuration. Name it
vcfguide-ch7-state, and add one variable,runCount, of typenumber, with the value0. Save it. - In VCF Orchestrator Guide/Chapter 7, create the workflow Count a run, with no inputs. Add a scriptable task called
Add one:
var category = Server.getConfigurationElementCategoryWithPath("VCF Orchestrator Guide/Chapter 7");var state = null;for (var i = 0; i < category.configurationElements.length; i++) { if (category.configurationElements[i].name === "vcfguide-ch7-state") { state = category.configurationElements[i]; }}var before = state.getAttributeWithKey("runCount").value;System.sleep(2000); // makes the gap between read and write wide enough to seestate.setAttributeWithKey("runCount", before + 1);System.log("runCount " + before + " -> " + (before + 1));- Save the workflow.
Watch it lose updates
- In the same folder, create the workflow Start five counts, with one input,
countWorkflow, of typeWorkflow. Add a scriptable task calledStart five, withcountWorkflowas its input.executestarts a run and returns at once, without waiting for it, so the five runs start within a few milliseconds of each other:
// Start five runs of the chosen workflow at (almost) the same momentvar tokens = [];for (var n = 1; n <= 5; n++) { tokens.push(countWorkflow.execute(new Properties()));}System.log("Started " + tokens.length + " runs of " + countWorkflow.name);Save it, click Run, pick Count a run for countWorkflow, and click Run.
runCount ends at without a lock, for Figure 7.13.- When the five runs have finished, open
vcfguide-ch7-state.runCountis less than5, often1. Open the runs under Activity > Workflow Runs: several of them logged the same line, runCount 0 -> 1. They all read the old value before any of them wrote the new one.
Activity > Workflow Runs filtered on Count a run: five runs started within the same second, all Completed; one of them open on the Logs tab with runCount 0 -> 1; beside it, vcfguide-ch7-state with runCount = 1.
Fix it with a lock
- Set
runCountback to0and save the configuration element. - Change the end of the
Add onescript, from the line that readsbefore, so that the read and the write happen under a lock:
var lockId = "vcfguide-ch7-state";var owner = workflow.id; // this run's IDLockingSystem.lockAndWait(lockId, owner);try { var before = state.getAttributeWithKey("runCount").value; System.sleep(2000); state.setAttributeWithKey("runCount", before + 1); System.log("runCount " + before + " -> " + (before + 1));} finally { LockingSystem.unlock(lockId, owner);}- Save, and start five runs again with the loop from step 4. This time the runs take about ten seconds in all, because they take turns, and
runCountends at5. Each run’s log has a different line, from runCount 0 -> 1 to runCount 4 -> 5.
Activity > Workflow Runs filtered on Count a run: five runs with start times in the same second and end times about two seconds apart; the Logs tabs of two runs side by side, runCount 2 -> 3 and runCount 3 -> 4; vcfguide-ch7-state with runCount = 5.
vco01 and, if you can, on the three-node cluster from recipe 2.4, and record the final runCount with and without the lock. Also confirm that setAttributeWithKey is visible to the next run at once (recipe 4.7 has the same check), because a write that’s cached per node would defeat the lock on a cluster.Don’t wait for ever
lockAndWaitwaits as long as it takes. If a run never gives the lock back, every run after it waits too. When waiting isn’t acceptable, try for the lock a limited number of times instead. Replace thelockAndWaitline with:
var tries = 0;while (!LockingSystem.lock(lockId, owner)) { tries++; if (tries >= 30) { throw "Gave up waiting for lock " + lockId + " after " + (tries * 2) + " seconds"; } System.sleep(2000);}Find and release a lock that was left behind
- Simulate a run that dies with the lock held. Duplicate Count a run as Hold the lock, and in its script remove the
tryandfinallyand theunlockcall, so the run takes the lock and never gives it back. Run it once. - Run Count a run. With step 9’s loop it fails after a minute with Gave up waiting for lock vcfguide-ch7-state.
- List the locks the server holds. Create the action
com.vcfguide.chapter7/listLockswith no inputs and the return typeArray/string:
var locks = LockingSystem.retrieveAll();for (var i = 0; i < locks.length; i++) { System.log(locks[i]);}return locks;Run it. One entry names the lock vcfguide-ch7-state and the ID of the Hold the lock run as its owner.
- Release that one lock, and no other, with a one-line script run as an administrator:
LockingSystem.unlock("vcfguide-ch7-state", "<owner from step 12>");. Run Count a run again. It succeeds. - Delete Hold the lock.
Run of the action listLocks, Logs tab: one entry naming vcfguide-ch7-state and the token ID of the Hold the lock run as owner; behind it, the failed run of Count a run with Gave up waiting for lock vcfguide-ch7-state after 60 seconds.
On 9.1.1, LockingSystem.retrieveAll() returns an array of strings, one per lock, each the lock ID and the owner joined by a comma, such as vcfguide-runcount,Count runs. The library folder Locking has Display all locks and Release all locks, plus two test workflows, Locking test and Locking test (x5), that take locks so you can see them listed.
How it works
A lock is a name and an owner. The LockingSystem object keeps a list of locks on the Orchestrator server. Each one is just two strings: the lock ID, which you choose, and the owner, which says who holds it. Orchestrator doesn’t know or care what the lock protects. Every workflow that touches the shared thing must ask for the same lock ID, or the lock protects nothing.
| Call | What it does |
|---|---|
LockingSystem.lock(id, owner) |
Takes the lock if it’s free and returns true. Returns false at once if someone else holds it. |
LockingSystem.lockAndWait(id, owner) |
Takes the lock, waiting for as long as it takes. |
LockingSystem.unlock(id, owner) |
Releases the lock, if this owner holds it. |
LockingSystem.retrieveAll() |
Lists the locks held on the server. |
LockingSystem.unlockAll() |
Releases every lock on the server, whoever holds it. |
The owner. Use workflow.id, the ID of the run, as the owner. It’s unique to the run, and it’s the first thing you’ll want to know when a lock is stuck: which run took it. Don’t use the workflow’s name or a fixed string, because then two runs of the same workflow count as the same owner and the lock doesn’t keep them apart. In an action, workflow isn’t available. Pass the owner in as an input instead.
Locks outlive runs. A lock is released only when someone calls unlock. Orchestrator doesn’t release it when the run that took it fails, is cancelled, or the server restarts. The try/finally in step 7 releases the lock when the script throws. A run that’s cancelled, or a node that dies in the middle, still leaves the lock behind, which is why steps 9 and 12 matter: a bounded wait so the queue doesn’t freeze, and a way to see who holds what.
vco-app pods, and are shared by all nodes of a cluster are inferred, not documented. Check them on 9.1.1: take a lock with Hold the lock, restart the pods, and run listLocks; on the cluster from recipe 2.4, take the lock on one node and try it from a run on another.Waiting costs little. lockAndWait, and the System.sleep in step 9, keep the run in the Running state but don’t use the processor while they wait. A queue of runs waiting for a lock still counts against the server’s limit of concurrent runs. Keep what you do under a lock short, and do the slow work, such as cloning a VM, outside it.
Locks and the canvas. Step 7 takes and releases the lock in one scriptable task. When the protected work spans several elements, take the lock in a scriptable task at the start, release it in a scriptable task at the end, and release it again in the workflow’s error path (recipe 3.4), so that a failure in any element gives the lock back.
LockingSystem in scripts, and use the Locking workflows in the library to look at and release locks.LockingSystem calls are the same in 9.x. We found no page for locks in the browser client, so a short action like listLocks is the way to see who holds what.There's more
Never call unlockAll from a workflow. It releases every lock on the server, including locks other teams’ runs hold right now, and lets their runs collide. Keep it for the moment after an outage when an administrator has checked that no run should be holding anything.
Name locks after what they protect. vcfguide-ch7-state says what’s locked. A lock per object, such as vcfguide-vm- followed by a VM’s ID, lets runs that touch different VMs go in parallel and only queues the ones that touch the same VM.
One lock at a time. If a run takes lock A and then waits for lock B, while another run holds B and waits for A, both wait for ever. Take one lock at a time where you can. Where you can’t, every workflow must take them in the same order, for example sorted by name.
Locks and configuration elements. Recipe 4.7 warned that runs updating the same configuration element at once can lose updates. This recipe is the fix. If many runs update a value, consider whether it should be in a configuration element at all. A database (recipe 5.4) has its own transactions and locking, and handles many writers better.
Locks don’t cross servers. A lock on vco01 means nothing to the Orchestrator at auto.vmw.lab. If two Orchestrators can change the same thing, the lock must live somewhere both can reach, such as a row in a shared database.
See also
- 3.4 Handling errors, for releasing a lock on the error path.
- 4.7 Working with configuration elements in code, for the configuration element calls used here.
- 7.2 Starting workflows from scripts, for starting runs from a shell.
- Marc Huppert, Process locking made easy in VCF Automation, on the
LockingSystemin VCF Automation’s Orchestrator. - vRO Locking System, a short example of
lock,lockAndWait,unlockandunlockAll, and of releasing a lock on the error path. - CloudBlogger, the author’s blog: Stop the Race Condition: AtomicInteger class in Orchestrator.
