├── .gitignore ├── LICENSE ├── README.md ├── benchmark ├── images ├── enable-bash.jpg ├── nodeapp-notify.jpg ├── nodeapp-pm2.jpg ├── nodeapp.jpg └── updates.png ├── install ├── nginx ├── NodeApp.stpl └── NodeApp.tpl ├── nodeapp.js ├── nodeapp.php ├── nodeapp ├── .nvmrc ├── .restart │ └── restart ├── README.md ├── app.config.js ├── app.js └── package.json ├── nodeapp_debounce.sh ├── pages ├── nodeapp.php └── nodeapplog.php ├── plugin.php └── uninstall /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hcpp-nodeapp 2 | A plugin for Hestia Control Panel (via [hestiacp-pluginable](https://github.com/virtuosoft-dev/hestiacp-pluginable)) that enables hosting generic NodeJS based applications with control via [PM2 (Process Manager)](https://pm2.keymetrics.io). With this plugin installed, user accounts can host their own NodeJS applications. A simple [Hello World! ExpressJS application](https://expressjs.com/en/starter/hello-world.html) is included as the default NodeApp application. [NVM (NodeJS Version Manager)](https://github.com/nvm-sh/nvm) is also included and the default PM2 configuration file will automatically select the proper NodeJS version based on the simple .nvmrc file. 3 | 4 | Version 2.X now includes a (PM2 based) process list UI within HestiaCP that lists all NodeApps for a given user account under the Web tab (see #1 in screenshot below). Additional controls have been added to allow for Start, Stop, and Restart with bulk actions and viewing of the log output for each NodeApp process (see #2 in screenshot below). 5 | 6 |

7 | Figure 1 - NodeApp process list, control, and logs 8 | 9 | Long term support NodeJS versions that are automatically installed with this plugin include: 10 | 11 | * Gallium v16 12 | * Hydrogen v18 13 | * Iron v20 14 | * Jod v22 15 | 16 | NodeApp also includes an updated administrator's [Server Settings -> Updates]() screen (see figure 2 below) that shows the current state of NVM NodeJS versions. All versions are automatically updated and maintained along with any global modules when HestiaCP's native [Enable Automatic Updates]() option is turned on. 17 | 18 |

19 | 20 |   21 | ## Installation 22 | HCPP-NodeApp requires an Ubuntu or Debian based installation of [Hestia Control Panel](https://hestiacp.com) in addition to an installation of [HestiaCP-Pluginable](https://github.com/virtuosoft-dev/hestiacp-pluginable) to function; please ensure that you have first installed pluginable on your Hestia Control Panel before proceeding. Clone the latest release version (i.e. replace **v2.0.3** below with the latest release version) to the nodeapp folder: 23 | 24 | ``` 25 | cd /usr/local/hestia/plugins 26 | sudo git clone --branch v2.0.3 https://github.com/virtuosoft-dev/hcpp-nodeapp nodeapp 27 | ``` 28 | 29 | Note: It is important that the destination plugin folder name is `nodeapp`. 30 | 31 | Be sure to logout and login again to your Hestia Control Panel as the admin user or, as admin, visit Server (gear icon) -> Configure -> Plugins -> Save; the plugin will immediately start installing NodeJS depedencies in the background. 32 | 33 |

34 | Figure 3 - NodeApp plugin install notification 35 | 36 | A notification will appear under the admin user account indicating *"NodeApp plugin has finished installing"* when complete. This may take awhile before the options appear in Hestia. You can force manual installation via: 37 | 38 | ``` 39 | cd /usr/local/hestia/plugins/nodeapp 40 | sudo ./install 41 | sudo touch "/usr/local/hestia/data/hcpp/installed/nodeapp" 42 | ``` 43 | 44 |   45 | ## Using NodeApp to Host a NodeJS Website 46 | The Hestia user account to be associated with a new web domain must have bash SSH access. This is to allow Hestia to switch to their user account to start and stop the NodeJS application. Login as the admin user in Hestia to grant bash SSH Access. Simply edit the Hestia user account; 1) Click the *'Advanced Options'* button after ***'Edit User'*** and 2) Select `bash` from the combobox under ***'SSH Access'***, and save the changes (see image below). 47 | 48 |

49 | Figure 4 - Enable Bash for domain 50 | 51 | The basic default NodeJS application is the [Hello World! ExpressJS application](https://expressjs.com/en/starter/hello-world.html). To use it, simply select the user account (that has bash SSH access enabled), and add a web domain. Edit the web domain; 1) Click the ***'Advanced Options'*** and 2) Select `NodeApp` in the ***'Proxy Template'*** combobox (if the option is missing, wait for installation to complete or attempt manual installation instructions above). 52 | 53 |

54 | Figure 5 - Selecting a Proxy Template 55 | 56 | ## Root NodeJS Application Hosting 57 | Using the NodeApp proxy template will allow you to host a NodeJS application from the web domain root (for a subfolder, see **'Subfolder NodeJS Application below'**). The example above will serve the NodeJS application using PM2. After saving your changes, you should be able to visit the web domain and see the `Hello World!` text on a white background. The basic NodeJS Express application lives in the `app.js` file which is located in the nodeapp folder. I.e. for the user "johnsmith" on "example.com", the filename path for the application would be at `/home/johnsmith/web/example.com/nodeapp/app.js`. Hestia control panel will automatically stop the NodeJS application when you select a different proxy template for the domain and restart it when you select NodeApp again. Likewise if you delete the domain, Hestia will free the allocated port from the pool of ports on the system and shutdown the NodeJS app prior to deleting the web domain. 58 | 59 | ## Subfolder NodeJS Application Hosting 60 | The HCPP-NodeApp plugin automatically scans the nodeapp folder for any additional PM2 configuration files (*.config.js) in subfolders (excluding node_modules). If it finds any such files, NodeApp plugin will automatically allocate an application port and auto-generate an Nginx include file, defininig the subfolder path, for addendum to whichever backend proxy template is selected. This allows you to automatically mix the hosting of multiple applications under a single domain. For instance, you can select Hestia's default backend template to host a PHP based application in root (such as WordPress), while hosting a NodeJS based applicaiton in a subfolder (such as VitePress, or Node-RED). Simply create a subfolder within the nodeapp folder and place a valid, unique, *<application name>*.config.js file within the subfolder. You can simply copy the app.config.js file; replace *'app'* with your own application name (be sure to update the package.json's *'main'* property from *'app'* too). Nginx will be configured to serve the NodeJS application under the given subfolder (i.e. www.example.com/nodebb). Note: the *<application name>*.config.js file name must be unique for a given domain. For example, you cannot have two app.config.js files; even if one exists in a subfolder. Instead, i.e. name the second file app2.config.js. 61 | 62 | Likewise, you can select the backend proxy template `NodeApp` and host two NodeJS applications, one from root, and another in a subfolder. Note that the scanning for *.config.js files, automatic allocation of proxy ports, auto-generation of Nginx addendum files, and automatic startup of NodeJS, only takes place when Nginx services are restarted; you can invoke a restart by selecting/re-selecting a different Proxy Template (see figure 4 above) or using HestiaCP's *`suspend'* and *'unsuspend'* actions. You may use suspend/unsuspend options to populate the NodeApp process list. 63 | 64 | 65 | ## Conclusion 66 | With the HCPP-NodeApp plugin, you do not need to configure ports, create Ngnix templates, or customize any templates. The plugin will automatically allocate ports for each user account and web domain (as well as clean them up when they are deleted). It will furnish a unique NodeJS instance using an advanced process manager with watch dog, as well as configure Nginx to securely display the app on your designated web domain or domain subfolder (or both). Your web development stack will be able to leverage the latest in NodeJS technology, use websockets, and run multiple users, and web domains all from the Hestia control panel. 67 | 68 | ## Extending HCPP-NodeApp via Pluginable Actions 69 | The following [hestiacp-pluginable](https://github.com/virtuosoft-dev/hestiacp-pluginable) actions are invoked when using 70 | the NodeApp. Developers can hook and implement their own NodeApp using these actions: 71 | 72 | * **nodeapp_ports_allocated** - *occurs after ports have been allocated for the given domain.* 73 | * **nodeapp_copy_files** - *occurs after include Hello world ExpressJS files are copied.* 74 | * **nodeapp_install_dependencies** - *occurs before `"npm install"`, allows filtering the command.* 75 | * **nodeapp_startup_services** - *occurs before `"pm2 start app.config.js"`, allows filtering the command.* 76 | * **nodeapp_shutdown_services** - *occurs before `"pm2 delete app.config.js"`, allows filtering the command.* 77 | * **nodeapp_write_conf_nodeapp** - *occurs before writing nginx.conf_nodeapp file for app hosting.* 78 | * **nodeapp_write_ssl_conf_nodeapp** - *occurs before writing nginx.ssl.conf_nodeapp file for app hosting.* 79 | * **nodeapp_nginx_confs_written** - *occurs after nginx.conf and nginx.ssl.conf have been written.* 80 | * **nodeapp_resurrect_apps** - *occurs after system reboot and issues the command to restart PM2 apps.* 81 | * **nodeapp_xpath** - *occurs when viewing the NodeApp process list.* 82 | * **nodeapp_html** - *occurs when viewing the NodeApp process list.* 83 | * **nodeapplog_xpath** - *occurs when viewing the NodeApp process log.* 84 | * **nodeapplog_html** - *occurs when viewing the NodeApp process log.* 85 | * **nodeapp_maintenance_start** - *occurs before a maintenance event starts.* 86 | * **nodeapp_maintenance_start** - *occurs after a maintenance event ends.* 87 | * **nodeapp_update_nodejs** - *occurs when a nodejs version is about to be updated.* 88 | * **nodeapp_autoupdate** - *occurs daily if hestia autoupdates is enabled; ideal time perform updates (do_maintenance) tasks.* 89 | 90 | 91 | ## Support the creator 92 | You can help this author's open source development endeavors by donating any amount to Stephen J. Carnam @ Virtuosoft. Your donation, no matter how large or small helps pay for essential time and resources to create MIT and GPL licensed projects that you and the world can benefit from. Click the link below to donate today :) 93 |
94 | 95 | 96 | [
 Donate to this Project 
][KBD] 97 | 98 | 99 |
100 | 101 | 102 | 103 | 104 | [KBD]: https://virtuosoft.com/donate 105 | 106 | https://virtuosoft.com/donate 107 | -------------------------------------------------------------------------------- /benchmark: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # @author Stephen J. Carnam 4 | # @license GNU GENERAL PUBLIC LICENSE Version 2 5 | # @link https://steveorevo.com 6 | # 7 | 8 | # Check if a command is provided 9 | if [ -z "$1" ]; then 10 | echo "Usage: benchmark " 11 | exit 1 12 | fi 13 | 14 | # Capture the start time in nanoseconds 15 | start_time=$(date +%s%N) 16 | 17 | # Run the provided command 18 | "$@" 19 | 20 | # Capture the end time in nanoseconds 21 | end_time=$(date +%s%N) 22 | 23 | # Calculate the elapsed time in seconds with fractional seconds 24 | elapsed_time=$(echo "scale=6; ($end_time - $start_time) / 1000000000" | bc) 25 | 26 | # Format the elapsed time 27 | minutes=$(echo "$elapsed_time / 60" | bc) 28 | seconds=$(echo "$elapsed_time % 60" | bc) 29 | 30 | if (( $(echo "$minutes > 0" | bc -l) )); then 31 | printf "Time taken: %d minutes and %.6f seconds\n" "$minutes" "$seconds" 32 | else 33 | printf "Time taken: %.6f seconds\n" "$seconds" 34 | fi -------------------------------------------------------------------------------- /images/enable-bash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtuosoft-dev/hcpp-nodeapp/8f2ec34b16be83a5291d653d30df2e9dbba2cc81/images/enable-bash.jpg -------------------------------------------------------------------------------- /images/nodeapp-notify.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtuosoft-dev/hcpp-nodeapp/8f2ec34b16be83a5291d653d30df2e9dbba2cc81/images/nodeapp-notify.jpg -------------------------------------------------------------------------------- /images/nodeapp-pm2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtuosoft-dev/hcpp-nodeapp/8f2ec34b16be83a5291d653d30df2e9dbba2cc81/images/nodeapp-pm2.jpg -------------------------------------------------------------------------------- /images/nodeapp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtuosoft-dev/hcpp-nodeapp/8f2ec34b16be83a5291d653d30df2e9dbba2cc81/images/nodeapp.jpg -------------------------------------------------------------------------------- /images/updates.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtuosoft-dev/hcpp-nodeapp/8f2ec34b16be83a5291d653d30df2e9dbba2cc81/images/updates.png -------------------------------------------------------------------------------- /install: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | export DEBIAN_FRONTEND=noninteractive 3 | if [[ -d "/opt/nvm" && -f "/usr/local/hestia/data/templates/web/nginx/NodeApp.stpl" ]] 4 | then 5 | echo "NodeApp appears to already be installed" 6 | exit 7 | fi 8 | 9 | # ############################################ 10 | # # Install NVM, NodeJS, PM2, and grunt 11 | # ############################################ 12 | 13 | # # Remove existing NodeJS installation 14 | # apt remove --purge nodejs -y 15 | 16 | # Get prerequisites, latest NVM version, and build tools if we need to compile from source 17 | apt-get install -y curl build-essential gnupg2 rsync 18 | LATEST_VERSION=$(curl -s https://api.github.com/repos/nvm-sh/nvm/releases/latest | grep '"tag_name":' | cut -d '"' -f 4) 19 | curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/${LATEST_VERSION}/install.sh | bash 20 | source ~/.bashrc 21 | 22 | # Install node version manager, globally 23 | mv ~/.nvm /opt/nvm 24 | chmod -R 755 /opt/nvm 25 | export NVM_DIR="/opt/nvm" 26 | [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm 27 | [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion 28 | export PATH="/opt/nvm:$PATH" 29 | 30 | # Initial install of NodeJS (version 20 is an LTS version) 31 | nvm install v22 32 | npm install -g npm@latest 33 | 34 | # Install last three NodeJS LTS versions 35 | nvm install v16 36 | nvm install v18 37 | nvm install v20 38 | nvm alias default v22 39 | 40 | # Install grunt, pm2 globally for all versions 41 | nvm use v16 42 | npm install -g grunt-cli 43 | npm install -g pm2 44 | nvm use v18 45 | npm install -g grunt-cli 46 | npm install -g pm2 47 | nvm use v20 48 | npm install -g grunt-cli 49 | npm install -g pm2 50 | nvm use v22 51 | npm install -g grunt-cli 52 | npm install -g pm2 53 | 54 | 55 | ############################################ 56 | # Install templates 57 | ############################################ 58 | 59 | rsync -r ./nginx/ /usr/local/hestia/data/templates/web/nginx/ 60 | 61 | ############################################ 62 | # Update global bash.bashrc 63 | ############################################ 64 | 65 | if ! grep -Fxq "# begin hcpp-nodeapp" "/etc/bash.bashrc";then 66 | 67 | cat <> /etc/bash.bashrc 68 | # begin hcpp-nodeapp 69 | export NVM_DIR="/opt/nvm" 70 | [ -s "\$NVM_DIR/nvm.sh" ] && \. "\$NVM_DIR/nvm.sh" # This loads nvm 71 | [ -s "\$NVM_DIR/bash_completion" ] && \. "\$NVM_DIR/bash_completion" # This loads nvm bash_completion 72 | export PATH="/opt/nvm:\$PATH" 73 | # end hcpp-nodeapp 74 | EOT 75 | 76 | fi 77 | 78 | # Comment out /root/.bashrc 79 | BASHRC_FILE="/root/.bashrc" 80 | 81 | # Lines to search for 82 | NVM_LINES=( 83 | 'export NVM_DIR="$HOME/.nvm"' 84 | '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' 85 | '[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"' 86 | ) 87 | 88 | # Iterate over each line and comment it out if not already commented 89 | for line in "${NVM_LINES[@]}"; do 90 | # Escape special characters in the line for use in grep and sed 91 | escaped_line=$(printf '%s\n' "$line" | sed 's/[.[\*^$(){}?+|]/\\&/g') 92 | 93 | # Check if the line exists and is not already commented 94 | if grep -q "$escaped_line" "$BASHRC_FILE" && ! grep -q "# $escaped_line" "$BASHRC_FILE"; then 95 | sed -i "s|$escaped_line|# $line|" "$BASHRC_FILE" 96 | echo "Commented out: $line" 97 | else 98 | echo "Line not found or already commented: $line" 99 | fi 100 | done 101 | 102 | # Notify installation has finished 103 | /usr/local/hestia/bin/v-add-user-notification admin NodeApp " NodeApp plugin has finished installing." 104 | -------------------------------------------------------------------------------- /nginx/NodeApp.stpl: -------------------------------------------------------------------------------- 1 | # 2 | # Serve our NodeJS based app at the base url 3 | # 4 | 5 | server { 6 | listen %ip%:%proxy_ssl_port% ssl http2; 7 | server_name %domain_idn% %alias_idn%; 8 | ssl_certificate %ssl_pem%; 9 | ssl_certificate_key %ssl_key%; 10 | ssl_stapling on; 11 | ssl_stapling_verify on; 12 | error_log /var/log/%web_system%/domains/%domain%.error.log error; 13 | 14 | # TLS 1.3 0-RTT anti-replay 15 | if ($anti_replay = 307) { return 307 https://$host$request_uri; } 16 | if ($anti_replay = 425) { return 425; } 17 | 18 | include %home%/%user%/conf/web/%domain%/nginx.hsts.conf*; 19 | 20 | location /error/ { 21 | alias %home%/%user%/web/%domain%/document_errors/; 22 | } 23 | 24 | location @fallback { 25 | proxy_pass https://%ip%:%web_ssl_port%; 26 | } 27 | 28 | location ~ /\.(?!well-known\/|file) { 29 | deny all; 30 | return 404; 31 | } 32 | 33 | proxy_hide_header Upgrade; 34 | 35 | include %home%/%user%/conf/web/%domain%/nginx.ssl.conf_*; 36 | } 37 | -------------------------------------------------------------------------------- /nginx/NodeApp.tpl: -------------------------------------------------------------------------------- 1 | # 2 | # Serve our NodeJS based app at the base url 3 | # 4 | 5 | server { 6 | listen %ip%:%proxy_port%; 7 | server_name %domain_idn% %alias_idn%; 8 | 9 | include %home%/%user%/conf/web/%domain%/nginx.forcessl.conf*; 10 | 11 | location /error/ { 12 | alias %home%/%user%/web/%domain%/document_errors/; 13 | } 14 | 15 | location @fallback { 16 | proxy_pass http://%ip%:%web_port%; 17 | } 18 | 19 | location ~ /\.(?!well-known\/|file) { 20 | deny all; 21 | return 404; 22 | } 23 | 24 | include %home%/%user%/conf/web/%domain%/nginx.conf_*; 25 | } 26 | -------------------------------------------------------------------------------- /nodeapp.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Give a path to an application config file, return a compatible PM2 app object with 3 | * details and support for .nvmrc, port allocation, and debug mode. 4 | * 5 | * @param {*} path - the path to the *.config.js file, contains the user, domain, etc. 6 | */ 7 | 8 | const { version } = require('os'); 9 | 10 | module.exports = function(path) { 11 | // Get the app name, user, domain, other details given the file path 12 | const fs = require('fs'); 13 | let details = {}; 14 | let parse = path.split('/'); 15 | details._config = parse.pop(); 16 | details._app = details._config.replace('.config.js', ''); 17 | details._domain = parse[4]; 18 | details.name = details._app + ' | ' + details._domain; 19 | details._user = parse[2]; 20 | details.cwd = path.substr(0, path.length - details._config.length - 1); 21 | details.script = details.cwd + '/' + details._app + '.js'; 22 | details.watch = ['.restart']; 23 | details.ignore_watch = []; 24 | details.watch_delay = 5000; 25 | details.restart_delay = 5000; 26 | 27 | // Support optional .nvmrc file or default to current version 28 | let nvmrc = details.cwd + '/.nvmrc'; 29 | let ver = 'current'; 30 | if (fs.existsSync(nvmrc)) { 31 | ver = fs.readFileSync(nvmrc, {encoding: 'utf8', flat: 'r'}).trim(); 32 | } 33 | const {execSync} = require('child_process'); 34 | ver = execSync('/bin/bash -c "source /opt/nvm/nvm.sh && nvm which ' + ver + '"').toString().trim(); 35 | if (!fs.existsSync(ver)) { 36 | console.error(ver); 37 | process.exit(1); 38 | } 39 | details.interpreter = ver; 40 | 41 | // Get the interpreter version from path 42 | let versionMatch = ver.match(/v\d+\.\d+\.\d+/); // Regular expression to match 'v' followed by version numbers 43 | if (versionMatch) { 44 | let version = versionMatch[0]; // Extract the matched version 45 | details.version = version; 46 | } else { 47 | console.error('Version not found in the path'); 48 | } 49 | 50 | // Pass the allocated port number as a -p argument 51 | let port = 0; 52 | let pfile = '/usr/local/hestia/data/hcpp/ports/' + details._user + '/' + details._domain + '.ports'; 53 | let ports = fs.readFileSync(pfile, {encoding:'utf8', flag:'r'}); 54 | ports = ports.split(/\r?\n/); 55 | for( let i = 0; i < ports.length; i++) { 56 | if (ports[i].indexOf(details._app + '_port') > -1) { 57 | port = ports[i]; 58 | break; 59 | } 60 | } 61 | port = parseInt(port.trim().split(' ').pop()); 62 | details._port = port; 63 | details.args = "-p " + details._port; 64 | 65 | // Check for debug mode and pass debug port as port + 3000 offset 66 | if ( fs.existsSync(details.cwd + '/.debug') ) { 67 | details._debugPort = port + 3000; 68 | details.interpreter_args = '--inspect=' + details._debugPort; 69 | } 70 | 71 | 72 | details.linkGlobalModules = function(modules) { 73 | 74 | // Ensure node_modules directory exists 75 | const nodeModulesPath = this.cwd + '/node_modules'; 76 | if (!fs.existsSync(nodeModulesPath)) { 77 | fs.mkdirSync(nodeModulesPath); 78 | } 79 | 80 | // Setup nvm, use npm version specified in .nvmrc 81 | let cmd = "bash -c 'export NVM_DIR=/opt/nvm && source /opt/nvm/nvm.sh && nvm use " + this.version + " && "; 82 | cmd += "cd " + this.cwd + " && "; 83 | 84 | // Link global modules to local node_modules 85 | for (let i = 0; i < modules.length; i++) { 86 | cmd += "unlink node_modules/" + modules[i] + " > /dev/null 2>&1 ; npm link " + modules[i] + " > /dev/null 2>&1 ; "; 87 | } 88 | cmd += "'"; 89 | 90 | // Update npm links 91 | try { 92 | const {execSync} = require('child_process'); 93 | execSync(cmd); 94 | } catch (error) { 95 | // Eat npm link permissions errors 96 | } 97 | } 98 | return details; 99 | } -------------------------------------------------------------------------------- /nodeapp.php: -------------------------------------------------------------------------------- 1 | log( "allocate_ports: $nodeapp_folder" ); 23 | $parse = explode( '/', $nodeapp_folder ); 24 | $user = $parse[2]; 25 | $domain = $parse[4]; 26 | 27 | // Wipe the existing ports for this domain 28 | if ( file_exists( "/usr/local/hestia/data/hcpp/ports/$user/$domain.ports" ) ) { 29 | unlink( "/usr/local/hestia/data/hcpp/ports/$user/$domain.ports" ); 30 | } 31 | 32 | // Allocate a port for each .config.js file found 33 | if ( ! is_dir( $nodeapp_folder ) ) { 34 | $hcpp->log( "allocate_ports: $nodeapp_folder is not a directory" ); 35 | return; 36 | } 37 | $files = $this->get_config_files( $nodeapp_folder ); 38 | foreach($files as $file) { 39 | 40 | // Get the name of the app from the filename 41 | if ( ! preg_match( '/\.config\.js$/', $file ) ) continue; 42 | $file = explode( '/', $file ); 43 | $file = end( $file ); 44 | $name = str_replace( '.config.js', '', $file ); 45 | $name = preg_replace( "/[^a-zA-Z0-9-_]+/", "", $name ) . "_port"; 46 | 47 | // Allocate a port for the app 48 | $hcpp->allocate_port( $name, $user, $domain ); 49 | } 50 | 51 | // Throw a nodeapp event to allow other plugins to allocate ports 52 | $args = [ 53 | 'user' => $user, 54 | 'domain' => $domain, 55 | 'nodeapp_folder' => $nodeapp_folder 56 | ]; 57 | $hcpp->do_action( 'nodeapp_ports_allocated', $args ); 58 | } 59 | 60 | /** 61 | * Constructor, listen for the priv_change_web_domain_proxy_tpl event 62 | */ 63 | public function __construct() { 64 | global $hcpp; 65 | $hcpp->add_action( 'v_change_web_domain_proxy_tpl', [ $this, 'v_change_web_domain_proxy_tpl'] ); 66 | $hcpp->add_action( 'v_delete_web_domain_backend', [ $this, 'v_delete_web_domain_backend' ] ); 67 | $hcpp->add_action( 'v_delete_web_domain', [ $this, 'v_delete_web_domain_backend' ] ); 68 | $hcpp->add_action( 'v_rebuild_web_domain', [ $this, 'v_rebuild_web_domain' ] ); 69 | $hcpp->add_action( 'v_suspend_web_domain', [ $this, 'v_suspend_web_domain' ] ); 70 | $hcpp->add_action( 'v_unsuspend_web_domain', [ $this, 'v_unsuspend_domain' ] ); // Bulk unsuspend domains only throws this event 71 | $hcpp->add_action( 'v_unsuspend_domain', [ $this, 'v_unsuspend_domain' ] ); // Individually unsuspend domain only throws this event 72 | $hcpp->add_action( 'v_update_sys_queue', [ $this, 'v_update_sys_queue' ] ); 73 | $hcpp->add_action( 'hcpp_invoke_plugin', [ $this, 'hcpp_invoke_plugin' ] ); 74 | $hcpp->add_action( 'hcpp_list_web_xpath', [ $this, 'hcpp_list_web_xpath' ] ); 75 | $hcpp->add_action( 'hcpp_list_updates_xpath', [ $this, 'hcpp_list_updates_xpath' ] ); 76 | $hcpp->add_action( 'hcpp_add_webapp_xpath', [ $this, 'hcpp_add_webapp_xpath' ] ); 77 | $hcpp->add_action( 'hcpp_rebooted', [ $this, 'hcpp_rebooted' ] ); 78 | $hcpp->add_action( 'hcpp_runuser', [ $this, 'hcpp_runuser' ] ); 79 | $hcpp->add_action( 'v_restart_proxy', [ $this, 'v_restart_proxy'] ); 80 | 81 | // Rewrite config files on ssl related events 82 | $hcpp->add_action( 'v_add_web_domain_ssl', [ $this, 'update_nginx_files'] ); 83 | $hcpp->add_action( 'v_delete_web_domain_ssl', [ $this, 'update_nginx_files'] ); 84 | $hcpp->add_action( 'v_add_web_domain_ssl_force', [ $this, 'update_nginx_files'] ); 85 | $hcpp->add_action( 'v_delete_web_domain_ssl_force', [ $this, 'update_nginx_files'] ); 86 | 87 | $hcpp->add_custom_page( 'nodeapp', __DIR__ . '/pages/nodeapp.php' ); 88 | $hcpp->add_custom_page( 'nodeapplog', __DIR__ . '/pages/nodeapplog.php' ); 89 | } 90 | 91 | /** 92 | * Do maintenance will shutdown all running apps, across all users that are 93 | * using the specified major version of NodeJS and invoke the given callback. 94 | * Lastly, after the callback has returned, the apps will be restarted. 95 | * 96 | * @param callable $cb_maintenance The callback to invoke after all apps have been shutdown, a [user=>apps] array will be passed of stopped apps. 97 | * @param array $majors The list of major nodejs versions to perform maintenance on; leave empty to shutdown apps from all versions. 98 | * @param array $apps The list of apps to perform maintenance on; leave empty to shutdown all apps. 99 | */ 100 | public function do_maintenance( $cb_maintenance = null, $majors = [], $apps = [] ) { 101 | 102 | // Check if majors array is empty and get all majors as default 103 | global $hcpp; 104 | $hcpp->log( 'nodeapp do_maintenance' ); 105 | $hcpp->log( $majors ); 106 | 107 | if ( count( $majors ) == 0 ) { 108 | $versions = $this->get_versions(); 109 | foreach( $versions as $v ) { 110 | $majors[] = $hcpp->getLeftMost( $v['installed'], '.' ); 111 | } 112 | } 113 | 114 | // Get user list of PM2 (bash) capable users 115 | $all = $hcpp->run( 'v-list-users json' ); 116 | $users = []; 117 | foreach( $all as $user => $details ) { 118 | if ( $details['SHELL'] == 'bash' ) { 119 | $users[] = $user; 120 | } 121 | } 122 | 123 | // Find any running apps using the major version across all users 124 | $pm2_list = []; 125 | foreach( $users as $user) { 126 | $pm2 = $this->get_pm2_list( $user ); 127 | if ( is_null( $pm2 ) ) continue; 128 | foreach( $pm2 as $p ) { 129 | if ( $p['pm2_env']['status'] == 'online' ) { 130 | $version = $p['pm2_env']['exec_interpreter']; 131 | $version = $hcpp->getRightMost( $version, '/v' ); 132 | $version = $hcpp->getLeftMost( $version, '/' ); 133 | $major = $hcpp->getLeftMost( $version, '.' ); 134 | if ( in_array( $major, $majors ) ) { 135 | if ( count( $apps ) == 0 ) { 136 | $pm2_list[$user][] = $p['pm_id']; 137 | }else{ 138 | 139 | // Filter by app name i.e. 'ghost' in 'ghost | test1.dev.pw' 140 | $name = $hcpp->getLeftMost( $p['name'], ' | ' ); 141 | if ( in_array( $name, $apps ) ) { 142 | $pm2_list[$user][] = $p['pm_id']; 143 | } 144 | } 145 | } 146 | } 147 | } 148 | } 149 | 150 | // Shutdown all apps by id for each user 151 | foreach( $pm2_list as $user => $app_ids ) { 152 | if ( count( $app_ids ) > 0 ) { 153 | $this->stop_pm2_ids( $app_ids, $user ); 154 | } 155 | } 156 | 157 | // Invoke the maintenance callback 158 | if ( is_callable( $cb_maintenance ) ) { 159 | $cb_maintenance( $pm2_list ); 160 | } 161 | 162 | // Restart the stopped apps by id for each user 163 | foreach( $pm2_list as $user => $app_ids ) { 164 | if ( count( $app_ids ) > 0 ) { 165 | $this->restart_pm2_ids( $app_ids, $user ); 166 | } 167 | } 168 | } 169 | 170 | /** 171 | * Throw the nodeapp_nginx_modified event to allow other plugins to modify the nginx config files 172 | */ 173 | public function do_nginx_modified( $restart = false ) { 174 | global $hcpp; 175 | $hcpp->log( "do_nginx_modified with restart: $restart" ); 176 | $lines = file( "/tmp/nodeapp_nginx_modified" ); 177 | unlink( "/tmp/nodeapp_nginx_modified" ); 178 | 179 | // Remove any duplicate lines 180 | $lines = array_unique( $lines ); 181 | $conf_folders = []; 182 | foreach( $lines as $line ) { 183 | $line = explode( ' ', $line ); 184 | $user = $line[0]; 185 | $domain = $line[1]; 186 | $conf_folders[] = trim( "/home/$user/conf/web/$domain" ); 187 | } 188 | $conf_folders = $hcpp->do_action( "nodeapp_nginx_confs_written", $conf_folders ); 189 | if ( $restart ) { 190 | $hcpp->run( "v-restart-proxy" ); 191 | } 192 | } 193 | 194 | /** 195 | * Delete the PM2 apps for the given user by ids. 196 | * 197 | * @param array $pm2_ids The list of PM2 process ids to delete 198 | */ 199 | public function delete_pm2_ids( $pm2_ids ) { 200 | $username = $_SESSION["user"]; 201 | if ($_SESSION["look"] != "") { 202 | $username = $_SESSION["look"]; 203 | } 204 | global $hcpp; 205 | $pm2_ids = escapeshellarg( json_encode( $pm2_ids ) ); 206 | $list = json_decode( $hcpp->run("v-invoke-plugin nodeapp_delete_pm2_ids " . $username . ' ' . $pm2_ids ), true ); 207 | } 208 | 209 | /** 210 | * Gather a list of all valid PM2 configuration files that allocate ports from the given folder 211 | */ 212 | public function get_config_files( $dir ) { 213 | global $hcpp; 214 | $configFiles = array(); 215 | $files = scandir( $dir ); 216 | foreach ( $files as $file ) { 217 | if ( $file == '.' || $file == '..' ) continue; 218 | $path = $dir . '/' . $file; 219 | if ( is_dir( $path ) && $file != "node_modules" ) { 220 | $configFiles = array_merge( $configFiles, $this->get_config_files( $path ) ); 221 | } else if ( preg_match('/\.config\.js$/', $file ) ) { 222 | 223 | // Sanitize the name of the app to prevent Nginx injection 224 | if ( ! preg_match( '/\.config\.js$/', $file ) ) continue; 225 | $file = explode( '/', $file ); 226 | $file = end( $file ); 227 | $name = str_replace( '.config.js', '', $file ); 228 | $name = preg_replace( "/[^a-zA-Z0-9-_]+/", "", $name ); 229 | if ( $path == $dir . '/' . $name . '.config.js' ) { 230 | 231 | // Check for hestia pm2 port allocating validity 232 | if ( file_exists( $path ) && strpos( file_get_contents( $path ), '/usr/local/hestia') !== false ) { 233 | $configFiles[] = $path; 234 | } 235 | } 236 | } 237 | } 238 | return $configFiles; 239 | } 240 | 241 | /** 242 | * Generate Nginx proxy settings for each .config.js file found in subfolders 243 | * and map the subfolder to a matching reverse proxy url of the same path 244 | */ 245 | public function generate_nginx_files( $nodeapp_folder, $inc_root = true ) { 246 | global $hcpp; 247 | $parse = explode( '/', $nodeapp_folder ); 248 | $user = $parse[2]; 249 | $domain = $parse[4]; 250 | $files = $this->get_config_files( $nodeapp_folder ); 251 | 252 | // Remove prior nginx config files 253 | if ( file_exists( "/home/$user/conf/web/$domain/nginx.ssl.conf_nodeapp" ) ) { 254 | unlink( "/home/$user/conf/web/$domain/nginx.ssl.conf_nodeapp" ); 255 | } 256 | if ( file_exists( "/home/$user/conf/web/$domain/nginx.conf_nodeapp" ) ) { 257 | unlink( "/home/$user/conf/web/$domain/nginx.conf_nodeapp" ); 258 | } 259 | 260 | // Write port variables in nginx.hsts.conf_ports and nginx.forcessl.conf_ports 261 | $file = "/usr/local/hestia/data/hcpp/ports/$user/$domain.ports"; 262 | if ( file_exists( $file ) ) { 263 | $content = "include /usr/local/hestia/data/hcpp/ports/$user/$domain.ports;"; 264 | file_put_contents( "/home/$user/conf/web/$domain/nginx.forcessl.conf_ports", $content ); 265 | file_put_contents( "/home/$user/conf/web/$domain/nginx.hsts.conf_ports", $content ); 266 | }else{ 267 | if ( file_exists( "/home/$user/conf/web/$domain/nginx.forcessl.conf_ports" ) ) { 268 | unlink( "/home/$user/conf/web/$domain/nginx.forcessl.conf_ports" ); 269 | } 270 | if ( file_exists( "/home/$user/conf/web/$domain/nginx.hsts.conf_ports" ) ) { 271 | unlink( "/home/$user/conf/web/$domain/nginx.hsts.conf_ports" ); 272 | } 273 | } 274 | 275 | // Generate new nodeapp nginx config files 276 | $nginx = ''; 277 | foreach($files as $file) { 278 | 279 | $subfolder = str_replace( "$nodeapp_folder/", '', $file ); 280 | if ( strpos( $subfolder, '/' ) === false ) { 281 | $subfolder = '/'; 282 | }else{ 283 | $subfolder = '/' . $hcpp->delRightMost($subfolder, '/') . '/'; 284 | } 285 | if ( $inc_root == false && $subfolder == '/' ) continue; // Skip root 286 | $app = $hcpp->getRightMost( $file, '/' ); 287 | $app = str_replace( '.config.js', '', $app ); 288 | $nginx .= 'location ' . $subfolder . ' { 289 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 290 | proxy_set_header X-Forwarded-Proto $scheme; 291 | proxy_set_header Host $host; 292 | proxy_pass http://127.0.0.1:$' . $app . '_port; 293 | proxy_http_version 1.1; 294 | proxy_set_header Upgrade $http_upgrade; 295 | proxy_set_header Connection "upgrade"; 296 | }' . "\n"; 297 | } 298 | 299 | // Write the nginx config nodeapp subfolder file to the user's conf folder 300 | if ($nginx != '') { 301 | $args = [ 302 | 'user' => $user, 303 | 'domain' => $domain, 304 | 'nginx' => $nginx 305 | ]; 306 | 307 | // Allow other plugins to modify nginx conf_nodeapp files 308 | $args = $hcpp->do_action( 'nodeapp_write_conf_nodeapp', $args ); 309 | $nginx = $args['nginx']; 310 | file_put_contents( "/home/$user/conf/web/$domain/nginx.conf_nodeapp", $nginx ); 311 | 312 | // Overrite the proxy_hide_header in the SSL config file 313 | $nginx .= "# Override prev. proxy_hide_header Upgrade\nadd_header Upgrade \$http_upgrade always;"; 314 | $args['nginx'] = $nginx; 315 | $args = $hcpp->do_action( 'nodeapp_write_ssl_conf_nodeapp', $args ); 316 | $nginx = $args['nginx']; 317 | file_put_contents( "/home/$user/conf/web/$domain/nginx.ssl.conf_nodeapp", $nginx ); 318 | } 319 | 320 | // Queue for single nginx files modified event 321 | // Check if the file exists and doesn't already have $user $domain in it 322 | if ( file_exists( "/tmp/nodeapp_nginx_modified" ) ) { 323 | $content = file_get_contents( "/tmp/nodeapp_nginx_modified" ); 324 | if ( strpos( $content, "$user $domain" ) === false ) { 325 | file_put_contents( "/tmp/nodeapp_nginx_modified", "$user $domain\n" ); 326 | } 327 | }else{ 328 | file_put_contents("/tmp/nodeapp_nginx_modified", "$user $domain\n", FILE_APPEND); 329 | } 330 | } 331 | 332 | /** 333 | * Get the list of PM2 processes for the given user 334 | * 335 | * @param string $user The username to get the PM2 process list for or the current HestiaCP user if not provided 336 | * @return array The list of PM2 processes for the given user 337 | */ 338 | public function get_pm2_list( $user = '""' ) { 339 | if ( $user == '""' && isset( $_SESSION ) ) { 340 | $user = $_SESSION['user']; 341 | if ( $_SESSION['look'] != '' ) { 342 | $user = $_SESSION['look']; 343 | } 344 | } 345 | global $hcpp; 346 | $list = $hcpp->run("v-invoke-plugin nodeapp_pm2_jlist " . $user); 347 | $list = '[' . $hcpp->delLeftMost( $list, '[' ); 348 | $list = json_decode( $list, true ); 349 | return $list; 350 | } 351 | 352 | /** 353 | * Get the log for the given PM2 process under the given user 354 | */ 355 | public function get_pm2_log( $pm2_id ) { 356 | $username = $_SESSION["user"]; 357 | if ($_SESSION["look"] != "") { 358 | $username = $_SESSION["look"]; 359 | } 360 | global $hcpp; 361 | $log = $hcpp->run("v-invoke-plugin nodeapp_pm2_log " . $username . ' ' . $pm2_id ); 362 | return $log; 363 | } 364 | 365 | /** 366 | * Get the installed and latest versions of nvm managed NodeJS installs. 367 | */ 368 | public function get_versions() { 369 | global $hcpp; 370 | $list = $hcpp->runuser( '', "nvm list --no-colors" ); 371 | $list = explode( "\n", $list ); 372 | $installed = []; 373 | $latest = []; 374 | $majors = []; 375 | foreach( $list as $line ) { 376 | if ( strpos( $line, 'lts/' ) !== false ) { 377 | $line = $hcpp->getRightMost( $line, ' v' ); 378 | $line = $hcpp->getLeftMost( $line, ' ' ); 379 | $major = $hcpp->getLeftMost( $line, '.' ); 380 | if ( in_array( $major, $majors ) ) { 381 | if( !in_array( $line, $latest ) ) { 382 | $latest[] = $line; 383 | } 384 | } 385 | }else{ 386 | if ( strpos( $line, '*' ) !== false ) { 387 | $line = $hcpp->getRightMost( $line, ' v' ); 388 | $line = $hcpp->getLeftMost( $line, ' ' ); 389 | if ( !in_array( $line, $installed ) ) { 390 | $installed[] = $line; 391 | $majors[] = $hcpp->getLeftMost( $line, '.' ); 392 | } 393 | } 394 | } 395 | } 396 | // sort latest 397 | usort( $latest, function( $a, $b ) { 398 | return version_compare( $a, $b ); 399 | }); 400 | $versions = []; 401 | $i = 0; 402 | foreach( $installed as $version ) { 403 | $versions[] = [ 404 | 'installed' => $version, 405 | 'latest' => $latest[$i] 406 | ]; 407 | $i++; 408 | } 409 | return $versions; 410 | } 411 | 412 | /** 413 | * Restart proxy on modified nginx config files 414 | */ 415 | public function hcpp_add_webapp_xpath( $xpath ) { 416 | global $hcpp; 417 | if ( file_exists( "/tmp/nodeapp_nginx_modified" ) ) { 418 | $hcpp->run( "v-invoke-plugin nodeapp_nginx_modified" ); 419 | } 420 | return $xpath; 421 | } 422 | 423 | /** 424 | * Process the PM2 list command request 425 | */ 426 | public function hcpp_invoke_plugin( $args ) { 427 | global $hcpp; 428 | if ( isset( $args[1] ) ) { 429 | $username = preg_replace( "/[^a-zA-Z0-9-_]+/", "", $args[1] ); // Sanitized username 430 | } 431 | switch ( $args[0] ) { 432 | case 'nodeapp_get_versions': 433 | $hcpp->log( 'nodeapp_get_versions' ); 434 | echo json_encode( $this->get_versions() ); 435 | break; 436 | case 'nodeapp_pm2_jlist': 437 | echo $hcpp->runuser( $username, 'pm2 jlist' ); 438 | break; 439 | 440 | case 'nodeapp_delete_pm2_ids': 441 | try { 442 | $pm2_ids = json_decode( $args[2], true ); 443 | }catch( Exception $e ) { 444 | $pm2_ids = []; 445 | } 446 | $cmd = ''; 447 | foreach( $pm2_ids as $id ) { 448 | $cmd .= 'pm2 delete ' . $id . '; '; 449 | } 450 | $cmd .= 'pm2 save --force'; 451 | $hcpp->runuser( $username, $cmd ); 452 | break; 453 | case 'nodeapp_stop_pm2_ids': 454 | try { 455 | $pm2_ids = json_decode( $args[2], true ); 456 | }catch( Exception $e ) { 457 | $pm2_ids = []; 458 | } 459 | $cmd = ''; 460 | foreach( $pm2_ids as $id ) { 461 | $cmd .= 'pm2 stop ' . $id . '; pm2 reset ' . $id . '; '; 462 | } 463 | $cmd .= 'pm2 save --force'; 464 | $hcpp->runuser( $username, $cmd ); 465 | 466 | // Force remove the PM2 logs 467 | $error_log_path = $hcpp->runuser( $username, 'pm2 info ' . $id . ' | grep "error log path"' ); 468 | $error_log_path = '/' . $hcpp->delLeftMost( $error_log_path, '/' ); 469 | $error_log_path = $hcpp->delRightMost( $error_log_path, '.log' ) . '.log'; 470 | $out_log_path = str_replace( '-error.log', '-out.log', $error_log_path ); 471 | $cmd = 'rm -f ' . $error_log_path . '; ' . 'rm -f ' . $out_log_path; 472 | $hcpp->runuser( $username, $cmd ); 473 | break; 474 | 475 | case 'nodeapp_restart_pm2_ids': 476 | try { 477 | $pm2_ids = json_decode( $args[2], true ); 478 | }catch( Exception $e ) { 479 | $pm2_ids = []; 480 | } 481 | 482 | // Restart via config.js filename; find by pm2_id 483 | $list = $hcpp->runuser( $username, 'pm2 jlist' ); 484 | $list = '[' . $hcpp->delLeftMost( $list, '[' ); 485 | $list = json_decode( $list, true ); 486 | $cmd = ''; 487 | foreach( $pm2_ids as $id ) { 488 | foreach( $list as $app ) { 489 | if ( $app['pm_id'] == $id ) { 490 | 491 | // Get the config.js file based on the script file 492 | $config = $hcpp->getLeftMost( $app['name'], ' | ' ); 493 | $config = $app['pm2_env']['cwd'] . '/' . $config . '.config.js'; 494 | if ( $config != '' ) { 495 | $cmd .= 'pm2 restart ' . $config . '; '; 496 | } 497 | } 498 | } 499 | } 500 | $cmd .= 'pm2 save --force'; 501 | $hcpp->runuser( $username, $cmd ); 502 | break; 503 | 504 | case 'nodeapp_pm2_log': 505 | $pm2_id = $args[2]; 506 | $pm2_id = filter_var( $pm2_id, FILTER_SANITIZE_NUMBER_INT ); 507 | echo $hcpp->runuser( $username, 'pm2 logs --lines 4096 --nostream --raw --no-color ' . $pm2_id . ' 2>&1' ); 508 | break; 509 | 510 | case 'nodeapp_nginx_modified': 511 | 512 | // Debounce allows use to queue and delay under higher loads 513 | $cmd = "nohup " . __DIR__ . "/nodeapp_debounce.sh > /dev/null 2>&1 &"; 514 | $hcpp->log( $cmd ); 515 | $hcpp->log( shell_exec( $cmd ) ); 516 | break; 517 | 518 | case 'nodeapp_debounce': 519 | if ( file_exists( "/tmp/nodeapp_nginx_modified" ) ) { 520 | $this->do_nginx_modified( true ); 521 | } 522 | break; 523 | } 524 | return $args; 525 | } 526 | 527 | public function hcpp_list_updates_xpath( $xpath ) { 528 | global $hcpp; 529 | $query = '//div[contains(@class, "units-table-row") and .//div[contains(@class, "units-table-cell") and contains(normalize-space(.), "hcpp-nodeapp")]]'; 530 | 531 | // Add the CSS to the head of the document 532 | $css = 'div.units-table-cell .sub-unit {float:left;margin:-3px 5px 0px 15px;}'; 533 | $head = $xpath->query('//head')->item(0); 534 | $style = $xpath->document->createElement('style', $css); 535 | $head->appendChild($style); 536 | 537 | // Inject list of NodeJS versions below hcpp-nodeapp in the updates list 538 | $nodes = $xpath->query($query); 539 | if ($nodes->length > 0) { 540 | 541 | // Get the list of NodeJS versions from the cache 542 | $versions = $hcpp->run( 'v-invoke-plugin nodeapp_get_versions json' ); 543 | $firstNode = $nodes->item(0); 544 | $arch = php_uname('m') == 'x86_64' ? 'amd64' : (php_uname('m') == 'aarch64' ? 'arm64' : 'unknown'); 545 | $html = ''; 546 | foreach ( $versions as $v ) { 547 | $installed = $v['installed']; 548 | $latest = $v['latest']; 549 | $major = $hcpp->getLeftMost( $installed, '.' ); 550 | if ( $installed != $latest ) { 551 | $icon = ''; 552 | $disabled = 'disabled '; 553 | $notice = '(update ' . $latest . ' available)'; 554 | }else{ 555 | $icon = ''; 556 | $disabled = ''; 557 | $notice = ''; 558 | } 559 | $html .= '
560 |
561 | Package Names: 562 |
563 | nvm-nodejs-v' . $major . ' 564 |
565 |
566 | Description: 567 | NodeJS v' . $major . ' runtime ' . $notice . ' 568 |
569 |
570 | Version: 571 | ' . $installed . ' (' . $arch . ') 572 |
573 |
574 | Status: 575 | ' . $icon . ' 576 |
577 |
'; 578 | 579 | } 580 | 581 | // Create a and insert it after the first found node 582 | $fragment = $xpath->document->createDocumentFragment(); 583 | $fragment->appendXML($html); 584 | $firstNode->parentNode->insertBefore($fragment, $firstNode->nextSibling); 585 | } else { 586 | $hcpp->log("hcpp-nodeapp was not found in updates"); 587 | } 588 | 589 | return $xpath; 590 | } 591 | 592 | /** 593 | * Modify runuser to incorporate NVM 594 | */ 595 | public function hcpp_runuser( $args ) { 596 | $cmd = $args[1]; 597 | $cmd = 'export NVM_DIR=/opt/nvm && source /opt/nvm/nvm.sh && ' . $cmd; 598 | $args[1] = $cmd; 599 | return $args; 600 | } 601 | 602 | /** 603 | * Check if system has rebooted and restart apps 604 | */ 605 | public function hcpp_rebooted() { 606 | 607 | // Wait up to 60 additional seconds for MySQL to start 608 | $i = 0; 609 | while ( $i < 60 ) { 610 | $i++; 611 | $mysql = shell_exec( 'systemctl is-active mysql' ); 612 | if ( trim( $mysql ) == 'active' ) { 613 | break; 614 | } 615 | sleep( 1 ); 616 | } 617 | 618 | // Restart all PM2 apps for all user accounts 619 | $users = scandir('/home'); 620 | global $hcpp; 621 | $cmd = ''; 622 | foreach ( $users as $user ) { 623 | // Ignore hidden files/folders and system folders 624 | if ( $user == '.' || $user == '..' || $user == 'lost+found' || $user == 'systemd' ) { 625 | continue; 626 | } 627 | 628 | // Check if the .pm2 folder exists in the user's home directory 629 | if ( is_dir( "/home/$user/.pm2" ) ) { 630 | 631 | // Restart any pm2 processes 632 | $cmd .= 'runuser -s /bin/bash -l ' . $user . ' -c "cd /home/' . $user . ' && '; 633 | $cmd .= 'export NVM_DIR=/opt/nvm && source /opt/nvm/nvm.sh && pm2 resurrect"' . "\n"; 634 | } 635 | } 636 | $cmd = $hcpp->do_action( 'nodeapp_resurrect_apps', $cmd ); 637 | if ( trim( $cmd ) != '' ) { 638 | $hcpp->log( shell_exec( $cmd ) ); 639 | } 640 | } 641 | 642 | /** 643 | * Add the PM2 process list button to the HestiaCP UI, and restart proxy on modified nginx config files 644 | */ 645 | public function hcpp_list_web_xpath( $xpath ) { 646 | 647 | // Check that user has bash shell access needed for PM2 648 | global $hcpp; 649 | $username = $_SESSION["user"]; 650 | if ($_SESSION["look"] != "") { 651 | $username = $_SESSION["look"]; 652 | } 653 | $detail = $hcpp->run( "v-list-user $username json" ); 654 | if ( isset( $detail[$username]['SHELL'] ) && $detail[$username]['SHELL'] == 'bash' ) { 655 | // Locate the 'Add Web Domain' button 656 | $addWebButton = $xpath->query( "//a[@href='/add/web/']" )->item(0); 657 | 658 | if ( $addWebButton ) { 659 | 660 | // Create a new button element 661 | $newButton = $xpath->document->createElement( 'a' ); 662 | $newButton->setAttribute( 'href', '?p=nodeapp' ); 663 | $newButton->setAttribute( 'class', 'button button-secondary' ); 664 | $newButton->setAttribute( 'title', 'NodaApps' ); 665 | 666 | // Create the icon element 667 | $icon = $xpath->document->createElement('span', '⬢'); 668 | $icon->setAttribute('style', 'font-size:x-large;color:green;margin:-2px 4px 0 0;'); 669 | 670 | // Create the text node 671 | $text = $xpath->document->createTextNode( 'NodeApps' ); 672 | 673 | // Append the icon and text to the new button 674 | $newButton->appendChild( $icon ); 675 | $newButton->appendChild( $text ); 676 | 677 | // Insert the new button next to the existing one 678 | $addWebButton->parentNode->insertBefore( $newButton, $addWebButton->nextSibling ); 679 | } 680 | } 681 | if ( file_exists( "/tmp/nodeapp_nginx_modified" ) ) { 682 | $hcpp->run( "v-invoke-plugin nodeapp_nginx_modified" ); 683 | } 684 | return $xpath; 685 | } 686 | 687 | /** 688 | * Restart the PM2 apps for the given user by ids. 689 | * 690 | * @param array $pm2_ids The list of PM2 process ids to restart 691 | * @param string $user The username to restart the PM2 processes for or the current HestiaCP user if not provided 692 | */ 693 | public function restart_pm2_ids( $pm2_ids, $user = '""' ) { 694 | if ( $user == '""' && isset( $_SESSION ) ) { 695 | $user = $_SESSION['user']; 696 | if ( $_SESSION['look'] != '' ) { 697 | $user = $_SESSION['look']; 698 | } 699 | } 700 | global $hcpp; 701 | $hcpp->log( 'nodeapp restart_pm2_ids for user: ' . $user ); 702 | $hcpp->log( $pm2_ids ); 703 | $pm2_ids = escapeshellarg( json_encode( $pm2_ids ) ); 704 | $hcpp->run("v-invoke-plugin nodeapp_restart_pm2_ids " . $user . ' ' . $pm2_ids ); 705 | } 706 | 707 | /** 708 | * Scan the nodeapp folder for .config.js files and start the app for each 709 | */ 710 | public function startup_apps( $nodeapp_folder, $inc_root = true ) { 711 | global $hcpp; 712 | $parse = explode( '/', $nodeapp_folder ); 713 | $user = $parse[2]; 714 | $domain = $parse[4]; 715 | $files = $this->get_config_files( $nodeapp_folder ); 716 | $cmd = 'cd "' . $nodeapp_folder . '" '; 717 | foreach($files as $file) { 718 | 719 | // Skip the root app if inc_root is false 720 | if ( $inc_root == false ) { 721 | $subfolder = str_replace( "$nodeapp_folder/", '', $file ); 722 | if ( strpos( $subfolder, '/' ) == false) continue; 723 | } 724 | 725 | // Add app to startup 726 | $cmd .= "; pm2 start $file "; 727 | } 728 | 729 | 730 | if ( strpos( $cmd, '; pm2 start ' ) ) { 731 | $cmd .= '; pm2 save --force '; 732 | $args = [ 733 | 'user' => $user, 734 | 'domain' => $domain, 735 | 'cmd' => $cmd 736 | ]; 737 | 738 | // Run the command to start all the apps 739 | $args = $hcpp->do_action( 'nodeapp_startup_services', $args ); 740 | $hcpp->runuser( $user, $args['cmd'] ); 741 | } 742 | } 743 | 744 | /** 745 | * Stop the PM2 apps for the given user by ids. 746 | * 747 | * @param array $pm2_ids The list of PM2 process ids to stop 748 | * @param string $user The username to stop the PM2 processes for or the current HestiaCP user if not provided 749 | */ 750 | public function stop_pm2_ids( $pm2_ids, $user = '""' ) { 751 | if ( $user == '""' && isset( $_SESSION ) ) { 752 | $user = $_SESSION['user']; 753 | if ( $_SESSION['look'] != '' ) { 754 | $user = $_SESSION['look']; 755 | } 756 | } 757 | global $hcpp; 758 | $hcpp->log( 'nodeapp stop_pm2_ids for user: ' . $user ); 759 | $hcpp->log( $pm2_ids ); 760 | $pm2_ids = escapeshellarg( json_encode( $pm2_ids ) ); 761 | $hcpp->run("v-invoke-plugin nodeapp_stop_pm2_ids " . $user . ' ' . $pm2_ids ); 762 | } 763 | 764 | /** 765 | * Gather list of all running apps to delete and construct shutdown command, 766 | * instead of pm2 delete all; delete each one individually as filters may 767 | * alter the behavior to keep user and select domain apps running. 768 | */ 769 | public function shutdown_apps( $nodeapp_folder ) { 770 | global $hcpp; 771 | $parse = explode( '/', $nodeapp_folder ); 772 | $user = $parse[2]; 773 | $domain = $parse[4]; 774 | 775 | // Get list of apps to delete 776 | $cmd = 'pm2 ls | grep "' . $domain . '"'; 777 | $lines = $hcpp->runuser( $user, $cmd ); 778 | $lines = explode( "\n", $lines ); 779 | $cmd = 'cd "' . $nodeapp_folder . '" '; 780 | foreach( $lines as $l ) { 781 | if ( strpos( $l, '-' . $domain ) === false ) continue; 782 | $app = $hcpp->getRightMost( $hcpp->getLeftMost( $l, '-' ), ' ' ); 783 | $app = $app . '-' . $domain; 784 | 785 | // Add app to shutdown by name 786 | $cmd .= "; pm2 delete $app "; 787 | } 788 | if ( strpos( $cmd, '; pm2 delete ' ) ) { 789 | $cmd .= '; pm2 save --force '; 790 | $args = [ 791 | 'user' => $user, 792 | 'domain' => $domain, 793 | 'cmd' => $cmd 794 | ]; 795 | 796 | // Run the command to shutdown all the apps 797 | $args = $hcpp->do_action( 'nodeapp_shutdown_services', $args ); 798 | $hcpp->runuser( $user, $args['cmd'] ); 799 | } 800 | } 801 | 802 | /** 803 | * Update all NVM managed NodeJS versions and global packages; 804 | * gracefully stop all running PM2 apps using the major version, 805 | * update NodeJS, and restart the stopped apps for each user. 806 | */ 807 | public function update_all() { 808 | 809 | // Get list of new versions 810 | global $hcpp; 811 | $versions = $this->get_versions(); 812 | $updates = []; 813 | foreach( $versions as $v ) { 814 | 815 | // Find any nodejs versions that need to be updated 816 | if ( $v['installed'] != $v['latest'] ) { 817 | $updates[] = $v; 818 | $majors[] = $hcpp->getLeftMost( $v['installed'], '.' ); 819 | } 820 | } 821 | 822 | // Perform maintenance only if updates are available 823 | if ( count( $updates ) == 0 ) { 824 | return; 825 | } 826 | 827 | // Perform the maintenance tasks 828 | $this->do_maintenance( function( $stopped ) use ( $hcpp, $updates ) { 829 | // Update NodeJS, npm, and re-install global packages 830 | foreach( $updates as $v ) { 831 | $cmd = 'nvm install ' . $v['latest'] . ' && nvm use ' . $v['latest'] . ' && npm install -g npm'; 832 | $cmd .= ' && nvm reinstall-packages ' . $v['installed']; 833 | $cmd .= ' && nvm uninstall ' . $v['installed']; 834 | $cmd = $hcpp->do_action( 'nodeapp_update_nodejs', $cmd ); 835 | $hcpp->runuser( '', $cmd ); 836 | } 837 | }, $majors ); 838 | } 839 | 840 | /** 841 | * Update the nginx config files for the given user and domain 842 | */ 843 | public function update_nginx_files( $args ) { 844 | global $hcpp; 845 | $user = $args[0]; 846 | $domain = $args[1]; 847 | $nodeapp_folder = "/home/$user/web/$domain/nodeapp"; 848 | if ( is_dir( $nodeapp_folder) ) { 849 | $this->generate_nginx_files( $nodeapp_folder, true ); 850 | } 851 | } 852 | 853 | /** 854 | * On proxy template change, copy basic nodeapp, allocate ports, and start apps 855 | */ 856 | public function v_change_web_domain_proxy_tpl( $args ) { 857 | global $hcpp; 858 | $user = $args[0]; 859 | $domain = $args[1]; 860 | $proxy = $args[2]; 861 | $nodeapp_folder = "/home/$user/web/$domain/nodeapp"; 862 | 863 | if ( !is_dir( $nodeapp_folder) && $proxy == 'NodeApp' ) { 864 | 865 | // Copy initial nodeapp folder 866 | $hcpp->copy_folder( __DIR__ . '/nodeapp', $nodeapp_folder, $user ); 867 | $args = [ 868 | 'user' => $user, 869 | 'domain' => $domain, 870 | 'proxy' => $proxy, 871 | 'nodeapp_folder' => $nodeapp_folder 872 | ]; 873 | $args = $hcpp->do_action( 'nodeapp_copy_files', $args ); 874 | $nodeapp_folder = $args['nodeapp_folder']; 875 | chmod( $nodeapp_folder, 0755 ); 876 | 877 | // Install dependencies 878 | $cmd = 'cd "' . $nodeapp_folder . '" && npm install'; 879 | $args['cmd'] = $cmd; 880 | $args = $hcpp->do_action( 'nodeapp_install_dependencies', $args ); 881 | $hcpp->runuser( $user, $args['cmd'] ); 882 | } 883 | 884 | // Shutdown stray apps and startup root and/or subfolder apps 885 | $this->shutdown_apps( $nodeapp_folder ); 886 | $this->allocate_ports( $nodeapp_folder ); 887 | $this->generate_nginx_files( $nodeapp_folder, ($proxy == 'NodeApp') ); 888 | $this->startup_apps( $nodeapp_folder, ($proxy == 'NodeApp') ); 889 | } 890 | 891 | /** 892 | * On domain delete, shutdown apps 893 | */ 894 | public function v_delete_web_domain_backend( $args ) { 895 | global $hcpp; 896 | $user = $args[0]; 897 | $domain = $args[1]; 898 | $nodeapp_folder = "/home/$user/web/$domain/nodeapp"; 899 | $this->shutdown_apps( $nodeapp_folder ); 900 | unlink( "/usr/local/hestia/data/hcpp/ports/$user/$domain.ports" ); 901 | } 902 | 903 | /** 904 | * Rebuild the nginx config files for the given user and domain 905 | */ 906 | public function v_rebuild_web_domain( $args ) { 907 | global $hcpp; 908 | $user = $args[0]; 909 | $domain = $args[1]; 910 | $nodeapp_folder = "/home/$user/web/$domain/nodeapp"; 911 | if ( is_dir( $nodeapp_folder) ) { 912 | $this->generate_nginx_files( $nodeapp_folder, true ); 913 | } 914 | return $args; 915 | } 916 | 917 | /** 918 | * Notify of any changes to the nginx config files 919 | */ 920 | public function v_restart_proxy( $args ) { 921 | if ( file_exists( '/tmp/nodeapp_nginx_modified' ) ) { 922 | $this->do_nginx_modified( false ); 923 | } 924 | return $args; 925 | } 926 | 927 | /** 928 | * On domain suspend, shutdown apps 929 | */ 930 | public function v_suspend_web_domain( $args ) { 931 | global $hcpp; 932 | $user = $args[0]; 933 | $domain = $args[1]; 934 | $nodeapp_folder = "/home/$user/web/$domain/nodeapp"; 935 | 936 | // Remove prior nginx config files; duplicate location "/" will cause nginx to fail 937 | if ( file_exists( "/home/$user/conf/web/$domain/nginx.ssl.conf_nodeapp" ) ) { 938 | unlink( "/home/$user/conf/web/$domain/nginx.ssl.conf_nodeapp" ); 939 | } 940 | if ( file_exists( "/home/$user/conf/web/$domain/nginx.conf_nodeapp" ) ) { 941 | unlink( "/home/$user/conf/web/$domain/nginx.conf_nodeapp" ); 942 | } 943 | $this->shutdown_apps( $nodeapp_folder ); 944 | return $args; 945 | } 946 | 947 | /** 948 | * On domain unsuspend, startup apps 949 | */ 950 | public function v_unsuspend_domain( $args ) { 951 | global $hcpp; 952 | $user = $args[0]; 953 | $domain = $args[1]; 954 | $nodeapp_folder = "/home/$user/web/$domain/nodeapp"; 955 | if ( is_dir( $nodeapp_folder) ) { 956 | $proxy = $hcpp->run("v-list-web-domain $user $domain json"); 957 | if ( $proxy != NULL ) { 958 | $proxy = $proxy[$domain]["PROXY"]; 959 | $this->allocate_ports( $nodeapp_folder ); 960 | $this->generate_nginx_files( $nodeapp_folder, ( $proxy == "NodeApp" ) ); 961 | $this->startup_apps( $nodeapp_folder, ( $proxy == "NodeApp" ) ); 962 | } 963 | } 964 | return $args; 965 | } 966 | 967 | /** 968 | * Check daily to update our NVM managed and installed NodeJS versions global packages. 969 | */ 970 | public function v_update_sys_queue( $args ) { 971 | global $hcpp; 972 | if ( ! (isset( $args[0] ) && trim( $args[0] ) == 'daily') ) return $args; 973 | if ( strpos( $hcpp->run('v-list-sys-hestia-autoupdate'), 'Enabled') == false ) return $args; 974 | $this->update_all(); 975 | $hcpp->do_action( 'nodeapp_autoupdate' ); 976 | return $args; 977 | } 978 | } 979 | global $hcpp; 980 | $hcpp->register_plugin( NodeApp::class ); 981 | } -------------------------------------------------------------------------------- /nodeapp/.nvmrc: -------------------------------------------------------------------------------- 1 | v22 -------------------------------------------------------------------------------- /nodeapp/.restart/restart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtuosoft-dev/hcpp-nodeapp/8f2ec34b16be83a5291d653d30df2e9dbba2cc81/nodeapp/.restart/restart -------------------------------------------------------------------------------- /nodeapp/README.md: -------------------------------------------------------------------------------- 1 | # Hello world! 2 | This is a basic NodeJS web server application, Hello world example from 3 | https://expressjs.com/en/starter/hello-world.html. See the source code in `app.js` for details. 4 | 5 | The application is managed under [PM2 (Process Manager 2)](https://pm2.keymetrics.io). You can run or stop running this application using the following commands from the nodeapp folder: 6 | 7 | ``` 8 | pm2 start app.config.js 9 | ``` 10 | and 11 | ``` 12 | pm2 delete app.config.js 13 | ``` 14 | 15 | PM2 features an auto-restart mechanism that you can activate by simply changing a file in the .restart subfolder. For example, you can restart the app.js application with: 16 | 17 | ``` 18 | touch .restart/restart 19 | ``` 20 | 21 | You can change the version of the NodeJS runtime engine by supplying a complete or partial version number in the file `.nvmrc` (i.e. "v18" or "current" for the latest NodeJS version). Supported NodeJS versions are: 22 | 23 | ``` 24 | v16 25 | v18 26 | v20 27 | v22 28 | ``` 29 | 30 | ## Create Project 31 | You can create your own project by simply renaming the app.js and app.config.js file; change 'app' to your own project. Don't forget to update the package.json's `main` property from 'app' to your own project's name. 32 | -------------------------------------------------------------------------------- /nodeapp/app.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Get compatible PM2 app config object with automatic support for .nvmrc, 3 | * port allocation, and debug mode. 4 | */ 5 | module.exports = { 6 | apps: (function() { 7 | let nodeapp = require('/usr/local/hestia/plugins/nodeapp/nodeapp.js')(__filename); 8 | return [nodeapp]; 9 | })() 10 | } 11 | -------------------------------------------------------------------------------- /nodeapp/app.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A simple Hello World! Node.js application that listens 3 | * on the port number specified in the command line. 4 | */ 5 | 6 | const express = require('express') 7 | const app = express() 8 | 9 | // Get the port number from the command line's -p argument 10 | let argv = require('minimist')(process.argv.slice(2)); 11 | let port = argv.p || 0; 12 | if (port == 0) { 13 | console.log("Port number is not specified"); 14 | process.exit(1); 15 | } 16 | 17 | app.get('*', (req, res) => { 18 | res.send('Hello World!'); 19 | }); 20 | 21 | app.listen(port, () => { 22 | console.log(`Example app listening on port ${port}`); 23 | }); 24 | -------------------------------------------------------------------------------- /nodeapp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "app", 3 | "version": "1.0.0", 4 | "description": "Hello world example Express app.", 5 | "main": "app.js", 6 | "author": "", 7 | "license": "ISC", 8 | "dependencies": { 9 | "express": "^4.18.2", 10 | "minimist": "^1.2.7" 11 | } 12 | } -------------------------------------------------------------------------------- /nodeapp_debounce.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | LOCKFILE="/tmp/nodeapp_debounce.lock" 3 | TIMEOUT=5 4 | 5 | # Check if lockfile exists 6 | if [ -e "$LOCKFILE" ]; then 7 | touch "$LOCKFILE" # Update lockfile timestamp 8 | exit 1 9 | fi 10 | 11 | # Create lockfile 12 | touch "$LOCKFILE" 13 | 14 | # Ensure lockfile is removed on script exit 15 | trap 'rm -f "$LOCKFILE"' EXIT 16 | 17 | # Wait until the lockfile is $TIMEOUT seconds old 18 | while [ $(( $(date +%s) - $(stat -c %Y "$LOCKFILE") )) -lt $TIMEOUT ]; do 19 | sleep 1 20 | done 21 | 22 | # Your script logic goes here 23 | /usr/local/hestia/bin/v-invoke-plugin nodeapp_debounce 24 | 25 | # Lockfile will be removed automatically due to trap 26 | exit 0 27 | 28 | -------------------------------------------------------------------------------- /pages/nodeapp.php: -------------------------------------------------------------------------------- 1 | log( $_REQUEST ); 3 | 4 | // Handle actions 5 | if ( isset( $_REQUEST['action'] ) ) { 6 | $action = $_REQUEST['action']; 7 | if ( isset($_REQUEST['pm2_id']) ) { 8 | $pm2_ids = [$_REQUEST['pm2_id']]; 9 | } elseif ( isset($_REQUEST['pm2_ids']) ) { 10 | $pm2_ids = $_REQUEST['pm2_ids']; 11 | } else { 12 | $pm2_ids = []; 13 | } 14 | if ( $action == 'start' || $action == 'restart' ) { 15 | $hcpp->nodeapp->restart_pm2_ids( $pm2_ids ); 16 | }elseif ( $action == 'stop' ) { 17 | $hcpp->nodeapp->stop_pm2_ids( $pm2_ids ); 18 | } 19 | } 20 | ?> 21 | 22 |
23 |
24 | 32 |
33 |
34 | 39 | 42 |
43 |
44 |
45 |
46 | 47 |
48 |
49 |
50 |
51 | 52 |
53 |
Name | Domain
54 |
55 |
NodeJS
56 |
Restarts
57 |
Uptime
58 |
CPU
59 |
Memory
60 |
61 | 62 | nodeapp->get_pm2_list(); 65 | $i = 0; 66 | $removed_apps = ''; 67 | $removed_ids = []; 68 | foreach( $list as $app ){ 69 | $hcpp->log( $app ); 70 | $pm_exec_path = $app['pm2_env']['pm_exec_path']; 71 | $name = $app['name']; 72 | $pm2_id = $app['pm_id']; 73 | if ( !file_exists( $pm_exec_path) ) { 74 | $removed_apps .= "

$name was removed; missing $pm_exec_path.

"; 75 | $removed_ids[] = $pm2_id; 76 | $hcpp->log("$name was removed; missing $pm_exec_path."); 77 | continue; 78 | } 79 | $i++; 80 | $restarts = $app['pm2_env']['restart_time']; 81 | $version = 'v' . $app['pm2_env']['node_version']; 82 | 83 | // Calculate uptime 84 | $pm_uptime = $app['pm2_env']['pm_uptime']; 85 | $uptime_seconds = (time() * 1000 - $pm_uptime) / 1000; 86 | $days = floor($uptime_seconds / (24 * 3600)); 87 | $uptime_seconds %= (24 * 3600); 88 | $hours = floor($uptime_seconds / 3600); 89 | $uptime_seconds %= 3600; 90 | $minutes = floor($uptime_seconds / 60); 91 | if ( $days > 0 ) { 92 | $uptime = $days . ' days'; 93 | } else if ( $hours > 0 ) { 94 | $uptime = $hours . ' hours'; 95 | } else { 96 | $uptime = $minutes . ' minutes'; 97 | } 98 | $status = $app['pm2_env']['status']; 99 | if ( $status == 'online' ) { 100 | $status_class = 'fas fa-circle-check icon-green u-mr5'; 101 | } else { 102 | $status_class = 'fas fa-circle-minus icon-red u-mr5'; 103 | $uptime = $status; 104 | } 105 | 106 | // Calculate memory and cpu 107 | $memory = round($app['monit']['memory'] / (1024 * 1024), 1) . ' MB'; 108 | $cpu = round($app['monit']['cpu'], 1); 109 | ?> 110 | 111 |
112 |
113 |
114 | 115 | 116 |
117 |
118 |
119 | Name: 120 | 121 | 122 | 123 | 124 |
125 |
126 | 155 |
156 |
157 | NodeJS Runtime: 158 | 159 |
160 |
161 | Restarts: 162 | 163 |
164 |
165 | Uptime: 166 | 167 |
168 |
169 | CPU: 170 | % 171 |
172 |
173 | Memory: 174 | 175 |
176 |
177 | 180 |
181 | nodeapp->delete_pm2_ids( $removed_ids ); 184 | ?> 185 |
186 | 193 | 196 | 201 |
202 | -------------------------------------------------------------------------------- /pages/nodeapplog.php: -------------------------------------------------------------------------------- 1 | 2 |
3 | 13 |
14 | 15 |
16 | 22 |
23 | 30 | -------------------------------------------------------------------------------- /plugin.php: -------------------------------------------------------------------------------- 1 | register_install_script( dirname(__FILE__) . '/install' ); 15 | $hcpp->register_uninstall_script( dirname(__FILE__) . '/uninstall' ); 16 | -------------------------------------------------------------------------------- /uninstall: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Remove NodeJS, NVM, PM2, and grunt 4 | rm -rf /opt/nvm 5 | 6 | # Update global bash.bashrc 7 | sed '/^# begin hcpp-nodeapp$/,/^# end hcpp-nodeapp$/d' /etc/bash.bashrc > temp.txt && mv temp.txt /etc/bash.bashrc 8 | 9 | ############################################ 10 | # Uninstall templates 11 | ############################################ 12 | rm -f /usr/local/hestia/data/templates/web/nginx/NodeApp.tpl 13 | rm -f /usr/local/hestia/data/templates/web/nginx/NodeApp.stpl 14 | --------------------------------------------------------------------------------