├── .envrc
├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── NEWS.md
├── README.md
├── TODO.org
├── daemons.cabal
├── examples
├── AddOne.hs
├── Memo.hs
├── Memo.md
├── Name.hs
└── Queue.hs
├── flake.lock
├── flake.nix
├── src
├── Control
│ └── Pipe
│ │ ├── C3.hs
│ │ ├── Serialize.hs
│ │ └── Socket.hs
└── System
│ ├── Daemon.hs
│ └── Posix
│ └── Daemon.hs
├── stack.yaml
├── stack.yaml.lock
└── test
└── Daemon.hs
/.envrc:
--------------------------------------------------------------------------------
1 | use flake
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | dist/
2 | dist-newstyle/
3 | cabal-dev/
4 | .direnv/
5 | cabal.project.local
6 | cabal.project.local~
7 | .stack-work/
8 | Setup.hs
9 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: haskell
2 | ghc:
3 | - "8.4"
4 | - "8.6"
5 | - "8.8"
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | CABAL := $(shell cabal-dev --version > /dev/null && echo cabal-dev || echo cabal)
2 |
3 | all: build test
4 |
5 | .PHONY: all build dist install clean doc p test ghci
6 |
7 | build: dist/setup-config
8 | grep -E "$ " examples/Memo.md | sed 's/$ //' > examples/Memo.hs
9 | $(CABAL) build
10 |
11 | dist: build
12 | cabal sdist
13 |
14 | install: build
15 | cabal install
16 |
17 | test: build
18 | $(CABAL) test
19 |
20 | clean:
21 | $(CABAL) clean
22 | rm -rf cabal-dev/
23 |
24 | dist/setup-config: daemons.cabal
25 | # If you don't have all the necessary packages installed on the first
26 | # run, run `cabal-dev install`.
27 | $(CABAL) configure --enable-tests || $(CABAL) install --enable-tests
28 |
29 | doc: build
30 | $(CABAL) haddock
31 |
32 | p:
33 | permamake.sh $(shell find src/ -name '*.hs') \
34 | $(shell find test/ -name '*.hs') \
35 | *.cabal \
36 | Makefile
37 |
38 | ghci: build
39 | cabal-dev ghci
40 |
--------------------------------------------------------------------------------
/NEWS.md:
--------------------------------------------------------------------------------
1 | Changes
2 | =======
3 |
4 | 0.4.0 (29 Sep 2023)
5 | -------------------
6 |
7 | - update to work with ghc-9.6; thank you, @tfausak
8 | - bump min base version to 4.18
9 |
10 | 0.3.0 (03 Feb 2020)
11 | -------------------
12 |
13 | - update to work with the new network library; thank you, @guibou
14 |
15 | 0.2.1 (03 Oct 2013)
16 | -------------------
17 |
18 | - update to work with cereal-0.4.0; thank you, Henry Laxen
19 |
20 | 0.2.0 (15 Sep 2013)
21 | -------------------
22 |
23 | - update to work with pipes-4.0.0; thank you, @gabriel439
24 |
25 | 0.1.2 (05 Apr 2013)
26 | -------------------
27 |
28 | - add `System.Posix.Daemon.killAndWait`; thank you, @isturdy
29 |
30 | 0.1.1 (18 Aug 2012)
31 | -------------------
32 |
33 | - do *not* use the `-threaded` runtime;
34 |
35 | - use of IPv4 to workaround unpredictable behaviours in different
36 | distros.
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | daemons
2 | =======
3 |
4 | > Daemons in Haskell made fun and easy
5 |
6 | Example
7 | -------
8 |
9 | Here's
10 | [AddOne](https://github.com/scvalex/daemons/blob/master/AddOne.hs), a
11 | simple daemon that waits for a number and responds with the
12 | incremented number.
13 |
14 | import Data.Default ( def )
15 | import System.Environment ( getArgs )
16 | import System.Daemon
17 |
18 | addOne :: Int -> IO Int
19 | addOne n = return (n + 1)
20 |
21 | main :: IO ()
22 | main = do
23 | ensureDaemonRunning "addOne" def addOne
24 | [n] <- getArgs
25 | res <- runClient "localhost" 5000 ((read n) :: Int)
26 | print (res :: Maybe Int)
27 |
28 | Running it, we see:
29 |
30 | % addone 22
31 | Daemon started on port 5000
32 | Just 23
33 | % addone 41
34 | Just 42
35 |
36 | The two important functions above are `ensureDaemonRunning`, which
37 | checks if a daemon named `addOne` is already running, and starts it if
38 | not, and `runClient` which connects to the daemon running on
39 | `localhost:5000`, passes it a number, and waits for the response.
40 |
41 | What would I use this for?
42 | --------------------------
43 |
44 | - You can use the `runDetached` from `System.Posix.Daemon` to turn
45 | your program into a daemon for Unix-like systems. You'd want to do
46 | this for practically every program that's meant to run as a server.
47 |
48 | - You can use the functions from `Control.Pipe.C3`, `Socket`, and
49 | `Serialize` to communicate with running Haskell program. At the
50 | simplest, you could query the program for its status, or instruct
51 | it to shutdown cleanly. A more complex use would be adding a full
52 | REPL into a running Haskell process (think `erl -remsh`).
53 |
54 | - You can use the helpers from `System.Daemon` to trivially do the
55 | above. Check out the following tutorials and examples for details.
56 |
57 | Tutorials and examples
58 | ----------------------
59 |
60 | - [Memo](https://github.com/scvalex/daemons/blob/master/examples/Memo.md) -
61 | in which we write an in-memory key-value store,
62 |
63 | - [Queue](https://github.com/scvalex/daemons/blob/master/examples/Queue.hs)
64 | - a task queue using the streaming interface of `daemons`.
65 |
66 | Installation
67 | ------------
68 |
69 | This package is on
70 | [Hackage](http://hackage.haskell.org/package/daemons). To install
71 | it, run:
72 |
73 | cabal update
74 | cabal install daemons
75 |
76 | Modules
77 | -------
78 |
79 | - `Control.Pipe.C3` provides simple RPC-like wrappers for pipes.
80 |
81 | - `Control.Pipe.Serialize` provides pipes to serialize and
82 | deserialize streams of strict `ByteString`s using
83 | [cereal](http://hackage.haskell.org/package/cereal).
84 |
85 | - `Control.Pipe.Socket` provides functions to setup strict
86 | `ByteString` pipes around sockets.
87 |
88 | - `System.Daemon` provides a high-level interface to starting
89 | daemonized programs that are controlled through sockets.
90 |
91 | - `System.Posix.Daemon` provides a low-level interface to starting,
92 | and controlling detached jobs.
93 |
94 | See also
95 | --------
96 |
97 | - `pipes` [The Pipes Tutorial](http://hackage.haskell.org/packages/archive/pipes/3.2.0/doc/html/Control-Proxy-Tutorial.html)
98 |
99 | - `C3` [Wikipedia](https://en.wikipedia.org/wiki/Command,_control,_and_communications#Command.2C_control_and_communications)
100 |
--------------------------------------------------------------------------------
/TODO.org:
--------------------------------------------------------------------------------
1 | * TODO Update code to use new `Control.Proxy` namespace
2 | * TODO Get rid of IPv4-only hack when creating sockets
3 |
--------------------------------------------------------------------------------
/daemons.cabal:
--------------------------------------------------------------------------------
1 | Name: daemons
2 | Version: 0.4.0
3 | Cabal-Version: 1.24
4 | License: GPL-3
5 | License-File: LICENSE
6 | Stability: experimental
7 | Author: Alexandru Scvortov
8 | Maintainer: scvalex@gmail.com
9 | Homepage: https://github.com/scvalex/daemons
10 | Category: System, Control, Network
11 | Synopsis: Daemons in Haskell made fun and easy
12 | Build-Type: Simple
13 | Description:
14 | "Control.Pipe.C3" provides simple RPC-like wrappers for pipes.
15 | .
16 | "Control.Pipe.Serialize" provides serialization and
17 | incremental deserialization pipes.
18 | .
19 | "Control.Pipe.Socket" provides functions to setup pipes around
20 | sockets.
21 | .
22 | "System.Daemon" provides a high-level interface to starting
23 | daemonized programs that are controlled through sockets.
24 | .
25 | "System.Posix.Daemon" provides a low-level interface to
26 | starting, and controlling detached jobs.
27 | .
28 | See the @README.md@ file and the homepage for details.
29 |
30 | Extra-Source-Files: Makefile
31 |
32 | Data-Files: README.md, NEWS.md, LICENSE, examples/Memo.md
33 |
34 | Source-repository head
35 | Type: git
36 | Location: git://github.com/scvalex/daemons.git
37 |
38 | Library
39 | Hs-Source-Dirs: src
40 | Build-depends: base >= 4.18 && < 5,
41 | bytestring >= 0.11 && < 0.12,
42 | cereal >= 0.4 && < 0.6,
43 | data-default >= 0.7 && < 0.8,
44 | directory >= 1.3 && < 1.4,
45 | filepath >= 1.4 && < 1.5,
46 | ghc-prim >= 0.10 && < 0.11,
47 | network >= 3.1 && < 3.2,
48 | pipes >= 4.0 && < 4.4,
49 | transformers >= 0.6 && < 0.7,
50 | unix >= 2.8 && < 2.9
51 | Ghc-options: -Wall
52 | Exposed-modules: Control.Pipe.C3,
53 | Control.Pipe.Serialize,
54 | Control.Pipe.Socket,
55 | System.Daemon,
56 | System.Posix.Daemon
57 | Other-modules:
58 | Default-language: Haskell2010
59 |
60 | Executable memo
61 | Build-depends: base >= 4.18 && < 5,
62 | bytestring >= 0.11 && < 0.12,
63 | cereal >= 0.4 && < 0.6,
64 | containers >= 0.6 && < 0.7,
65 | daemons,
66 | data-default >= 0.7 && < 0.8,
67 | ghc-prim >= 0.10.0 && < 0.11
68 | Main-Is: examples/Memo.hs
69 | Ghc-options: -Wall
70 | Default-language: Haskell2010
71 |
72 | Executable addone
73 | Build-depends: base >= 4.18 && < 5, daemons,
74 | data-default >= 0.7 && < 0.8,
75 | ghc-prim >= 0.10 && < 0.11
76 | Main-Is: examples/AddOne.hs
77 | Ghc-options: -Wall
78 | Default-language: Haskell2010
79 |
80 | Executable queue
81 | Build-depends: base >= 4.18 && < 5,
82 | bytestring >= 0.11 && < 0.12,
83 | cereal >= 0.4 && < 0.6,
84 | containers >= 0.6 && < 0.7,
85 | daemons,
86 | data-default >= 0.7 && < 0.8,
87 | ghc-prim >= 0.10 && < 0.11,
88 | network >= 3.1 && < 3.2,
89 | pipes >= 4.0 && < 4.4,
90 | transformers >= 0.6 && < 0.7
91 | Main-Is: examples/Queue.hs
92 | Ghc-options: -Wall
93 | Default-language: Haskell2010
94 |
95 | Executable name
96 | Build-depends: base >= 4.18 && < 5,
97 | bytestring >= 0.11 && < 0.12,
98 | cereal >= 0.4 && < 0.6,
99 | containers >= 0.6 && < 0.7,
100 | daemons,
101 | data-default >= 0.7 && < 0.8,
102 | ghc-prim >= 0.10.0 && < 0.11
103 | Main-Is: examples/Name.hs
104 | Ghc-options: -Wall
105 | Default-language: Haskell2010
106 |
107 | Test-suite daemon
108 | Hs-Source-Dirs: test
109 | Main-Is: Daemon.hs
110 | Type: exitcode-stdio-1.0
111 | Build-Depends: base >= 4.18 && < 5, daemons,
112 | data-default >= 0.7 && < 0.8,
113 | directory >= 1.3 && < 1.4,
114 | ghc-prim >= 0.10 && < 0.11,
115 | HUnit, test-framework, test-framework-hunit,
116 | unix >= 2.8 && < 2.9
117 | Ghc-Options: -Wall
118 | Default-language: Haskell2010
119 |
--------------------------------------------------------------------------------
/examples/AddOne.hs:
--------------------------------------------------------------------------------
1 | module Main where
2 |
3 | import Data.Default ( def )
4 | import System.Environment ( getArgs )
5 | import System.Daemon
6 |
7 | addOne :: Int -> IO Int
8 | addOne n = return (n + 1)
9 |
10 | main :: IO ()
11 | main = do
12 | ensureDaemonRunning "addOne" def addOne
13 | [n] <- getArgs
14 | res <- runClient "localhost" 5000 ((read n) :: Int)
15 | print (res :: Maybe Int)
16 |
--------------------------------------------------------------------------------
/examples/Memo.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
2 |
3 | module Main where
4 |
5 | import Control.Concurrent.MVar ( MVar, newMVar, modifyMVar )
6 | import Data.ByteString.Char8 ( ByteString )
7 | import Data.Default ( def )
8 | import Data.Serialize ( Serialize )
9 | import Data.String ( fromString )
10 | import qualified Data.Map as M
11 | import GHC.Generics
12 | import System.Environment ( getArgs )
13 | import System.Daemon
14 |
15 | data Command = Put ByteString ByteString
16 | | Get ByteString
17 | deriving ( Generic, Show )
18 |
19 | instance Serialize Command
20 |
21 | data Response = Failed String
22 | | Value ByteString
23 | deriving ( Generic, Show )
24 |
25 | instance Serialize Response
26 |
27 | type Book = M.Map ByteString ByteString
28 |
29 | handleCommand :: MVar Book -> Command -> IO Response
30 | handleCommand bookVar comm = modifyMVar bookVar $ \book -> return $
31 | case comm of
32 | Get key -> ( book
33 | , maybe (Failed "not found") Value (M.lookup key book) )
34 | Put key value -> ( M.insert key value book
35 | , Value "ok" )
36 |
37 | main :: IO ()
38 | main = do
39 | bookVar <- newMVar M.empty
40 | let options = def { daemonPort = 7856 }
41 | ensureDaemonRunning "memo" options (handleCommand bookVar)
42 | args <- getArgs
43 | let args' = map fromString args
44 | res <- case args' of
45 | ["get", key] -> runClient "localhost" 7856 (Get key)
46 | ["put", key, value] -> runClient "localhost" 7856 (Put key value)
47 | _ -> error "invalid command"
48 | print (res :: Maybe Response)
49 |
50 | {-
51 | % dist/build/memo/memo get apples
52 | Daemon started on port 7856
53 | Just (Failed "not found")
54 |
55 | % dist/build/memo/memo put apples 23
56 | Just (Value "ok")
57 |
58 | % dist/build/memo/memo get apples
59 | Just (Value "23")
60 | -}
61 |
--------------------------------------------------------------------------------
/examples/Memo.md:
--------------------------------------------------------------------------------
1 | Memo
2 | ====
3 |
4 | > A simple in-memory key-value store
5 |
6 | Welcome to the first `daemons` tutorial, in which we walk through
7 | writing an in-memory key-value store with an RPC-like interface. The
8 | code for this tutorial is
9 | [Memo.hs](https://github.com/scvalex/daemons/blob/master/examples/Memo.hs).
10 |
11 | Concretely, we want a program such that:
12 |
13 | - `memo put x 42` associates the value `42` with the key `x`, and
14 |
15 | - `memo get x` returns the value `42`.
16 |
17 | First of all, the extensions and imports:
18 |
19 | {-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
20 |
21 |
22 | We need `DeriveGenerics` for
23 | [cereal](http://hackage.haskell.org/package/cereal) to generate
24 | serializers and deserializers automatically, and we enable
25 | `OverloadedStrings` because it makes working with `ByteString`s much
26 | nicer.
27 |
28 | module Main where
29 |
30 | import Control.Concurrent.MVar ( MVar, newMVar, modifyMVar )
31 | import Data.ByteString.Char8 ( ByteString )
32 | import Data.Default ( def )
33 | import Data.Serialize ( Serialize )
34 | import Data.String ( fromString )
35 | import qualified Data.Map as M
36 | import GHC.Generics
37 | import System.Environment ( getArgs )
38 | import System.Daemon
39 |
40 |
41 | Our key-value store will be a `Map ByteString ByteString` and we'll
42 | store it in an `MVar` to synchronize concurrent accesses. Instead of
43 | handcrafting a binary protocol for our daemon, we take the easy road
44 | and generate it automatically with `Data.Serialize` and
45 | [GHC.Generics](http://www.haskell.org/ghc/docs/7.4.2/html/users_guide/generic-programming.html).
46 |
47 | We import `System.Daemon` which is the high-level interface to the
48 | `daemons` library. The daemons' configuration is an instance of
49 | [Data.Default](http://hackage.haskell.org/package/data-default), so
50 | we'll be able to use the defaults.
51 |
52 | data Command = Put ByteString ByteString
53 | | Get ByteString
54 | deriving ( Generic, Show )
55 |
56 | instance Serialize Command
57 |
58 |
59 | We define a datatype for the `put ` and `get `
60 | commands. We let GHC derive the `Generics` instance, which gives us a
61 | pure Haskell representation of the type; this is used by the
62 | `Serialize` instance to generate all the necessary binary
63 | serialization and deserialization code.
64 |
65 | data Response = Failed String
66 | | Value ByteString
67 | deriving ( Generic, Show )
68 |
69 | instance Serialize Response
70 |
71 |
72 | Similarly, we define a datatype for the possible responses. These can
73 | either be values requested by `get `, or failure messages.
74 |
75 | type Book = M.Map ByteString ByteString
76 |
77 | handleCommand :: MVar Book -> Command -> IO Response
78 | handleCommand bookVar comm = modifyMVar bookVar $ \book -> return $
79 |
80 | Our "book" is just a map of `ByteString`s; our command handler takes
81 | this map and a command, and returns a response.
82 |
83 | Whenever the daemon receives a command, it spawns a new thread and
84 | runs the command handler. We want to share the book between these
85 | concurrent calls to the handler, so we stick it in an
86 | [MVar](http://www.haskell.org/ghc/docs/7.4.2/html/libraries/base/Control-Concurrent-MVar.html).
87 |
88 | An `MVar` is basically a thread-safe box which holds at most *one*
89 | item. We use `modifyMVar` which takes the book out of the `MVar`,
90 | runs our function with it, and puts the returned book back in the
91 | `MVar`.
92 |
93 | case comm of
94 | Get key -> ( book
95 | , maybe (Failed "not found") Value (M.lookup key book) )
96 |
97 | A `get ` command does not change the book, so we just return it.
98 | We look up the key and return its value or a failure message.
99 |
100 | Put key value -> ( M.insert key value book
101 | , Value "ok" )
102 |
103 |
104 | A `put ` command inserts the key-value pair into the
105 | book, and returns a confirmation message.
106 |
107 | main :: IO ()
108 | main = do
109 | bookVar <- newMVar M.empty
110 | let options = def { daemonPort = 7856 }
111 | ensureDaemonRunning "memo" options (handleCommand bookVar)
112 |
113 | Before doing anything else, we need to ensure that the daemon is
114 | running: we create an empty book, customize the daemon's default
115 | options, and finally start it. Note that `ensureDaemonRunning` checks
116 | if the daemon is running and starts it otherwise; so, the daemon will
117 | be started the first time the program is run, and all later runs will
118 | use the initial daemon.
119 |
120 | args <- getArgs
121 | let args' = map fromString args
122 |
123 | Now it's time to handle the user input. First, we convert all the
124 | arguments to `ByteString`s for ease of use.
125 |
126 | res <- case args' of
127 | ["get", key] -> runClient "localhost" 7856 (Get key)
128 | ["put", key, value] -> runClient "localhost" 7856 (Put key value)
129 | _ -> error "invalid command"
130 |
131 | Next, we parse the arguments into a command and send it to the daemon.
132 | We call `runClient` with the port we gave earlier to
133 | `ensureDaemonRunning` and with the parsed command.
134 |
135 | print (res :: Maybe Response)
136 |
137 |
138 | Finally, we print the returned response. Note that `runClient` is
139 | polymorphic in its return so we *need* to specify the type of the
140 | response.
141 |
142 | Now let's see it in action:
143 |
144 | {-
145 | % dist/build/memo/memo get apples
146 | Daemon started on port 7856
147 | Just (Failed "not found")
148 |
149 | % dist/build/memo/memo put apples 23
150 | Just (Value "ok")
151 |
152 | % dist/build/memo/memo get apples
153 | Just (Value "23")
154 | -}
155 |
156 | To recap, we:
157 |
158 | - wrote data-types for commands and responses and gave them
159 | `Serialize` instances,
160 |
161 | - wrote a handler that takes a command and returns a response,
162 |
163 | - ensured that our daemon is running with `ensureDaemonRunning`, and
164 |
165 | - sent commands and received responses with `runClient`.
166 |
167 | This tutorial illustrates the basic concepts behind `daemons`, but
168 | hides a powerful feature: the interface is *streaming*. See the
169 | [Queue](https://github.com/scvalex/daemons/blob/master/examples/Queue.hs)
170 | (Poor Man's Task Queue) tutorial for an example use of the streaming
171 | interface.
172 |
--------------------------------------------------------------------------------
/examples/Name.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE DeriveGeneric, OverloadedStrings, MultiParamTypeClasses, FunctionalDependencies #-}
2 |
3 | module Main where
4 |
5 | import Control.Concurrent.MVar ( MVar, newMVar, modifyMVar )
6 | import Data.ByteString.Char8 ( ByteString, unpack )
7 | import Data.Default ( def )
8 | import Data.Serialize ( Serialize )
9 | import Data.String ( fromString )
10 | import qualified Data.Map as M
11 | import GHC.Generics
12 | import System.Environment ( getArgs )
13 | import System.Daemon
14 |
15 | data CommandV0 = Register ByteString Port
16 | | WhereIs ByteString
17 | deriving ( Generic, Show )
18 |
19 | instance Serialize CommandV0
20 |
21 | data Command = CommandV0 CommandV0
22 | deriving ( Generic, Show )
23 |
24 | instance Serialize Command
25 |
26 | data ResponseV0 = Ok
27 | | NotFound ByteString
28 | | AtPort ByteString Port
29 | deriving ( Generic, Show )
30 |
31 | instance Serialize ResponseV0
32 |
33 | data Response = ResponseV0 ResponseV0
34 | deriving ( Generic, Show )
35 |
36 | instance Serialize Response
37 |
38 | type Registry = M.Map ByteString Port
39 |
40 | class VersionOf a b | a -> b where
41 | toLatest :: a -> b
42 | fromLatest :: b -> a
43 |
44 | instance VersionOf Command CommandV0 where
45 | toLatest (CommandV0 v0) = v0
46 | fromLatest v0 = CommandV0 v0
47 |
48 | instance VersionOf Response ResponseV0 where
49 | toLatest (ResponseV0 v0) = v0
50 | fromLatest v0 = ResponseV0 v0
51 |
52 | namePort :: Port
53 | namePort = 4370
54 |
55 | handleCommand :: MVar Registry -> CommandV0 -> IO ResponseV0
56 | handleCommand registryVar cmd = modifyMVar registryVar $ \registry -> return $
57 | case cmd of
58 | WhereIs name -> ( registry
59 | , maybe (NotFound name) (AtPort name) (M.lookup name registry) )
60 | Register name port -> ( M.insert name port registry
61 | , Ok )
62 |
63 | wrapVersion :: (CommandV0 -> IO ResponseV0) -> Command -> IO Response
64 | wrapVersion f cmd = do
65 | rsp <- f (toLatest cmd)
66 | return (fromLatest rsp)
67 |
68 | main :: IO ()
69 | main = do
70 | registryVar <- newMVar M.empty
71 | let options = def { daemonPort = namePort }
72 | ensureDaemonRunning "name" options (wrapVersion (handleCommand registryVar))
73 | args <- getArgs
74 | let args' = map fromString args
75 | res <- case args' of
76 | ["where-is", key] ->
77 | runClient "localhost" namePort (CommandV0 (WhereIs key))
78 | ["register", name, port] ->
79 | let portNum = read (unpack port) in
80 | runClient "localhost" namePort (CommandV0 (Register name portNum))
81 | _ ->
82 | error "invalid command"
83 | print (fmap toLatest (res :: Maybe Response))
84 |
--------------------------------------------------------------------------------
/examples/Queue.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
2 |
3 | module Main where
4 |
5 | import Control.Concurrent.Chan ( Chan, newChan, readChan, writeChan )
6 | import Control.Concurrent.MVar ( MVar, newMVar, modifyMVar )
7 | import Control.Monad ( forever )
8 | import Control.Monad.Trans.Class ( lift )
9 | import Control.Pipe.Serialize ( serializer, deserializer )
10 | import Control.Pipe.Socket ( Handler )
11 | import Data.ByteString.Char8 ( ByteString )
12 | import qualified Data.ByteString.Char8 as B
13 | import Data.Char ( toLower )
14 | import Data.Default ( def )
15 | import Data.Serialize ( Serialize )
16 | import Data.String ( fromString )
17 | import qualified Data.Map as M
18 | import GHC.Generics
19 | import Network.Socket ( withSocketsDo )
20 | import Pipes ( runEffect, (<-<), await, yield )
21 | import System.Environment ( getArgs )
22 | import System.Daemon
23 | import System.IO ( hPutStrLn, stderr )
24 |
25 | data Command = Push ByteString ByteString
26 | | Pop ByteString
27 | | Consume ByteString
28 | deriving ( Generic, Show )
29 |
30 | instance Serialize Command
31 |
32 | data Response = Value ByteString
33 | deriving ( Generic, Show )
34 |
35 | instance Serialize Response
36 |
37 | type Registry = M.Map ByteString (Chan ByteString)
38 |
39 | handleCommands :: MVar Registry -> Handler ()
40 | handleCommands registryVar reader writer = runEffect $
41 | writer <-< serializer <-< commandExecuter <-< deserializer <-< reader
42 | where
43 | commandExecuter = forever $ do
44 | comm <- await
45 | case comm of
46 | Pop topic -> do
47 | ch <- lift $ getCreateChan topic
48 | transferToPipeFromChan ch
49 | Consume topic -> do
50 | ch <- lift $ getCreateChan topic
51 | forever $ transferToPipeFromChan ch
52 | Push topic val -> do
53 | ch <- lift $ getCreateChan topic
54 | lift $ writeChan ch val
55 | yield (Value "ok")
56 |
57 | -- Transfer a value from the given channel to the pipe.
58 | transferToPipeFromChan ch = do
59 | val <- lift $ readChan ch
60 | yield (Value val)
61 |
62 | -- Get the channel for the given topic, and create it if it does
63 | -- not already exist.
64 | getCreateChan topic = modifyMVar registryVar $ \registry -> do
65 | case M.lookup topic registry of
66 | Nothing -> do
67 | ch <- newChan
68 | return (M.insert topic ch registry, ch)
69 | Just ch -> do
70 | return (registry, ch)
71 |
72 | main :: IO ()
73 | main = withSocketsDo $ do
74 | registryVar <- newMVar M.empty
75 | let options = def { daemonPort = 7857 }
76 | ensureDaemonWithHandlerRunning "queue" options (handleCommands registryVar)
77 | args <- getArgs
78 | let args' = map (fromString . map toLower) args
79 | case args' of
80 | ["pop", key] -> do
81 | res <- runClient "localhost" 7857 (Pop key)
82 | printResult res
83 | ["push", key, value] -> do
84 | res <- runClient "localhost" 7857 (Push key value)
85 | printResult res
86 | ["consume", key] -> do
87 | runClientWithHandler "localhost" 7857 $ \reader writer ->
88 | runEffect $ do
89 | writer <-< serializer <-< yield (Consume key)
90 | (forever $ await >>= \res -> lift (printResult (Just res)))
91 | <-< deserializer <-< reader
92 | _ -> do
93 | error "invalid command"
94 | where
95 | printResult :: Maybe Response -> IO ()
96 | printResult Nothing = hPutStrLn stderr "no response"
97 | printResult (Just (Value val)) = B.putStrLn val
98 |
--------------------------------------------------------------------------------
/flake.lock:
--------------------------------------------------------------------------------
1 | {
2 | "nodes": {
3 | "flake-compat": {
4 | "flake": false,
5 | "locked": {
6 | "lastModified": 1673956053,
7 | "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=",
8 | "owner": "edolstra",
9 | "repo": "flake-compat",
10 | "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9",
11 | "type": "github"
12 | },
13 | "original": {
14 | "owner": "edolstra",
15 | "repo": "flake-compat",
16 | "type": "github"
17 | }
18 | },
19 | "nixpkgs": {
20 | "locked": {
21 | "lastModified": 1695825837,
22 | "narHash": "sha256-4Ne11kNRnQsmSJCRSSNkFRSnHC4Y5gPDBIQGjjPfJiU=",
23 | "owner": "NixOS",
24 | "repo": "nixpkgs",
25 | "rev": "5cfafa12d57374f48bcc36fda3274ada276cf69e",
26 | "type": "github"
27 | },
28 | "original": {
29 | "owner": "NixOS",
30 | "ref": "nixos-23.05",
31 | "repo": "nixpkgs",
32 | "type": "github"
33 | }
34 | },
35 | "root": {
36 | "inputs": {
37 | "flake-compat": "flake-compat",
38 | "nixpkgs": "nixpkgs",
39 | "utils": "utils"
40 | }
41 | },
42 | "systems": {
43 | "locked": {
44 | "lastModified": 1681028828,
45 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
46 | "owner": "nix-systems",
47 | "repo": "default",
48 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
49 | "type": "github"
50 | },
51 | "original": {
52 | "owner": "nix-systems",
53 | "repo": "default",
54 | "type": "github"
55 | }
56 | },
57 | "utils": {
58 | "inputs": {
59 | "systems": "systems"
60 | },
61 | "locked": {
62 | "lastModified": 1694529238,
63 | "narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
64 | "owner": "numtide",
65 | "repo": "flake-utils",
66 | "rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
67 | "type": "github"
68 | },
69 | "original": {
70 | "owner": "numtide",
71 | "repo": "flake-utils",
72 | "type": "github"
73 | }
74 | }
75 | },
76 | "root": "root",
77 | "version": 7
78 | }
79 |
--------------------------------------------------------------------------------
/flake.nix:
--------------------------------------------------------------------------------
1 | {
2 | inputs = {
3 | nixpkgs.url = "github:NixOS/nixpkgs/nixos-23.05";
4 | utils.url = "github:numtide/flake-utils";
5 | flake-compat = {
6 | url = github:edolstra/flake-compat;
7 | flake = false;
8 | };
9 | };
10 |
11 | outputs = { self, nixpkgs, utils, ... }:
12 | utils.lib.eachDefaultSystem (system:
13 | let
14 | pkgs = import nixpkgs { inherit system; };
15 | in
16 | {
17 | devShell = with pkgs; mkShell {
18 | buildInputs = [
19 | cabal-install
20 | tokei
21 |
22 | haskell.compiler.ghc96
23 | haskellPackages.pipes
24 | ];
25 | GIT_EXTERNAL_DIFF = "${difftastic}/bin/difft";
26 | };
27 | });
28 | }
29 |
--------------------------------------------------------------------------------
/src/Control/Pipe/C3.hs:
--------------------------------------------------------------------------------
1 | module Control.Pipe.C3 (
2 | -- * Pipes
3 | commandSender, commandReceiver
4 | ) where
5 |
6 | import Control.Monad ( forever )
7 | import Control.Monad.Trans.Class ( lift )
8 | import Control.Pipe.Serialize ( serializer, deserializer )
9 | import Control.Pipe.Socket ( Handler )
10 | import Data.Serialize ( Serialize )
11 | import Pipes ( runEffect, await, yield, (<-<) )
12 |
13 | -- | Send a single command over the outgoing pipe and wait for a
14 | -- response. If the incoming pipe is closed before a response
15 | -- arrives, returns @Nothing@.
16 | commandSender :: (Serialize a, Serialize b) => a -> Handler (Maybe b)
17 | commandSender command reader writer = runEffect $ do
18 | writer <-< serializer <-< sendCommand
19 | receiveResponse
20 | <-< (deserializer >> return Nothing)
21 | <-< (reader >> return Nothing)
22 | where
23 | sendCommand = do
24 | yield command
25 |
26 | receiveResponse = do
27 | res <- await
28 | return (Just res)
29 |
30 | -- | Wait for commands on the incoming pipe, handle them, and send the
31 | -- reponses over the outgoing pipe.
32 | commandReceiver :: (Serialize a, Serialize b) => (a -> IO b) -> Handler ()
33 | commandReceiver executeCommand reader writer = runEffect $
34 | writer <-< serializer <-< commandExecuter <-< deserializer <-< reader
35 | where
36 | commandExecuter = forever $ do
37 | comm <- await
38 | yield =<< lift (executeCommand comm)
39 |
--------------------------------------------------------------------------------
/src/Control/Pipe/Serialize.hs:
--------------------------------------------------------------------------------
1 | -- | This module provides the 'deserializer' and 'serializer' pipes to
2 | -- convert 'B.ByteString's off of pipes into typed values.
3 | --
4 | -- In order to use it, the types of the values need to have
5 | -- 'Serialize' instances. These can be derived automatically using
6 | -- "Ghc.Generics":
7 | --
8 | -- > {-# LANGUAGE DeriveGeneric #-}
9 | -- >
10 | -- > data Foo = Bar String | Baz Int
11 | -- > deriving ( Generic )
12 | -- >
13 | -- > instance Serialize Foo
14 | --
15 | -- Note that in the above example: we use the @DeriveGeneric@
16 | -- extension, derive a @Generic@ instance for our data-type, and write
17 | -- an /empty/ @Serialize@ instance.
18 | --
19 | module Control.Pipe.Serialize (
20 | -- * Pipes
21 | serializer, deserializer
22 | ) where
23 |
24 | import Data.ByteString.Char8 ( ByteString )
25 | import Data.Serialize ( Serialize, get, encode
26 | , Result(..), runGetPartial )
27 | import Pipes ( Pipe, await, yield )
28 | import Control.Monad ( forever )
29 |
30 | -- | De-serialize data from strict 'ByteString's. Uses @cereal@'s
31 | -- incremental 'Data.Serialize.Get' parser.
32 | deserializer :: (Serialize a, Monad m, MonadFail m) => Pipe ByteString a m ()
33 | deserializer = loop Nothing Nothing
34 | where
35 | loop mk mbin = do
36 | bin <- maybe await return mbin
37 | case (maybe (runGetPartial get) id mk) bin of
38 | Fail reason _leftover ->
39 | fail reason
40 | Partial k ->
41 | loop (Just k) Nothing
42 | Done c bin' -> do
43 | yield c
44 | loop Nothing (Just bin')
45 |
46 | -- | Serialize data into strict 'ByteString's.
47 | serializer :: (Serialize a, Monad m) => Pipe a ByteString m ()
48 | serializer = forever $ do
49 | x <- await
50 | yield (encode x)
51 |
--------------------------------------------------------------------------------
/src/Control/Pipe/Socket.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE ScopedTypeVariables #-}
2 |
3 | -- Thank you:
4 | -- pipes-network
5 |
6 | module Control.Pipe.Socket (
7 | -- * Socket pipes
8 | socketReader, socketWriter,
9 |
10 | -- * Socket server/client
11 | Handler, runSocketServer, runSocketClient
12 | ) where
13 |
14 | import Control.Concurrent ( forkIO )
15 | import qualified Control.Exception as CE
16 | import Control.Monad ( forever, unless )
17 | import Control.Monad.IO.Class ( MonadIO(..) )
18 | import Control.Monad.Trans.Class ( lift )
19 | import Data.ByteString.Char8 ( ByteString )
20 | import qualified Data.ByteString.Char8 as B
21 | import Network.Socket ( Socket )
22 | import qualified Network.Socket as NS
23 | import Network.Socket.ByteString ( sendAll, recv )
24 | import Pipes ( Consumer, Producer, await, yield )
25 |
26 | -- | Stream data from the socket.
27 | socketReader :: (MonadIO m) => Socket -> Producer ByteString m ()
28 | socketReader socket = do
29 | bin <- lift . liftIO $ recv socket 4096
30 | unless (B.null bin) $ do
31 | yield bin
32 | socketReader socket
33 |
34 | -- | Stream data to the socket.
35 | socketWriter :: (MonadIO m) => Socket -> Consumer ByteString m ()
36 | socketWriter socket = forever $ do
37 | bin <- await
38 | lift . liftIO $ sendAll socket bin
39 |
40 | -- | A simple handler: takes an incoming stream of 'ByteString's, an
41 | -- stream of 'ByteString's, and ties them together somehow.
42 | -- Conceptually, the simplest handler would be @identity@:
43 | --
44 | -- > import Control.Monad
45 | -- > import Control.Pipe
46 | -- > import Data.ByteString.Char8
47 | -- >
48 | -- > handler reader writer = do
49 | -- > let identity = forever $ do
50 | -- > x <- await
51 | -- > yield x
52 | -- > runPipe (writer <+< identity <+< reader)
53 | --
54 | -- See the @pipes@ tutorial for more examples of writing pipes.
55 | --
56 | -- Since 'ByteString's are fairly boring by themseleves, have a look
57 | -- at "Control.Pipe.Serialize" which lets you deserialize/serialize
58 | -- pipes of 'ByteString's easily.
59 | type Handler r = Producer ByteString IO ()
60 | -> Consumer ByteString IO ()
61 | -> IO r
62 |
63 | -- | Listen for connections on the given socket, and run 'Handler' on
64 | -- each received connection. The socket should previously have been
65 | -- bound to a port or to a file. Each handler is run in its own
66 | -- thread. Even in case of an error, the handlers' sockets are
67 | -- closed.
68 | runSocketServer :: (MonadIO m) => Socket -> Handler () -> m ()
69 | runSocketServer lsocket handler = liftIO $ forever $ do
70 | (socket, _addr) <- NS.accept lsocket
71 | _ <- forkIO $ CE.finally
72 | (handler (socketReader socket) (socketWriter socket))
73 | (NS.close socket)
74 | return ()
75 |
76 | -- | Run 'Handler' on the given socket.
77 | runSocketClient :: (MonadIO m) => Socket -> Handler r -> m r
78 | runSocketClient socket handler = liftIO $ do
79 | handler (socketReader socket) (socketWriter socket)
80 |
--------------------------------------------------------------------------------
/src/System/Daemon.hs:
--------------------------------------------------------------------------------
1 | -- | An RPC-like interface for daemons is provided by
2 | -- 'ensureDaemonRunning' and 'runClient'.
3 | --
4 | -- A more versatile interface that lets you supply your own `Handler`
5 | -- is provided by `ensureDaemonWithHandlerRunning` and
6 | -- `runClientWithHandler`. These are useful if, for instance, you
7 | -- need streaming requests or replies, or if you need to change your
8 | -- event handler at runtime.
9 | --
10 | -- The event handling loop is provided by `runInForeground`. You may
11 | -- want to use this for debugging purposes or if you want to handle
12 | -- daemonization manually.
13 | module System.Daemon (
14 | -- * Daemons
15 | ensureDaemonRunning, ensureDaemonWithHandlerRunning,
16 |
17 | -- * Clients,
18 | runClient, runClientWithHandler,
19 |
20 | -- * Types
21 | DaemonOptions(..), PidFile(..), HostName, Port,
22 |
23 | -- * Helpers
24 | runInForeground, bindPort, getSocket
25 | ) where
26 |
27 | import Control.Concurrent ( threadDelay )
28 | import qualified Control.Exception as CE
29 | import Control.Monad ( when )
30 | import Control.Pipe.C3 ( commandSender, commandReceiver )
31 | import Control.Pipe.Socket ( Handler, runSocketServer, runSocketClient )
32 | import Data.Default ( Default(..) )
33 | import Data.Serialize ( Serialize )
34 | import Data.String ( IsString(..) )
35 | import Network.Socket ( Socket, SockAddr(..), Family(..), SocketType(..)
36 | , SocketOption(..), setSocketOption
37 | , socket, close, connect, bind, listen
38 | , AddrInfo(..), getAddrInfo, addrAddress, defaultHints
39 | , defaultProtocol, tupleToHostAddress, maxListenQueue )
40 | import System.Directory ( getHomeDirectory )
41 | import System.FilePath ( (>), (<.>) )
42 | import System.Posix.Daemon ( runDetached, isRunning )
43 | import Text.Printf ( printf )
44 |
45 | type Port = Int
46 | type HostName = String
47 |
48 | -- | The configuration options of a daemon. See 'ensureDaemonRunning'
49 | -- for a description of each.
50 | data DaemonOptions = DaemonOptions
51 | { daemonPort :: Port
52 | , daemonPidFile :: PidFile
53 | , printOnDaemonStarted :: Bool
54 | } deriving ( Show )
55 |
56 | instance Default DaemonOptions where
57 | def = DaemonOptions { daemonPort = 5000
58 | , daemonPidFile = InHome
59 | , printOnDaemonStarted = True
60 | }
61 |
62 | -- | The location of the daemon's pidfile.
63 | data PidFile = InHome
64 | | PidFile FilePath
65 | deriving ( Show )
66 |
67 | instance IsString PidFile where
68 | fromString = PidFile
69 |
70 | -- | Simple wrapper around 'ensureDaemonWithHandlerRunning' which uses
71 | -- a simple function to respond to commands and doesn't deal with
72 | -- pipes.
73 | --
74 | -- The @handler@ is just a function that takes a command and returns a
75 | -- response.
76 | ensureDaemonRunning :: (Serialize a, Serialize b)
77 | => String -- ^ name
78 | -> DaemonOptions -- ^ options
79 | -> (a -> IO b) -- ^ handler
80 | -> IO ()
81 | ensureDaemonRunning name options executeCommand = do
82 | ensureDaemonWithHandlerRunning name options (commandReceiver executeCommand)
83 |
84 | -- FIXME Add set-up and tear-down action. The reason the threaded
85 | -- runtime wouldn't work was because we were creating the mvar in a
86 | -- different thread!
87 |
88 | -- | Start a daemon running on the given port, using the given handler
89 | -- to respond to events. If the daemon is already running, don't do
90 | -- anything. Returns immediately.
91 | --
92 | -- The pidfile @PidFile options@ will be created and locked. This
93 | -- function checks the pidfile to see if the daemon is already
94 | -- running.
95 | --
96 | -- The daemon will listen for incoming connections on all interfaces
97 | -- on @daemonPort options@.
98 | --
99 | -- The @handler@ is a function that takes the reader and writer
100 | -- 'ByteString' pipes and does something with them. See
101 | -- 'commandReceiver' for an example handler.
102 | ensureDaemonWithHandlerRunning :: String -- ^ name
103 | -> DaemonOptions -- ^ options
104 | -> Handler () -- ^ handler
105 | -> IO ()
106 | ensureDaemonWithHandlerRunning name options handler = do
107 | home <- getHomeDirectory
108 | let pidfile = case daemonPidFile options of
109 | InHome -> home > ("." ++ name) <.> "pid"
110 | PidFile path -> path
111 | running <- isRunning pidfile
112 | when (not running) $ do
113 | runDetached (Just pidfile) def
114 | (runInForeground (daemonPort options) handler)
115 | when (printOnDaemonStarted options)
116 | (printf "Daemon started on port %d\n" (daemonPort options))
117 | threadDelay (1 * 1000 * 1000) -- 1s delay
118 |
119 | -- | Start the given handler in the foreground. It will listen and
120 | -- respond to events on the given port.
121 | --
122 | -- This is the function that 'ensureDaemonWithHandlerRunning' runs on
123 | -- the daemon thread.
124 | runInForeground :: Port -> Handler () -> IO ()
125 | runInForeground port handler = do
126 | CE.bracket
127 | (bindPort port)
128 | close
129 | (\lsocket ->
130 | runSocketServer lsocket handler)
131 |
132 | -- | Send a command to the daemon running at the given network address
133 | -- and wait for a response.
134 | --
135 | -- This is a simple wrapper around 'runClientWithHandler' that sends a
136 | -- single command and waits for a single response.
137 | --
138 | -- If the connection is closed before receiving a response, return
139 | -- 'Nothing'.
140 | runClient :: (Serialize a, Serialize b)
141 | => HostName -- ^ hostname
142 | -> Port -- ^ port
143 | -> a -- ^ command
144 | -> IO (Maybe b)
145 | runClient hostname port comm =
146 | runClientWithHandler hostname port (commandSender comm)
147 |
148 | -- | Connect to the given network address and run the handler on the
149 | -- reader and wrier pipes for the socket.
150 | --
151 | -- The @handler@ is a function that takes the reader and writer
152 | -- 'ByteString' pipes and does something with them. For an example
153 | -- handler, see 'commandSender', which sends a command and waits for a
154 | -- response.
155 | runClientWithHandler :: HostName -- ^ hostname
156 | -> Port -- ^ port
157 | -> Handler a -- ^ command
158 | -> IO a
159 | runClientWithHandler hostname port handler = do
160 | CE.bracket
161 | (getSocket hostname port)
162 | close
163 | (\s -> runSocketClient s handler)
164 |
165 | -- | Create a socket and bind it to the given port.
166 | bindPort :: Port -> IO Socket
167 | bindPort port = do
168 | CE.bracketOnError
169 | (socket AF_INET Stream defaultProtocol)
170 | close
171 | (\s -> do
172 | -- FIXME See the examples at the end of Network.Socket.ByteString
173 | setSocketOption s ReuseAddr 1
174 | bind s (SockAddrInet (fromIntegral port) (tupleToHostAddress (0, 0, 0, 0)))
175 | listen s maxListenQueue
176 | return s)
177 |
178 | -- | Create a socket connected to the given network address.
179 | getSocket :: HostName -> Port -> IO Socket
180 | getSocket hostname port = do
181 | addrInfos <- getAddrInfo (Just (defaultHints { addrFamily = AF_INET }))
182 | (Just hostname)
183 | (Just $ show port)
184 | CE.bracketOnError
185 | (socket AF_INET Stream defaultProtocol)
186 | close
187 | (\s -> do
188 | connect s (addrAddress $ head addrInfos)
189 | return s)
190 |
--------------------------------------------------------------------------------
/src/System/Posix/Daemon.hs:
--------------------------------------------------------------------------------
1 | -- | This module provides a simple interface to creating, checking the
2 | -- status of, and stopping background jobs.
3 | --
4 | -- Use 'runDetached' to start a background job. For instance, here is
5 | -- a daemon that peridically hits a webserver:
6 | --
7 | -- > import Control.Concurrent
8 | -- > import Control.Monad
9 | -- > import Data.Default
10 | -- > import Data.Maybe
11 | -- > import Network.BSD
12 | -- > import Network.HTTP
13 | -- > import Network.URI
14 | -- > import System.Posix.Daemon
15 | -- >
16 | -- > main :: IO ()
17 | -- > main = runDetached (Just "diydns.pid") def $ forever $ do
18 | -- > hostname <- getHostName
19 | -- > _ <- simpleHTTP
20 | -- > (Request { rqURI = fromJust (parseURI "http://foo.com/dns")
21 | -- > , rqMethod = GET
22 | -- > , rqHeaders = []
23 | -- > , rqBody = hostname })
24 | -- > threadDelay (600 * 1000 * 1000)
25 | --
26 | -- To check if the above job is running, use 'isRunning' with the same
27 | -- pidfile:
28 | --
29 | -- > isRunning "diydns.pid"
30 | --
31 | -- Finally, to stop the above job (maybe because we're rolling a new
32 | -- version of it), use 'kill':
33 | --
34 | -- > kill "diydns.pid"
35 | --
36 | -- To stop a job and wait for it to close (and release its pidfile), use
37 | -- 'killAndWait':
38 | --
39 | -- > killAndWait "diydns.pid" >> doSomething
40 | --
41 | -- As a side note, the code above is a script that the author uses as
42 | -- a sort of homebrew dynamic DNS: the remote address is a CGI script
43 | -- that records the IP addresses of all incoming requests in separate
44 | -- files named after the contents of the requests; the addresses are
45 | -- then viewable with any browser.
46 | module System.Posix.Daemon (
47 | -- * Starting
48 | runDetached, Redirection(..),
49 |
50 | -- * Status
51 | isRunning,
52 |
53 | -- * Stopping
54 | kill, killAndWait, brutalKill
55 | ) where
56 |
57 | import Prelude hiding ( FilePath )
58 |
59 | import Control.Monad ( when )
60 | import Data.ByteString.Char8 ( unpack )
61 | import Data.Default ( Default(..) )
62 | import System.Directory ( doesFileExist )
63 | import System.FilePath ( FilePath )
64 | import System.IO ( SeekMode(..), hFlush, stdout )
65 | import System.Posix.Files ( stdFileMode )
66 | import System.Posix.IO ( openFd, OpenMode(..), defaultFileFlags, closeFd
67 | , dupTo, stdInput, stdOutput, stdError, getLock
68 | , createFile, fdWrite
69 | , LockRequest (..), setLock, waitToSetLock, creat )
70 | import System.Posix.IO.ByteString ( fdRead )
71 | import System.Posix.Process ( getProcessID, forkProcess, createSession )
72 | import System.Posix.Signals ( Signal, signalProcess, sigQUIT, sigKILL )
73 |
74 | -- | Where should the output (and input) of a daemon be redirected to?
75 | -- (we can't just leave it to the current terminal, because it may be
76 | -- closed, and that would kill the daemon).
77 | --
78 | -- When in doubt, just use 'def', the default value.
79 | --
80 | -- 'DevNull' causes the output to be redirected to @\/dev\/null@. This
81 | -- is safe and is what you want in most cases.
82 | --
83 | -- If you don't want to lose the output (maybe because you're using it
84 | -- for logging), use 'ToFile', instead.
85 | data Redirection = DevNull
86 | | ToFile FilePath
87 | deriving ( Show )
88 |
89 | instance Default Redirection where
90 | def = DevNull
91 |
92 | -- | Run the given action detached from the current terminal; this
93 | -- creates an entirely new process. This function returns
94 | -- immediately. Uses the double-fork technique to create a well
95 | -- behaved daemon. If @pidfile@ is given, check/write it; if we
96 | -- cannot obtain a lock on the file, another process is already using
97 | -- it, so fail. The @redirection@ parameter controls what to do with
98 | -- the standard channels (@stdin@, @stderr@, and @stdout@).
99 | --
100 | -- See:
101 | --
102 | -- Note: All unnecessary fds should be close before calling this.
103 | -- Otherwise, you get an fd leak.
104 | runDetached :: Maybe FilePath -- ^ pidfile
105 | -> Redirection -- ^ redirection
106 | -> IO () -- ^ program
107 | -> IO ()
108 | runDetached maybePidFile redirection program = do
109 | -- check if the pidfile exists; fail if it does
110 | checkPidFile
111 | -- fork first child
112 | ignore $ forkProcess $ do
113 | -- create a new session and make this process its leader; see
114 | -- setsid(2)
115 | ignore $ createSession
116 | -- fork second child
117 | ignore $ forkProcess $ do
118 | -- create the pidfile
119 | writePidFile
120 | -- remap standard fds
121 | remapFds
122 | -- run the daemon
123 | program
124 | where
125 | ignore act = act >> return ()
126 |
127 | -- Remap the standard channels based on the @redirection@
128 | -- parameter.
129 | remapFds = do
130 | devnull <- openFd "/dev/null" ReadOnly defaultFileFlags
131 | ignore (dupTo devnull stdInput)
132 | closeFd devnull
133 |
134 | let file = case redirection of
135 | DevNull -> "/dev/null"
136 | ToFile filepath -> filepath
137 | fd <- openFd file ReadWrite defaultFileFlags { creat = Just stdFileMode }
138 | hFlush stdout
139 | mapM_ (dupTo fd) [stdOutput, stdError]
140 | closeFd fd
141 |
142 | -- Convert the 'FilePath' @pidfile@ to a regular 'String' and run
143 | -- the action with it.
144 | withPidFile act =
145 | case maybePidFile of
146 | Nothing -> return ()
147 | Just pidFile -> act pidFile
148 |
149 | -- Check if the pidfile exists; fail if it does, and create it, otherwise
150 | checkPidFile = withPidFile $ \pidFile -> do
151 | running <- isRunning pidFile
152 | when running $ fail "already running"
153 |
154 | writePidFile = withPidFile $ \pidFile -> do
155 | fd <- createFile pidFile stdFileMode
156 | setLock fd (WriteLock, AbsoluteSeek, 0, 0)
157 | pid <- getProcessID
158 | ignore $ fdWrite fd (show pid)
159 | -- note that we do not close the fd; doing so would release
160 | -- the lock
161 |
162 | -- | Return 'True' if the given file is locked by a process. In our
163 | -- case, returns 'True' when the daemon that created the file is still
164 | -- alive.
165 | isRunning :: FilePath -> IO Bool
166 | isRunning pidFile = do
167 | dfe <- doesFileExist pidFile
168 | if dfe
169 | then do
170 | fd <- openFd pidFile ReadWrite defaultFileFlags
171 | -- is there an *incompatible* lock on the pidfile?
172 | ml <- getLock fd (WriteLock, AbsoluteSeek, 0, 0)
173 | pid <- fdRead fd 100 >>= \x -> return (unpack x)
174 | closeFd fd
175 | case ml of
176 | Nothing -> do
177 | pid' <- getProcessID
178 | return (read pid == pid')
179 | Just _ -> do
180 | return True
181 | else do
182 | return False
183 |
184 | -- | Send 'sigQUIT' to the process recorded in the pidfile. This
185 | -- gives the process a chance to close cleanly.
186 | kill :: FilePath -> IO ()
187 | kill = signalProcessByFilePath sigQUIT
188 |
189 | -- | Kill a process and wait for it to release its pidfile
190 | killAndWait :: FilePath -> IO ()
191 | killAndWait pidFile = do
192 | signalProcessByFilePath sigQUIT pidFile
193 | fd <- openFd pidFile ReadWrite defaultFileFlags
194 | waitToSetLock fd (WriteLock, AbsoluteSeek, 0, 0)
195 | closeFd fd
196 |
197 | -- | Send 'sigKILL' to the process recorded in the pidfile. This
198 | -- immediately kills the process.
199 | brutalKill :: FilePath -> IO ()
200 | brutalKill = signalProcessByFilePath sigKILL
201 |
202 | -- | Send a signal to a process whose pid is recorded in a file.
203 | signalProcessByFilePath :: Signal -> FilePath -> IO ()
204 | signalProcessByFilePath signal pidFile = do
205 | pid <- readFile pidFile
206 | signalProcess signal (read pid)
207 |
--------------------------------------------------------------------------------
/stack.yaml:
--------------------------------------------------------------------------------
1 | # This file was automatically generated by 'stack init'
2 | #
3 | # Some commonly used options have been documented as comments in this file.
4 | # For advanced use and comprehensive documentation of the format, please see:
5 | # https://docs.haskellstack.org/en/stable/yaml_configuration/
6 |
7 | # Resolver to choose a 'specific' stackage snapshot or a compiler version.
8 | # A snapshot resolver dictates the compiler version and the set of packages
9 | # to be used for project dependencies. For example:
10 | #
11 | # resolver: lts-3.5
12 | # resolver: nightly-2015-09-21
13 | # resolver: ghc-7.10.2
14 | #
15 | # The location of a snapshot can be provided as a file or url. Stack assumes
16 | # a snapshot provided as a file might change, whereas a url resource does not.
17 | #
18 | # resolver: ./custom-snapshot.yaml
19 | # resolver: https://example.com/snapshots/2018-01-01.yaml
20 | resolver: lts-14.22
21 |
22 | # User packages to be built.
23 | # Various formats can be used as shown in the example below.
24 | #
25 | # packages:
26 | # - some-directory
27 | # - https://example.com/foo/bar/baz-0.0.2.tar.gz
28 | # subdirs:
29 | # - auto-update
30 | # - wai
31 | packages:
32 | - .
33 | # Dependency packages to be pulled from upstream that are not in the resolver.
34 | # These entries can reference officially published versions as well as
35 | # forks / in-progress versions pinned to a git hash. For example:
36 | #
37 | # extra-deps:
38 | # - acme-missiles-0.3
39 | # - git: https://github.com/commercialhaskell/stack.git
40 | # commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a
41 | #
42 | # extra-deps: []
43 |
44 | # Override default flag values for local packages and extra-deps
45 | # flags: {}
46 |
47 | # Extra package databases containing global packages
48 | # extra-package-dbs: []
49 |
50 | # Control whether we use the GHC we find on the path
51 | # system-ghc: true
52 | #
53 | # Require a specific version of stack, using version ranges
54 | # require-stack-version: -any # Default
55 | # require-stack-version: ">=2.1"
56 | #
57 | # Override the architecture used by stack, especially useful on Windows
58 | # arch: i386
59 | # arch: x86_64
60 | #
61 | # Extra directories used by stack for building
62 | # extra-include-dirs: [/path/to/dir]
63 | # extra-lib-dirs: [/path/to/dir]
64 | #
65 | # Allow a newer minor version of GHC than the snapshot specifies
66 | # compiler-check: newer-minor
67 |
--------------------------------------------------------------------------------
/stack.yaml.lock:
--------------------------------------------------------------------------------
1 | # This file was autogenerated by Stack.
2 | # You should not edit this file by hand.
3 | # For more information, please see the documentation at:
4 | # https://docs.haskellstack.org/en/stable/lock_files
5 |
6 | packages: []
7 | snapshots:
8 | - completed:
9 | size: 524164
10 | url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/14/22.yaml
11 | sha256: 7ad8f33179b32d204165a3a662c6269464a47a7e65a30abc38d01b5a38ec42c0
12 | original: lts-14.22
13 |
--------------------------------------------------------------------------------
/test/Daemon.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
2 |
3 | module Main where
4 |
5 | import Control.Concurrent
6 | import Control.Exception
7 | import Control.Monad
8 | import Data.Default
9 | import System.Directory
10 | import System.Posix.Daemon
11 | import System.Posix.Process
12 |
13 | import Test.Framework
14 | import Test.Framework.Providers.HUnit
15 | import Test.HUnit
16 |
17 | main :: IO ()
18 | main = defaultMainWithOpts
19 | [ testCase "firstRun" testFirst
20 | , testCase "withPid" testWithPid
21 | , testCase "isRunning" testIsRunning
22 | , testCase "exclusion" testExclusion
23 | , testCase "release" testRelease
24 | , testCase "redirection" testRedirection
25 | ] mempty
26 |
27 | ensureRemoved :: [FilePath] -> IO ()
28 | ensureRemoved filepaths = forM_ filepaths $ \filepath -> do
29 | exists <- doesFileExist filepath
30 | when exists $ do
31 | removeFile filepath
32 |
33 | -- Wait the given number of ms.
34 | sleep :: Int -> IO ()
35 | sleep n = threadDelay (n * 1000)
36 |
37 | testFirst :: Assertion
38 | testFirst = flip finally (ensureRemoved ["tmp"]) $ do
39 | let txtExp = "42"
40 | runDetached Nothing def $ do
41 | writeFile "tmp" txtExp
42 | sleep 500
43 | txt <- readFile "tmp"
44 | txt @?= txtExp
45 |
46 | testWithPid :: Assertion
47 | testWithPid = flip finally (ensureRemoved ["pid", "tmp"]) $ do
48 | let txtExp = "42"
49 | runDetached (Just "pid") def $ do
50 | pid <- getProcessID
51 | pid' <- readFile "pid"
52 | if show pid == pid'
53 | then writeFile "tmp" txtExp
54 | else writeFile "tmp" "wrong pid recorded"
55 | sleep 500
56 | txt <- readFile "tmp"
57 | txt @?= txtExp
58 | pid <- readFile "pid"
59 | null pid @?= False
60 |
61 | testIsRunning :: Assertion
62 | testIsRunning = flip finally (ensureRemoved ["pid", "tmp"]) $ do
63 | runDetached (Just "pid") def $ do
64 | running <- isRunning "pid"
65 | writeFile "tmp" (show running)
66 | sleep 10000
67 | sleep 500
68 |
69 | -- FIXME There's some weird behaviour when the process that has locked
70 | -- the file (or its ancestors, or its descendents) use 'isRunning'.
71 | --
72 | -- The semantics of 'fnctl' are "try to aquire the requested lock; if
73 | -- there is an incompatible lock in place, return it". Of course,
74 | -- this means that the process that acquired the lock sees it as
75 | -- unlocked.
76 | --
77 | -- We mitigated the obvious part of the problem (same process) by
78 | -- checking the pid in the pidfile. Now, we're left with the case
79 | -- where an ancestor of the process thinks it can set the lock.
80 |
81 | -- running <- isRunning "pid"
82 | -- running @?= True
83 | txt <- readFile "tmp"
84 | txt @?= "True"
85 |
86 | testExclusion :: Assertion
87 | testExclusion = flip finally (ensureRemoved ["pid", "tmp"]) $ do
88 | let txtExp = "ok"
89 | runDetached (Just "pid") def $ do
90 | sleep 1000
91 | sleep 500
92 | handle (\(_ :: SomeException) -> writeFile "tmp" txtExp)
93 | (runDetached (Just "pid") def $ do
94 | writeFile "tmp" "failed")
95 | sleep 500
96 | txt <- readFile "tmp"
97 | txt @?= txtExp
98 |
99 | testRelease :: Assertion
100 | testRelease = flip finally (ensureRemoved ["pid", "tmp"]) $ do
101 | let txtExp = "ok"
102 | runDetached (Just "pid") def $ do
103 | writeFile "tmp" txtExp
104 | sleep 500
105 | txt <- readFile "tmp"
106 | txt @?= txtExp
107 | let txtExp' = "ok"
108 | runDetached (Just "pid") def $ do
109 | writeFile "tmp" txtExp'
110 | sleep 500
111 | txt' <- readFile "tmp"
112 | txt' @?= txtExp'
113 |
114 | testRedirection :: Assertion
115 | testRedirection = flip finally (ensureRemoved ["tmp"]) $ do
116 | let txtExp = "ok"
117 | runDetached Nothing (ToFile "tmp") $ do
118 | putStr "ok"
119 | sleep 500
120 | txt <- readFile "tmp"
121 | txt @?= txtExp
122 |
--------------------------------------------------------------------------------