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.

309 lines
11 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. +++
  2. title = "Supercharge Your Bash Scripts with Multiprocessing"
  3. date = "2021-05-05T17:08:12+03:00"
  4. author = "Yigit Colakoglu"
  5. authorTwitter = "theFr1nge"
  6. cover = "images/supercharge-your-bash-scripts-with-multiprocessing.png"
  7. tags = ["bash", "scripting", "programming"]
  8. keywords = ["bash", "scripting"]
  9. description = "Bash is a great tool for automating tasks and improving your workflow. However, it is SLOW. Adding multiprocessing to the scripts you write can improve the performance greatly."
  10. showFullContent = false
  11. draft=false
  12. +++
  13. Bash is a great tool for automating tasks and improving your workflow. However,
  14. it is ***SLOW***. Adding multiprocessing to the scripts you write can improve
  15. the performance greatly.
  16. ## What is multiprocessing?
  17. In the simplest terms, multiprocessing is the principle of splitting the
  18. computations or jobs that a script has to do and running them on different
  19. processes. In even simpler terms however, multiprocessing is the computer
  20. science equivalent of hiring more than one
  21. worker when you are constructing a building.
  22. ### Introducing "&"
  23. While implementing multiprocessing the sign `&` is going to be our greatest
  24. friend. It is an essential sign if you are writing bash scripts and a very
  25. useful tool in general when you are in the terminal. What `&` does is that it
  26. makes the command you added it to the end of run in the background and allows
  27. the rest of the script to continue running as the command runs in the
  28. background. One thing to keep in mind is that since it creates a fork of the
  29. process you ran the command on, if you change a variable that the command in the
  30. background uses while it runs, it will not be affected. Here is a simple
  31. example:
  32. {{< code language="bash" id="1" expand="Show" collapse="Hide" isCollapsed="false" >}}
  33. foo="yeet"
  34. function run_in_background(){
  35. sleep 0.5
  36. echo "The value of foo in the function run_in_background is $foo"
  37. }
  38. run_in_background & # Spawn the function run_in_background in the background
  39. foo="YEET"
  40. echo "The value of foo changed to $foo."
  41. wait # wait for the background process to finish
  42. {{< /code >}}
  43. This should output:
  44. ```
  45. The value of foo changed to YEET.
  46. The value of foo in here is yeet
  47. ```
  48. As you can see, the value of `foo` did not change in the background process even though
  49. we changed it in the main function.
  50. ## Baby steps...
  51. Just like anything related to computer science, there is more than one way of
  52. achieving our goal. We are going to take the easier, less intimidating but less
  53. efficient route first before moving on to the big boy implementation. Let's open up vim and get to scripting!
  54. First of all, let's write a very simple function that allows us to easily test
  55. our implementation:
  56. {{< code language="bash" id="1" expand="Show" collapse="Hide" isCollapsed="false" >}}
  57. function tester(){
  58. # A function that takes an int as a parameter and sleeps
  59. echo "$1"
  60. sleep "$1"
  61. echo "ENDED $1"
  62. }
  63. {{< /code >}}
  64. Now that we have something to run in our processes, we now need to spawn several
  65. of them in controlled manner. Controlled being the keyword here. That's because
  66. each system has a maximum number of processes that can be spawned (You can find
  67. that out with the command `ulimit -u`). In our case, we want to limit the
  68. processes being ran to the variable `num_processes`. Here is the implementation:
  69. {{< code language="bash" id="1" expand="Show" collapse="Hide" isCollapsed="false" >}}
  70. num_processes=$1
  71. pcount=0
  72. for i in {1..10}; do
  73. ((pcount=pcount%num_processes));
  74. ((pcount++==0)) && wait
  75. tester $i &
  76. done
  77. {{< /code >}}
  78. What this loop does is that it takes the number of processes you would like to
  79. spawn as an argument and runs `tester` in that many processes. Go ahead and test it out!
  80. You might notice however that the processes are run int batches. And the size of
  81. batches is the `num_processes` variable. The reason this happens is because
  82. every time we spawn `num_processes` processes, we `wait` for all the processes
  83. to end. This implementation is not a problem in itself, there are many cases
  84. where you can use this implementation and it works perfectly fine. However, if
  85. you don't want this to happen, we have to dump this naive approach all together
  86. and improve our tool belt.
  87. ## Real Chads use Job Pools
  88. The solution to the bottleneck that was introduced in our previous approach lies
  89. in using job pools. Job pools are where jobs created by a main process get sent
  90. and wait to get executed. This approach solves our problems because instead of
  91. spawning a new process for every copy and waiting for all the processes to
  92. finish we instead only create a set number of processes(workers) which
  93. continuously pick up jobs from the job pool not waiting for any other process to finish.
  94. Here is the implementation that uses job pools. Brace yourselves, because it is
  95. kind of complicated.
  96. {{< code language="bash" id="1" expand="Show" collapse="Hide" isCollapsed="false" >}}
  97. job_pool_end_of_jobs="NO_JOB_LEFT"
  98. job_pool_job_queue=/tmp/job_pool_job_queue_$$
  99. job_pool_progress=/tmp/job_pool_progress_$$
  100. job_pool_pool_size=-1
  101. job_pool_nerrors=0
  102. function job_pool_cleanup()
  103. {
  104. rm -f ${job_pool_job_queue}
  105. rm -f ${job_pool_progress}
  106. }
  107. function job_pool_exit_handler()
  108. {
  109. job_pool_stop_workers
  110. job_pool_cleanup
  111. }
  112. function job_pool_worker()
  113. {
  114. local id=$1
  115. local job_queue=$2
  116. local cmd=
  117. local args=
  118. exec 7<> ${job_queue}
  119. while [[ "${cmd}" != "${job_pool_end_of_jobs}" && -e "${job_queue}" ]]; do
  120. flock --exclusive 7
  121. IFS=$'\v'
  122. read cmd args <${job_queue}
  123. set -- ${args}
  124. unset IFS
  125. flock --unlock 7
  126. if [[ "${cmd}" == "${job_pool_end_of_jobs}" ]]; then
  127. echo "${cmd}" >&7
  128. else
  129. { ${cmd} "$@" ; }
  130. fi
  131. done
  132. exec 7>&-
  133. }
  134. function job_pool_stop_workers()
  135. {
  136. echo ${job_pool_end_of_jobs} >> ${job_pool_job_queue}
  137. wait
  138. }
  139. function job_pool_start_workers()
  140. {
  141. local job_queue=$1
  142. for ((i=0; i<${job_pool_pool_size}; i++)); do
  143. job_pool_worker ${i} ${job_queue} &
  144. done
  145. }
  146. function job_pool_init()
  147. {
  148. local pool_size=$1
  149. job_pool_pool_size=${pool_size:=1}
  150. rm -rf ${job_pool_job_queue}
  151. rm -rf ${job_pool_progress}
  152. touch ${job_pool_progress}
  153. mkfifo ${job_pool_job_queue}
  154. echo 0 >${job_pool_progress} &
  155. job_pool_start_workers ${job_pool_job_queue}
  156. }
  157. function job_pool_shutdown()
  158. {
  159. job_pool_stop_workers
  160. job_pool_cleanup
  161. }
  162. function job_pool_run()
  163. {
  164. if [[ "${job_pool_pool_size}" == "-1" ]]; then
  165. job_pool_init
  166. fi
  167. printf "%s\v" "$@" >> ${job_pool_job_queue}
  168. echo >> ${job_pool_job_queue}
  169. }
  170. function job_pool_wait()
  171. {
  172. job_pool_stop_workers
  173. job_pool_start_workers ${job_pool_job_queue}
  174. }
  175. {{< /code >}}
  176. Ok... But that the actual fuck is going in here???
  177. ### fifo and flock
  178. In order to understand what this code is doing, you first need to understand two
  179. key commands that we are using, `fifo` and `flock`. Despite their complicated
  180. names, they are actually quite simple. Let's check their man pages to figure out
  181. their purposes, shall we?
  182. #### man fifo
  183. fifo's man page tells us that:
  184. ```
  185. NAME
  186. fifo - first-in first-out special file, named pipe
  187. DESCRIPTION
  188. A FIFO special file (a named pipe) is similar to a pipe, except that
  189. it is accessed as part of the filesystem. It can be opened by multiple
  190. processes for reading or writing. When processes are exchanging data
  191. via the FIFO, the kernel passes all data internally without writing it
  192. to the filesystem. Thus, the FIFO special file has no contents on the
  193. filesystem; the filesystem entry merely serves as a reference point so
  194. that processes can access the pipe using a name in the filesystem.
  195. ```
  196. So put in **very** simple terms, a fifo is a named pipe that allows
  197. communication between processes. Using a fifo allows us to loop through the jobs
  198. in the pool without having to delete them manually, because once we read them
  199. with `read cmd args < ${job_queue}`, the job is out of the pipe and the next
  200. read outputs the next job in the pool. However the fact that we have multiple
  201. processes introduces one caveat, what if two processes access the pipe at the
  202. same time? They would run the same command and we don't want that. So we resort
  203. to using `flock`.
  204. #### man flock
  205. flock's man page defines it as:
  206. ```
  207. SYNOPSIS
  208. flock [options] file|directory command [arguments]
  209. flock [options] file|directory -c command
  210. flock [options] number
  211. DESCRIPTION
  212. This utility manages flock(2) locks from within shell scripts or from
  213. the command line.
  214. The first and second of the above forms wrap the lock around the
  215. execution of a command, in a manner similar to su(1) or newgrp(1).
  216. They lock a specified file or directory, which is created (assuming
  217. appropriate permissions) if it does not already exist. By default, if
  218. the lock cannot be immediately acquired, flock waits until the lock is
  219. available.
  220. The third form uses an open file by its file descriptor number. See
  221. the examples below for how that can be used.
  222. ```
  223. Cool, translated to modern English that us regular folks use, `flock` is a thin
  224. wrapper around the C standard function `flock` (see `man 2 flock` if you are
  225. interested). It is used to manage locks and has several forms. The one we are
  226. interested in is the third one. According to the man page, it uses and open file
  227. by its **file descriptor number**. Aha! so that was the purpose of the `exec 7<>
  228. ${job_queue}` calls in the `job_pool_worker` function. It would essentially
  229. assign the file descriptor 7 to the fifo `job_queue` and afterwards lock it with
  230. `flock --exclusive 7`. Cool. This way only one process at a time can read from
  231. the fifo `job_queue`
  232. ## Great! But how do I use this?
  233. It depends on your preference, you can either save this in a file(e.g.
  234. job_pool.sh) and source it in your bash script. Or you can simply paste it
  235. inside an existing bash script. Whatever tickles your fancy. I have also
  236. provided an example that replicates our first implementation. Just paste the
  237. below code under our "chad" job pool script.
  238. {{< code language="bash" id="1" expand="Show" collapse="Hide" isCollapsed="false" >}}
  239. function tester(){
  240. # A function that takes an int as a parameter and sleeps
  241. echo "$1"
  242. sleep "$1"
  243. echo "ENDED $1"
  244. }
  245. num_workers=$1
  246. job_pool_init $num_workers
  247. pcount=0
  248. for i in {1..10}; do
  249. job_pool_run tester "$i"
  250. done
  251. job_pool_wait
  252. job_pool_shutdown
  253. {{< /code >}}
  254. Hopefully this article was(or will be) helpful to you. From now on, you don't
  255. ever have to write single threaded bash scripts like normies :)