8784: Fix test for latest firefox.
[arvados.git] / doc / user / topics / run-command.html.textile.liquid
1 ---
2 layout: default
3 navsection: userguide
4 title: "run-command reference"
5 ...
6
7 {% include 'pipeline_deprecation_notice' %}
8
9 The @run-command@ crunch script enables you run command line programs.
10
11 {% include 'tutorial_expectations_workstation' %}
12
13 h1. Using run-command
14
15 The basic @run-command@ process evaluates its inputs and builds a command line, executes the command, and saves the contents of the output directory back to Keep.  For large datasets, @run-command@ can schedule concurrent tasks to execute the wrapped program over a range of inputs (see @task.foreach@ below.)
16
17 @run-command@ is controlled through the @script_parameters@ section of a pipeline component.  @script_parameters@ is a JSON object consisting of key-value pairs.  There are three categories of keys that are meaningful to run-command:
18 * The @command@ section defining the template to build the command line of task
19 * Special processing directives such as @task.foreach@ @task.cwd@ @task.vwd@ @task.stdin@ @task.stdout@
20 * User-defined parameters (everything else)
21
22 In the following examples, you can use "dry run mode" to determine the command line that @run-command@ will use without actually running the command.  For example:
23
24 <notextile>
25 <pre><code>~$ <span class="userinput">cd $HOME/arvados/crunch_scripts</span>
26 ~$ <span class="userinput">./run-command --dry-run --script-parameters '{
27   "command": ["echo", "hello world"]
28 }'</span>
29 run-command: echo hello world
30 </code></pre>
31 </notextile>
32
33 h2. Command template
34
35 The value of the "command" key is a list.  The first parameter of the list is the actual program to invoke, followed by the command arguments.  The simplest @run-command@ invocation simply runs a program with static parameters.  In this example, run "echo" with the first argument "hello world":
36
37 <pre>
38 {
39   "command": ["echo", "hello world"]
40 }
41 </pre>
42
43 Running this job will print "hello world" to the job log.
44
45 By default, the command will start with the current working directory set to the output directory.  Anything written to the output directory will be saved to Keep when the command is finished.  You can change the default working directory using @task.cwd@ and get the path to the output directory using @$(task.outdir)@ as explained below.
46
47 Items in the "command" list may include lists and objects in addition to strings.  Lists are flattened to produce the final command line.  JSON objects are evaluated as list item functions (see below).  For example, the following evaluates to @["echo", "hello", "world"]@:
48
49 <pre>
50 {
51   "command": ["echo", ["hello", "world"]]
52 }
53 </pre>
54
55 Finally, if "command" is a list of lists, it specifies a Unix pipeline where the standard output of the previous command is piped into the standard input of the next command.  The following example describes the Unix pipeline @cat foo | grep bar@:
56
57 <pre>
58 {
59   "command": [["cat", "foo"], ["grep", "bar"]]
60 }
61 </pre>
62
63 h2. Parameter substitution
64
65 The "command" list can include parameter substitutions.  Substitutions are enclosed in "$(...)" and may contain the name of a user-defined parameter.  In the following example, the value of "a" is "hello world"; so when "command" is evaluated, it will substitute "hello world" for "$(a)":
66
67 <pre>
68 {
69   "a": "c1bad4b39ca5a924e481008009d94e32+210/var-GS000016015-ASM.tsv.bz2",
70   "command": ["echo", "$(file $(a))"]
71 }
72 </pre>
73
74 table(table table-bordered table-condensed).
75 |_. Function|_. Action|
76 |$(file ...)       | Takes a reference to a file within an Arvados collection and evaluates to a file path on the local file system where that file can be accessed by your command.  Will raise an error if the file is not accessible.|
77 |$(dir ...)        | Takes a reference to an Arvados collection or directory within an Arvados collection and evaluates to a directory path on the local file system where that directory can be accessed by your command.  The path may include a file name, in which case it will evaluate to the parent directory of the file.  Uses Python's os.path.dirname(), so "/foo/bar" will evaluate to "/foo" but "/foo/bar/" will evaluate to "/foo/bar".  Will raise an error if the directory is not accessible. |
78 |$(basename&nbsp;...)   | Strip leading directory and trailing file extension from the path provided.  For example, $(basename /foo/bar.baz.txt) will evaluate to "bar.baz".|
79 |$(glob ...)       | Take a Unix shell path pattern (supports @*@ @?@ and @[]@) and search the local filesystem, returning the first match found.  Use together with $(dir ...) to get a local filesystem path for Arvados collections.  For example: $(glob $(dir $(mycollection)/*.bam)) will find the first .bam file in the collection specified by the user parameter "mycollection".  If there is more than one match, which one is returned is undefined.  Will raise an error if no matches are found.|
80 |$(task.tmpdir)|Designated temporary directory.  This directory will be discarded when the job completes.|
81 |$(task.outdir)|Designated output directory.  The contents of this directory will be saved to Keep when the job completes.  A symlink to a file in the keep mount will reference existing Keep blocks in your job output collection, with no data copying or duplication.|
82 |$(job.srcdir)|Path to the git working directory ($CRUNCH_SRC).|
83 |$(node.cores)|Number of CPU cores on the node.|
84 |$(job.uuid)|Current job uuid ($JOB_UUID)|
85 |$(task.uuid)|Current task uuid ($TASK_UUID)|
86
87 h3. Escape sequences
88
89 If your command includes a @$()@ sequence that shouldn't be interpreted by run-command&mdash;for example, because you're writing shell code that calls a subcommand&mdash;you can prevent run-command from interpreting it by placing a backslash in front of the @$@ character.  Note that JSON also uses backslash to escape characters, so you'll need to write two backslashes for run-command to see one after parsing the parameter.  This example uppercases all alphabetic characters in the "pattern" parameter before using it as a regular expression in grep:
90
91 <pre>{"command": ["bash", "-c", "grep \\$(echo '$(pattern)' | tr a-z A-Z) '$(input)'"]}</pre>
92
93 You can put a literal backslash in your command by escaping it with another backslash.  Ultimately this means that where the primary Unix command includes a single backslash, you'll need to write four backslashes: double the backslashes for run-command escaping, then double them again for JSON escaping.
94
95 <pre>{"command": ["grep", "\\\\bword\\\\b", "$(input)"]}</pre>
96
97 h2. List context
98
99 Where specified by the documentation, parameters may be evaluated in a "list context".  That means the value will evaluate to a list instead of a string.  Parameter values can be a static list, a path to a file, a path to a directory, or a JSON object describing a list context function.
100
101 If the value is a string, it is interpreted as a path.  If the path specifies a regular file, that file will be opened as a text file and produce a list with one item for each line in the file (end-of-line characters will be stripped).  If the path specifies a directory, produce a list containing all of the entries in the directory.  Note that parameter expansion is not performed on list items produced this way.
102
103 If the value is a static list, it will evaluate each item and return the expanded list.  Each item may be a string (evaluated for parameter substitution), a list (recursively evaluated), or a JSON object (indicating a list function, described below).
104
105 If the value is a JSON object, it is evaluated as a list function described below.
106
107 h2. List functions
108
109 When @run-command@ is evaluating a list (such as "command"), in addition to string parameter substitution, you can use list item functions.  In the following functions, you specify the name of a user parameter to act on (@"$(a)"@ in the first example); the value of that user parameter will be evaluated in a list context (as described above) to get the list value. Alternately, you can provide list value directly in line.  As an example, the following two fragments yield the same result:
110
111 <pre>
112 {
113   "a": ["alice", "bob"],
114   "command": ["echo", {"foreach": "$(a)",
115                        "var": "a_var",
116                        "command": ["--something", "$(a_var)"]}]
117 }
118 </pre>
119
120 <pre>
121 {
122   "command": ["echo", {"foreach": ["alice", "bob"],
123                        "var": "a_var",
124                        "command": ["--something", "$(a_var)"]}]
125 }
126 </pre>
127
128 Note: when you provide the list inline with "foreach" or "index", you must include the "var" parameter to specify the substitution variable name to use when evaluating the command fragment.
129
130 You can also nest functions.  This filters @["alice", "bob", "betty"]@ on the regular expression @"b.*"@ to get the list @["bob", "betty"]@, assigns @a_var@ to each value of the list, then expands @"command"@ to get @["--something", "bob", "--something", "betty"]@.
131
132 <pre>
133 {
134   "command": ["echo", {"foreach": {"filter": ["alice", "bob", "betty"],
135                                    "regex": "b.*"},
136                        "var": "a_var",
137                        "command": ["--something", "$(a_var)"]}]
138 }
139 </pre>
140
141 h3. foreach
142
143 The @foreach@ list item function (not to be confused with the @task.foreach@ directive) expands a command template for each item in the specified user parameter (the value of the user parameter is evaluated in a list context, as described above).  The following example will evaluate "command" to @["echo", "--something", "alice", "--something", "bob"]@:
144
145 <pre>
146 {
147   "a": ["alice", "bob"],
148   "command": ["echo", {"foreach": "$(a)",
149                        "var": "a_var",
150                        "command": ["--something", "$(a_var)"]}]
151 }
152 </pre>
153
154 h3. index
155
156 This function extracts a single item from a list.  The value of @index@ is zero-based (i.e. the first item is at index 0, the second item index 1, etc).  The following example will evaluate "command" to @["echo", "--something", "bob"]@:
157
158 <pre>
159 {
160   "a": ["alice", "bob"],
161   "command": ["echo", {"list": "$(a)",
162                        "var": "a_var",
163                        "index": 1,
164                        "command": ["--something", "$(a_var)"]}]
165 }
166 </pre>
167
168 h3. filter
169
170 Filter the list so that it only includes items that match a regular expression.  The following example will evaluate to @["echo", "bob"]@
171
172 <pre>
173 {
174   "a": ["alice", "bob"],
175   "command": ["echo", {"filter": "$(a)",
176                        "regex": "b.*"}]
177 }
178 </pre>
179
180 h3. group
181
182 Generate a list of lists, where items are grouped on common subexpression match.  Items which don't match the regular expression are excluded.  In the following example, the subexpression is @(a?)@, resulting in two groups, strings that contain the letter 'a' and strings that do not.  The following example evaluates to @["echo", "--group", "alice", "carol", "dave", "--group", "bob", "betty"]@:
183
184 <pre>
185 {
186   "a": ["alice", "bob", "betty", "carol", "dave"],
187   "b": {"group": "$(a)",
188         "regex": "[^a]*(a?).*"},
189   "command": ["echo", {"foreach": "$(b)",
190                        "var": "b_var",
191                        "command": ["--group", "$(b_var)"]}]
192 }
193 </pre>
194
195 h3. extract
196
197 Generate a list of lists, where items are split by subexpression match.  Items which don't match the regular expression are excluded.  The following example evaluates to @["echo", "--something", "c", "a", "rol", "--something", "d", "a", "ve"]@:
198
199 <pre>
200 {
201   "a": ["alice", "bob", "carol", "dave"],
202   "b": {"extract": "$(a)",
203         "regex": "(.+)(a)(.*)"},
204   "command": ["echo", {"foreach": "$(b)",
205                        "var": "b_var",
206                        "command": ["--something", "$(b_var)"]}]
207 }
208 </pre>
209
210 h3. batch
211
212 Generate a list of lists, where items are split into a batch size.  If the list does not divide evenly into batch sizes, the last batch will be short.  The following example evaluates to @["echo", "--something", "alice", "bob", "--something", "carol", "dave"]@
213
214 <pre>
215 {
216   "a": ["alice", "bob", "carol", "dave"],
217   "command": ["echo", {"foreach":{"batch": "$(a)",
218                                   "size": 2},
219                        "var": "a_var",
220                        "command": ["--something", "$(a_var)"]}]
221 }
222 </pre>
223
224 h2. Directives
225
226 Directives alter the behavior of run-command.  All directives are optional.
227
228 h3. task.cwd
229
230 This directive sets the initial current working directory in which your command will run.  If @task.cwd@ is not specified, the default current working directory is @task.outdir@.
231
232 h3. task.ignore_rcode
233
234 By Unix convention a task which exits with a non-zero return code is considered failed.  However, some programs (such as @grep@) return non-zero codes for conditions that should not be considered fatal errors.  Set @"task.ignore_rcode": true@ to indicate the task should always be considered a success regardless of the return code.
235
236 h3. task.stdin and task.stdout
237
238 Provide standard input and standard output redirection.
239
240 @task.stdin@ must evaluate to a path to a file to be bound to the standard input stream of the command.  When command describes a Unix pipeline, this goes into the first command.
241
242 @task.stdout@ specifies the desired file name in the output directory to save the content of standard output.  When command describes a Unix pipeline, this captures the output of the last command.
243
244 h3. task.env
245
246 Set environment variables for the command.  Accepts an object mapping environment variables to the desired values.  Parameter substitution is performed on values, but not on the environment variable names themselves.  Example usage:
247
248 <pre>
249 {
250   "command": ["/bin/sh", "-c", "echo $MY_ENV_VAR"],
251   "task.env": {
252     "MY_ENV_VAR": "Hello world!"
253   }
254 }
255 </pre>
256
257 h3. task.vwd
258
259 Background: because Keep collections are read-only, this does not play well with certain tools that expect to be able to write their outputs alongside their inputs (such as tools that generate indexes that are closely associated with the original file.)  The run-command's solution to this is the "virtual working directory".
260
261 @task.vwd@ specifies a Keep collection with the starting contents of the output directory.  @run-command@ will populate @task.outdir@ with directories and symlinks to mirror the contents of the @task.vwd@ collection.  Your command will then be able to both access its input files and write its output files from within @task.outdir@.  When the command completes, run-command will write the contents of the output directory, which will include the output of your command as well as symlinks to files in starting collection.  Note that files from the starting collection remain read-only and cannot be altered, but may be deleted or renamed.
262
263 h3. task.foreach
264
265 Using @task.foreach@, you can run your command concurrently over large datasets.
266
267 @task.foreach@ takes the names of one or more user-defined parameters.  The value of these parameters are evaluated in a list context.  @run-command@ then generates tasks based on the Cartesian product (i.e. all combinations) of the input lists.  The outputs of all tasks are merged to create the final output collection.  Note that if two tasks output a file in the same directory with the same name, that file will be concatenated in the final output.  In the following example, three tasks will be created for the "grep" command, based on the contents of user parameter "a":
268
269 <pre>
270 {
271   "command": ["echo", "$(a)"],
272   "task.foreach": "a",
273   "a": ["alice", "bob", "carol"]
274 }
275 </pre>
276
277 This evaluates to the commands:
278 <notextile>
279 <pre>
280 ["echo", "alice"]
281 ["echo", "bob"]
282 ["echo", "carol"]
283 </pre>
284 </notextile>
285
286 You can also specify multiple parameters:
287
288 <pre>
289 {
290   "a": ["alice", "bob"],
291   "b": ["carol", "dave"],
292   "task.foreach": ["a", "b"],
293   "command": ["echo", "$(a)", "$(b)"]
294 }
295 </pre>
296
297 This evaluates to the commands:
298
299 <pre>
300 ["echo", "alice", "carol"]
301 ["echo", "alice", "dave"]
302 ["echo", "bob", "carol"]
303 ["echo", "bob", "dave"]
304 </pre>
305
306 h1. Examples
307
308 The following is a single task pipeline using @run-command@ to run the bwa alignment tool to align a single paired-end read fastq sample.  The input to this pipeline is the reference genome and a collection consisting of two fastq files for the read pair.
309
310 <notextile>{% code 'run_command_simple_example' as javascript %}</notextile>
311
312 The following is a concurrent task pipeline using @run-command@ to run the bwa alignment tool to align a set of fastq reads over multiple samples.  The input to this pipeline is the reference genome and a collection consisting subdirectories for each sample, with each subdirectory containing pairs of fastq files for each set of reads.
313
314 <notextile>{% code 'run_command_foreach_example' as javascript %}</notextile>