├── .gitignore ├── .travis.yml ├── CMakeLists.txt ├── LICENSE ├── README.md ├── TODO.md ├── cmake ├── FindBison.cmake └── FindFlex.cmake ├── conf └── bitzer.conf ├── config.h.cmake └── src ├── CMakeLists.txt ├── alloc.c ├── alloc.h ├── bitzer.h ├── conf.c ├── conf.h ├── conf_gram.y ├── conf_scan.l ├── context.c ├── context.h ├── list.h ├── log.c ├── log.h ├── main.c ├── rbtree.c ├── rbtree.h ├── sighandler.c ├── sighandler.h ├── strutil.c ├── strutil.h ├── task.c ├── task.h └── util.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Object files 2 | *.o 3 | *.ko 4 | *.obj 5 | *.elf 6 | 7 | # Libraries 8 | *.lib 9 | *.a 10 | 11 | # Shared objects (inc. Windows DLLs) 12 | *.dll 13 | *.so 14 | *.so.* 15 | *.dylib 16 | 17 | # Executables 18 | *.exe 19 | *.out 20 | *.app 21 | *.i*86 22 | *.x86_64 23 | *.hex 24 | 25 | # CMake build directory 26 | build/ 27 | 28 | # ctags 29 | tags 30 | 31 | test 32 | test.c 33 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | 3 | compiler: 4 | - gcc 5 | - clang 6 | 7 | env: 8 | global: 9 | - LINUX_DIST=bionic 10 | 11 | before_install: 12 | - sudo apt-get update -qq 13 | - sudo apt-get install -qq cmake 14 | 15 | before_script: 16 | - mkdir build 17 | - cd build 18 | - cmake .. 19 | 20 | script: 21 | - make 22 | - cp -r ../conf . && mkdir log 23 | - ./bitzer -p . -t 24 | 25 | notifications: 26 | email: 27 | - idealities@gmail.com 28 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2015 Shang Yuanchun 2 | 3 | project(bitzer) 4 | 5 | cmake_minimum_required(VERSION 2.6) 6 | 7 | message(STATUS "Running cmake version ${CMAKE_VERSION}") 8 | 9 | set(BITZER_VERSION "0.0.1") 10 | set(CMAKE_COLOR_MAKEFILE ON) 11 | set(CMAKE_VERBOSE_MAKEFILE OFF) 12 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}) 13 | 14 | list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake") 15 | 16 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall") 17 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") 18 | 19 | # whether bz_log_debug() is available 20 | if (CMAKE_BUILD_TYPE) 21 | string(TOUPPER ${CMAKE_BUILD_TYPE} BUILD_TYPE) 22 | endif (CMAKE_BUILD_TYPE) 23 | if (BUILD_TYPE STREQUAL "DEBUG" OR DEBUG_LOG) 24 | set(BZ_DEBUG_LOG TRUE) 25 | endif (BUILD_TYPE STREQUAL "DEBUG" OR DEBUG_LOG) 26 | 27 | if (LOG_PATH) 28 | set(BZ_LOG_PATH TRUE) 29 | endif (LOG_PATH) 30 | if (CONF_PATH) 31 | set(BZ_CONF_PATH TRUE) 32 | endif (CONF_PATH) 33 | if (PID_PATH) 34 | set(BZ_PID_PATH TRUE) 35 | endif (PID_PATH) 36 | 37 | find_package(Flex REQUIRED) 38 | find_package(Bison REQUIRED) 39 | 40 | # check header files 41 | include(CheckIncludeFiles) 42 | 43 | # check functions 44 | include(CheckFunctionExists) 45 | check_function_exists(backtrace HAVE_BACKTRACE) 46 | check_function_exists(backtrace_symbols HAVE_BACKTRACE_SYMBOLS) 47 | check_function_exists(posix_memalign HAVE_POSIX_MEMALIGN) 48 | check_function_exists(memalign HAVE_MEMALIGN) 49 | check_function_exists(getopt_long HAVE_GETOPT_LONG) 50 | check_function_exists(getifaddrs HAVE_GETIFADDRS) 51 | check_function_exists(pselect HAVE_PSELECT) 52 | 53 | include_directories(${PROJECT_BINARY_DIR} 54 | ${PROJECT_SOURCE_DIR}/src 55 | ) 56 | 57 | set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) 58 | 59 | if (CMAKE_COMPILER_IS_GNUCC) 60 | add_definitions(-D_GNU_SOURCE) 61 | endif (CMAKE_COMPILER_IS_GNUCC) 62 | 63 | configure_file(config.h.cmake ${PROJECT_BINARY_DIR}/config.h) 64 | 65 | add_subdirectory(src) 66 | 67 | if (NOT DEFINED CONF_PATH) 68 | install(FILES ${PROJECT_SOURCE_DIR}/conf/bitzer.conf DESTINATION conf) 69 | endif (NOT DEFINED CONF_PATH) 70 | 71 | if (NOT DEFINED LOG_PATH) 72 | install(DIRECTORY DESTINATION log) 73 | endif (NOT DEFINED LOG_PATH) 74 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bitzer 2 | 3 | [![Build Status]][Travis CI] 4 | 5 | Bitzer is an application that can be used to run and manage a number of processes on UNIX-like operating systems. It's much like [supervisord](http://supervisord.org/) and [supervise](http://cr.yp.to/daemontools/supervise.html). 6 | 7 | What Bitzer do is quite simple currently. When Bitzer starts, it starts a number of processes based on your config, and then going to sleep. At sometime when one of the processes exits due to some reason, it will restart the process automatically. 8 | 9 | Authors 10 | ======= 11 | 12 | * Shang Yuanchun 13 | 14 | Installation 15 | ============ 16 | 17 | You need cmake 2.6 or higher to build Bitzer from source. Further more, you also need flex (2.5.4 or higher), and bison (2.5 or higher). 18 | 19 | ```shell 20 | mkdir build && cd build 21 | ``` 22 | 23 | ```shell 24 | cmake .. -DCMAKE_INSTALL_PREFIX=/tmp 25 | make && make install 26 | ``` 27 | 28 | In that prefix directory, there is a `bitzer.conf` under `conf` directory, the format is described as below. 29 | 30 | Configuration 31 | ============= 32 | 33 | In `bitzer.conf`, you describe the processes that need to run. Here is an example: 34 | 35 | ``` 36 | task { 37 | name siesta; 38 | path /bin/sleep; 39 | args 10; 40 | dir /tmp; 41 | } 42 | ``` 43 | 44 | `name` and `path` must be provided. `args` is the arguments passed to the process. If `dir` is specified, it will be the process's working directory. 45 | 46 | Running 47 | ======= 48 | 49 | Just run `bitzer` if its path is in PATH, or type in the absolute path of bitzer. 50 | 51 | The name 52 | ======= 53 | 54 | [`Bitzer`](http://shaunthesheep.wikia.com/wiki/Bitzer) is a sheepdog in `Shaun the Sheep`. 55 | 56 | [Build Status]: https://travis-ci.org/ideal/bitzer.svg?branch=master 57 | [Travis CI]: https://travis-ci.org/ideal/bitzer 58 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | * [ ] Option to set max start count in an interval 2 | * [ ] Fix non waited process when master exits 3 | * [ ] Whether to kill processes when master exits 4 | -------------------------------------------------------------------------------- /cmake/FindBison.cmake: -------------------------------------------------------------------------------- 1 | FIND_PROGRAM(BISON_EXECUTABLE NAMES bison bison.exe) 2 | 3 | IF(BISON_EXECUTABLE) 4 | SET(BISON_FOUND TRUE) 5 | 6 | EXECUTE_PROCESS(COMMAND ${BISON_EXECUTABLE} --version 7 | OUTPUT_VARIABLE _BISON_VERSION 8 | ) 9 | string (REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)*" BISON_VERSION "${_BISON_VERSION}") 10 | ENDIF(BISON_EXECUTABLE) 11 | 12 | IF(BISON_FOUND) 13 | IF(NOT Bison_FIND_QUIETLY) 14 | MESSAGE(STATUS "Found Bison: ${BISON_EXECUTABLE}, version: ${BISON_VERSION}") 15 | ENDIF(NOT Bison_FIND_QUIETLY) 16 | ELSE(BISON_FOUND) 17 | IF(Bison_FIND_REQUIRED) 18 | MESSAGE(FATAL_ERROR "Could not find Bison") 19 | ENDIF(Bison_FIND_REQUIRED) 20 | ENDIF(BISON_FOUND) 21 | -------------------------------------------------------------------------------- /cmake/FindFlex.cmake: -------------------------------------------------------------------------------- 1 | FIND_PROGRAM(FLEX_EXECUTABLE NAMES flex flex.exe ) 2 | 3 | IF(FLEX_EXECUTABLE) 4 | SET(FLEX_FOUND TRUE) 5 | 6 | EXECUTE_PROCESS(COMMAND ${FLEX_EXECUTABLE} --version 7 | OUTPUT_VARIABLE _FLEX_VERSION 8 | ) 9 | string (REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" FLEX_VERSION "${_FLEX_VERSION}") 10 | ENDIF(FLEX_EXECUTABLE) 11 | 12 | IF(FLEX_FOUND) 13 | IF(NOT Flex_FIND_QUIETLY) 14 | MESSAGE(STATUS "Found Flex: ${FLEX_EXECUTABLE}, version: ${FLEX_VERSION}") 15 | ENDIF(NOT Flex_FIND_QUIETLY) 16 | ELSE(FLEX_FOUND) 17 | IF(Flex_FIND_REQUIRED) 18 | MESSAGE(FATAL_ERROR "Could not find Flex") 19 | ENDIF(Flex_FIND_REQUIRED) 20 | ENDIF(FLEX_FOUND) 21 | -------------------------------------------------------------------------------- /conf/bitzer.conf: -------------------------------------------------------------------------------- 1 | # a line begins with # is comment 2 | 3 | task { 4 | # name: the task name 5 | name siesta; 6 | 7 | # path : the executable path 8 | path /bin/sleep; 9 | 10 | # path: the args passed to the process 11 | args 10; 12 | 13 | # dir: the working directory for process 14 | dir /tmp; 15 | 16 | # env: environment variables, but not used currently 17 | env PWD=/home/ideal; 18 | } 19 | 20 | task { 21 | name afternoon_tea; 22 | path /bin/sleep; 23 | args 60; 24 | dir /; 25 | env PWD=/home/ideal; 26 | } 27 | -------------------------------------------------------------------------------- /config.h.cmake: -------------------------------------------------------------------------------- 1 | #ifndef BITZER_CONFIG_H 2 | #define BITZER_CONFIG_H 3 | 4 | #define BITZER_VERSION "${BITZER_VERSION}" 5 | #define BITZER_NAME "bitzer" 6 | 7 | #define BZ_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}" 8 | #cmakedefine BZ_LOG_PATH "${LOG_PATH}" 9 | #cmakedefine BZ_CONF_PATH "${CONF_PATH}" 10 | #cmakedefine BZ_PID_PATH "${PID_PATH}" 11 | 12 | #cmakedefine BZ_DEBUG_LOG 13 | 14 | #cmakedefine HAVE_BACKTRACE 15 | #cmakedefine HAVE_BACKTRACE_SYMBOLS 16 | #cmakedefine HAVE_POSIX_MEMALIGN 17 | #cmakedefine HAVE_MEMALIGN 18 | #cmakedefine HAVE_GETOPT_LONG 19 | #cmakedefine HAVE_GETIFADDRS 20 | #cmakedefine HAVE_PSELECT 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(bitzer_SRCS 2 | main.c 3 | log.c 4 | strutil.c 5 | sighandler.c 6 | context.c 7 | rbtree.c 8 | task.c 9 | alloc.c 10 | conf.c 11 | ) 12 | 13 | add_custom_command( 14 | SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/conf_scan.l 15 | COMMAND ${FLEX_EXECUTABLE} 16 | ARGS -o${CMAKE_CURRENT_BINARY_DIR}/conf_scan.c 17 | --header-file=${CMAKE_CURRENT_BINARY_DIR}/conf_scan.h 18 | ${CMAKE_CURRENT_SOURCE_DIR}/conf_scan.l 19 | OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/conf_scan.c 20 | ) 21 | 22 | add_custom_command( 23 | SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/conf_gram.y 24 | COMMAND ${BISON_EXECUTABLE} 25 | ARGS -d -o ${CMAKE_CURRENT_BINARY_DIR}/conf_gram.c 26 | ${CMAKE_CURRENT_SOURCE_DIR}/conf_gram.y 27 | DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/conf_scan.c 28 | OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/conf_gram.c 29 | ) 30 | 31 | set(bitzer_SRCS ${bitzer_SRCS} 32 | ${CMAKE_CURRENT_BINARY_DIR}/conf_scan.c 33 | ${CMAKE_CURRENT_BINARY_DIR}/conf_gram.c 34 | ) 35 | 36 | set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/conf_scan.c GENERATED) 37 | set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/conf_gram.c GENERATED) 38 | 39 | add_executable(bitzer ${bitzer_SRCS}) 40 | 41 | add_custom_target(bitzerconf DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/conf_gram.c) 42 | 43 | add_dependencies(bitzer bitzerconf) 44 | 45 | include_directories(${CMAKE_CURRENT_BINARY_DIR}) 46 | 47 | install(TARGETS bitzer DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) 48 | 49 | -------------------------------------------------------------------------------- /src/alloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #include "alloc.h" 23 | 24 | void *bz_alloc(size_t size, bz_log_t *log) 25 | { 26 | void *p = malloc(size); 27 | 28 | if (p == NULL) { 29 | bz_log_error(log, "malloc(%zu) failed", size); 30 | } 31 | 32 | bz_log_debug(log, BZ_LOG_DEBUG, "malloc: %zu at: %p", size, p); 33 | return p; 34 | } 35 | 36 | void *bz_calloc(size_t size, bz_log_t *log) 37 | { 38 | void *p = bz_alloc(size, log); 39 | 40 | return (p != NULL ? memset(p, 0, size) : p); 41 | } 42 | 43 | -------------------------------------------------------------------------------- /src/alloc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_ALLOC_H 23 | #define BZ_ALLOC_H 24 | 25 | #include "bitzer.h" 26 | 27 | void *bz_alloc (size_t size, bz_log_t *log); 28 | void *bz_calloc(size_t size, bz_log_t *log); 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /src/bitzer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_CORE_H 23 | #define BZ_CORE_H 24 | 25 | #include "config.h" 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | 35 | #include 36 | #include 37 | 38 | #include 39 | #include 40 | #include 41 | 42 | #include 43 | 44 | #include 45 | #include 46 | #include 47 | 48 | typedef intptr_t bz_int_t; 49 | typedef uintptr_t bz_uint_t; 50 | typedef intptr_t bz_flag_t; 51 | 52 | typedef struct context_s context_t; 53 | 54 | #define BZ_OK 0 55 | #define BZ_ERROR -1 56 | #define BZ_AGAIN -2 57 | #define BZ_NOMEM -3 58 | #define BZ_ABORT -4 59 | 60 | #define OK BZ_OK 61 | #define ERROR BZ_ERROR 62 | 63 | #include "log.h" 64 | #include "util.h" 65 | #include "sighandler.h" 66 | #include "strutil.h" 67 | #include "list.h" 68 | #include "rbtree.h" 69 | #include "task.h" 70 | #include "alloc.h" 71 | #include "conf.h" 72 | 73 | #include "context.h" 74 | 75 | struct bitzer_s { 76 | int log_level; 77 | char *prefix; 78 | char *log_file; 79 | char *conf_file; 80 | pid_t pid; 81 | char *pid_file; 82 | 83 | unsigned int log_file_alloc:1; 84 | unsigned int conf_file_alloc:1; 85 | unsigned int pid_file_alloc:1; 86 | 87 | char hostname[BZ_MAXHOSTNAMELEN]; 88 | bz_log_t *log; 89 | }; 90 | 91 | #endif 92 | -------------------------------------------------------------------------------- /src/conf.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #include "bitzer.h" 23 | #include "conf_gram.h" 24 | #include "conf_scan.h" 25 | 26 | int yyparse(conf_t *cnf, yyscan_t scanner); 27 | static char *conf_mmap(const char *path, size_t *len); 28 | 29 | conf_t *conf_create(context_t *ctx) 30 | { 31 | conf_t *cnf; 32 | 33 | cnf = (conf_t *)bz_alloc(sizeof(conf_t), ctx->log); 34 | if (cnf) { 35 | cnf->ctx = ctx; 36 | // an empty tasks list 37 | INIT_LIST_HEAD(&cnf->tasks_list); 38 | } 39 | 40 | return cnf; 41 | } 42 | 43 | int conf_load(conf_t *cnf, const char *path) 44 | { 45 | int ret; 46 | size_t len; 47 | yyscan_t scanner; 48 | YY_BUFFER_STATE state; 49 | const char *confstr; 50 | 51 | if (yylex_init(&scanner) != 0) { 52 | return ERROR; 53 | } 54 | 55 | if (!(confstr = conf_mmap(path, &len))) { 56 | return ERROR; 57 | } 58 | 59 | state = yy_scan_bytes(confstr, len, scanner); 60 | ret = yyparse(cnf, scanner) == 0 ? OK : ERROR; 61 | 62 | munmap((void *)confstr, len); 63 | yy_delete_buffer(state, scanner); 64 | yylex_destroy(scanner); 65 | 66 | return ret; 67 | } 68 | 69 | int conf_close(conf_t *cnf) 70 | { 71 | if (cnf) { 72 | free(cnf); 73 | } 74 | return OK; 75 | } 76 | 77 | static char *conf_mmap(const char *path, size_t *len) 78 | { 79 | int fd; 80 | char *ptr; 81 | struct stat st; 82 | 83 | ptr = NULL; 84 | fd = open(path, O_RDONLY); 85 | if (fd < 0) { 86 | bz_log_stderr("open conf file '%s' failed: %s", path, strerror(errno)); 87 | return NULL; 88 | } 89 | if (fstat(fd, &st) < 0) { 90 | goto EXIT; 91 | } 92 | 93 | *len = st.st_size; 94 | ptr = (char *)mmap(NULL, *len, PROT_READ, MAP_PRIVATE, fd, 0); 95 | if (ptr == MAP_FAILED) { 96 | ptr = NULL; 97 | goto EXIT; 98 | } 99 | 100 | EXIT: 101 | close(fd); 102 | return ptr; 103 | } 104 | -------------------------------------------------------------------------------- /src/conf.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_CONF_H 23 | #define BZ_CONF_H 24 | 25 | #include "bitzer.h" 26 | 27 | typedef struct conf_s { 28 | context_t *ctx; 29 | struct list_head tasks_list; 30 | } conf_t; 31 | 32 | conf_t *conf_create(context_t *ctx); 33 | int conf_load(conf_t *cnf, const char *path); 34 | int conf_close(conf_t *cnf); 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /src/conf_gram.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #include "bitzer.h" 3 | #include "conf_gram.h" 4 | #include "conf_scan.h" 5 | 6 | #define CONF_DEFAULT_LEN 10 7 | 8 | static task_t *task; 9 | 10 | #define check_task() \ 11 | do { \ 12 | if (!task) { \ 13 | task = task_create(conf->ctx); \ 14 | if (task) { \ 15 | task_init(task, conf->ctx); \ 16 | } \ 17 | } \ 18 | } while(0) 19 | 20 | #define check_task_member(member, needsize, incrsize) \ 21 | do { \ 22 | if (task->member ## _len + needsize > task->member ## _total) { \ 23 | /* TODO: check if realloc failed */ \ 24 | task->member = (char **)realloc(task->member, \ 25 | (task->member ## _total + incrsize) \ 26 | * sizeof(char *)); \ 27 | task->member ## _total += incrsize; \ 28 | } \ 29 | } while(0) 30 | 31 | void yyerror(YYLTYPE *locp, conf_t *cnf, yyscan_t scanner, const char *str) 32 | { 33 | bz_log_stderr("error in you config file: %s near line: %d", str, locp->first_line); 34 | } 35 | 36 | %} 37 | 38 | %code requires { 39 | 40 | #ifndef YY_TYPEDEF_YY_SCANNER_T 41 | #define YY_TYPEDEF_YY_SCANNER_T 42 | typedef void* yyscan_t; 43 | #endif 44 | 45 | } 46 | 47 | %locations 48 | %define api.pure 49 | %lex-param { yyscan_t scanner } 50 | %parse-param { conf_t *conf } 51 | %parse-param { yyscan_t scanner } 52 | 53 | %token OPENBRACE ENDBRACE TOKENTASK TOKENNAME TOKENPATH TOKENARGS TOKENENV TOKENDIR SEMICOLON QUOTE 54 | 55 | %union 56 | { 57 | int number; 58 | char *string; 59 | } 60 | 61 | %token NUMBER 62 | %token ALNUMWORD 63 | %token ALPHAWORD 64 | %token STRING 65 | %token PATH 66 | %token ENVAR 67 | %token ARGKEY 68 | 69 | %type taskname 70 | %type arg 71 | %type innerarg 72 | 73 | %% 74 | 75 | tasks: 76 | | tasks task 77 | ; 78 | 79 | task: 80 | TOKENTASK OPENBRACE taskopts ENDBRACE 81 | { 82 | size_t i; 83 | 84 | // there must be args 85 | check_task_member(args, 2, 2); 86 | for (i = task->args_len; i > 0; i--) { 87 | task->args[i] = task->args[i - 1]; 88 | } 89 | task->args[0] = (char *)task->path; 90 | task->args_len++; 91 | task->args[task->args_len++] = NULL; 92 | 93 | // envp is optional 94 | if (task->envp) { 95 | check_task_member(envp, 1, 1); 96 | task->envp[task->envp_len++] = NULL; 97 | } 98 | 99 | list_add(&task->list, &conf->tasks_list); 100 | task = NULL; 101 | } 102 | ; 103 | 104 | taskopts: 105 | | taskopts taskopt 106 | ; 107 | 108 | taskopt: 109 | name 110 | | 111 | path 112 | | 113 | args 114 | | 115 | env 116 | | 117 | dir 118 | ; 119 | 120 | name: 121 | TOKENNAME taskname SEMICOLON 122 | { 123 | check_task(); 124 | task->name = $2; 125 | } 126 | ; 127 | 128 | taskname: 129 | STRING 130 | | 131 | ALPHAWORD 132 | | 133 | QUOTE ALPHAWORD QUOTE 134 | { 135 | $$ = $2; 136 | } 137 | ; 138 | 139 | path: 140 | TOKENPATH PATH SEMICOLON 141 | { 142 | check_task(); 143 | task->path = $2; 144 | } 145 | ; 146 | 147 | args: 148 | TOKENARGS argslist SEMICOLON 149 | ; 150 | 151 | argslist: 152 | | argslist arg 153 | { 154 | check_task(); 155 | check_task_member(args, 1, CONF_DEFAULT_LEN); 156 | task->args[task->args_len++] = $2; 157 | } 158 | ; 159 | 160 | arg: 161 | STRING 162 | | 163 | ARGKEY 164 | | 165 | ALPHAWORD 166 | | 167 | ALNUMWORD 168 | | 169 | NUMBER 170 | | 171 | QUOTE innerarg QUOTE 172 | { 173 | $$ = $2; 174 | } 175 | ; 176 | 177 | innerarg: 178 | STRING 179 | | 180 | ARGKEY 181 | | 182 | ALPHAWORD 183 | | 184 | ALNUMWORD 185 | | 186 | NUMBER 187 | ; 188 | 189 | env: 190 | TOKENENV ENVAR SEMICOLON 191 | { 192 | check_task(); 193 | check_task_member(envp, 1, CONF_DEFAULT_LEN); 194 | task->envp[task->envp_len++] = $2; 195 | } 196 | ; 197 | 198 | dir: 199 | TOKENDIR PATH SEMICOLON 200 | { 201 | check_task(); 202 | task->dir = $2; 203 | }; 204 | 205 | %% 206 | -------------------------------------------------------------------------------- /src/conf_scan.l: -------------------------------------------------------------------------------- 1 | %{ 2 | #include "bitzer.h" 3 | #include "conf_gram.h" 4 | 5 | %} 6 | 7 | %option reentrant 8 | %option noyywrap 9 | %option bison-bridge 10 | %option bison-locations 11 | 12 | number [0-9] 13 | 14 | %% 15 | 16 | \{ return OPENBRACE; 17 | \} return ENDBRACE; 18 | task return TOKENTASK; 19 | name return TOKENNAME; 20 | path return TOKENPATH; 21 | args return TOKENARGS; 22 | env return TOKENENV; 23 | dir return TOKENDIR; 24 | \" return QUOTE; 25 | \; return SEMICOLON; 26 | {number}+ yylval->string=strdup(yytext); return NUMBER; 27 | [0-9]+[_a-zA-Z-]* yylval->string=strdup(yytext); return ALNUMWORD; 28 | [a-zA-Z][\.\/_a-zA-Z0-9-]* yylval->string=strdup(yytext); return ALPHAWORD; 29 | \/[-\.+a-zA-Z0-9]*(\/[-\._+a-zA-Z0-9]*)* yylval->string=strdup(yytext); return PATH; 30 | -(-)?[^ \t\n;0-9-]+ yylval->string=strdup(yytext); return ARGKEY; 31 | [a-zA-Z][a-zA-Z0-9]*=[^;\n]+ yylval->string=strdup(yytext); return ENVAR; 32 | \n ; 33 | [ \t]+ ; 34 | ^#.*$ ; 35 | 36 | %% 37 | 38 | -------------------------------------------------------------------------------- /src/context.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #include "context.h" 23 | 24 | context_t *context; 25 | 26 | sig_atomic_t bz_quit; 27 | sig_atomic_t bz_terminate; 28 | sig_atomic_t bz_reconfigure; 29 | sig_atomic_t bz_reopen; 30 | sig_atomic_t bz_child; 31 | 32 | static int context_sigmask(context_t *ctx, sigset_t *mask); 33 | static int context_event_handler(context_t *ctx); 34 | static task_t *context_find_task(context_t *ctx, pid_t pid); 35 | static int context_start_tasks(context_t *ctx); 36 | static int context_restart_task(context_t *ctx, task_t *task); 37 | 38 | context_t *context_create(struct bitzer_s *bz) 39 | { 40 | context_t *ctx; 41 | 42 | ctx = (context_t *)bz_alloc(sizeof(context_t), bz->log); 43 | if (ctx == NULL) { 44 | bz_log_error(bz->log, "create context failed"); 45 | return NULL; 46 | } 47 | 48 | ctx->instance = bz; 49 | ctx->log = bz->log; 50 | 51 | // there is no signal callback currently 52 | ctx->signal_task.callback = NULL; 53 | ctx->signal_task.arg = NULL; 54 | 55 | ctx->conf = NULL; 56 | 57 | // an empty tasks rbtree 58 | rbtree_init(&ctx->tasks_rbtree, &ctx->sentinel); 59 | return ctx; 60 | } 61 | 62 | int context_init(context_t *ctx) 63 | { 64 | ctx->conf = conf_create(ctx); 65 | if (!ctx->conf) { 66 | return ERROR; 67 | } 68 | 69 | return conf_load(ctx->conf, ctx->instance->conf_file); 70 | } 71 | 72 | void context_set_signal_callback(context_t *ctx, signal_callback_t cb, void *arg) 73 | { 74 | ctx->signal_task.callback = cb; 75 | ctx->signal_task.arg = arg; 76 | } 77 | 78 | void context_run(context_t *ctx) 79 | { 80 | int ret; 81 | sigset_t mask; 82 | 83 | if (context_sigmask(ctx, &mask) < 0) { 84 | bz_log_error(ctx->log, "set signal mask failed: %s", strerror(errno)); 85 | return; 86 | } 87 | 88 | context_start_tasks(ctx); 89 | 90 | while (1) { 91 | ret = pselect(0, NULL, NULL, NULL, NULL, &ctx->origmask); 92 | if (ret < 0 && errno == EINTR) { 93 | context_event_handler(ctx); 94 | if (ctx->signal_task.callback) { 95 | ctx->signal_task.callback(ctx->signal_task.arg); 96 | } 97 | } else { 98 | bz_log_error(ctx->log, "unexpected return value from pselect: %d", ret); 99 | } 100 | } 101 | } 102 | 103 | // TODO: finish tasks 104 | void context_close(context_t *ctx) 105 | { 106 | struct list_head *pos; 107 | 108 | if (ctx->conf) { 109 | list_for_each(pos, &ctx->conf->tasks_list) { 110 | task_close(list_entry(pos, task_t, list)); 111 | } 112 | } 113 | 114 | conf_close(ctx->conf); 115 | free(ctx); 116 | } 117 | 118 | static int context_sigmask(context_t *ctx, sigset_t *mask) 119 | { 120 | sigemptyset(mask); 121 | sigaddset(mask, SIGCHLD); 122 | sigaddset(mask, SIGINT); 123 | sigaddset(mask, signal_value(SIGNAL_SHUTDOWN)); 124 | sigaddset(mask, signal_value(SIGNAL_TERMINATE)); 125 | sigaddset(mask, signal_value(SIGNAL_RECONFIGURE)); 126 | sigaddset(mask, signal_value(SIGNAL_REOPEN)); 127 | 128 | return sigprocmask(SIG_BLOCK, mask, &ctx->origmask); 129 | } 130 | 131 | static int context_event_handler(context_t *ctx) 132 | { 133 | int status; 134 | pid_t pid; 135 | task_t *task; 136 | 137 | if (!bz_child) { 138 | return OK; 139 | } 140 | 141 | while (1) { 142 | pid = waitpid(-1, &status, WNOHANG); 143 | if (pid == 0) { 144 | break; 145 | } else if (pid < 0) { 146 | bz_log_error(ctx->log, "error at waitpid: %s", strerror(errno)); 147 | break; 148 | } 149 | task = context_find_task(ctx, pid); 150 | if (!task) { 151 | bz_log_error(ctx->log, "process finished but no related task found, pid: %d", pid); 152 | continue; 153 | } 154 | task_exit_handler(task, status); 155 | if (context_restart_task(ctx, task) != OK) { 156 | continue; 157 | } 158 | } 159 | 160 | return OK; 161 | } 162 | 163 | static task_t *context_find_task(context_t *ctx, pid_t pid) 164 | { 165 | rbtree_key_t key; 166 | rbtree_node_t *node, *sentinel; 167 | 168 | key = pid; 169 | node = ctx->tasks_rbtree.root; 170 | sentinel = ctx->tasks_rbtree.sentinel; 171 | 172 | while (node != sentinel) { 173 | 174 | if (key < node->key) { 175 | node = node->left; 176 | continue; 177 | } 178 | 179 | if (key > node->key) { 180 | node = node->right; 181 | continue; 182 | } 183 | 184 | return rbtree_entry(node, task_t, node); 185 | } 186 | 187 | /* not found */ 188 | return NULL; 189 | } 190 | 191 | static int context_start_tasks(context_t *ctx) 192 | { 193 | task_t *task; 194 | struct list_head *pos; 195 | 196 | if (list_empty(&ctx->conf->tasks_list)) { 197 | return OK; 198 | } 199 | 200 | list_for_each(pos, &ctx->conf->tasks_list) { 201 | task = list_entry(pos, task_t, list); 202 | if (task_run(task) == OK) { 203 | // add to rbtree 204 | rbtree_insert(&ctx->tasks_rbtree, &task->node); 205 | bz_log(ctx->log, BZ_LOG_INFO, "starting task succeed, name: %s, pid: %d", task->name, task->pid); 206 | } else { 207 | bz_log_error(ctx->log, "starting task failed, name: %s", task->name); 208 | } 209 | } 210 | return OK; 211 | } 212 | 213 | static int context_restart_task(context_t *ctx, task_t *task) 214 | { 215 | // first remove from rbtree 216 | rbtree_delete(&ctx->tasks_rbtree, &task->node); 217 | 218 | if (task_run(task) == OK) { 219 | // add to rbtree again 220 | rbtree_insert(&ctx->tasks_rbtree, &task->node); 221 | bz_log(ctx->log, BZ_LOG_INFO, "restarting task succeed, name: %s, pid: %d", task->name, task->pid); 222 | return OK; 223 | } 224 | 225 | bz_log_error(ctx->log, "restarting task failed, name: %s", task->name); 226 | return ERROR; 227 | } 228 | -------------------------------------------------------------------------------- /src/context.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_CONTEXT_H 23 | #define BZ_CONTEXT_H 24 | 25 | #include "bitzer.h" 26 | 27 | typedef void (*signal_callback_t)(void *arg); 28 | 29 | typedef struct signal_task_s { 30 | signal_callback_t callback; 31 | void *arg; 32 | } signal_task_t; 33 | 34 | struct context_s { 35 | conf_t *conf; 36 | struct bitzer_s *instance; 37 | bz_log_t *log; 38 | signal_task_t signal_task; 39 | sigset_t origmask; 40 | rbtree_t tasks_rbtree; 41 | rbtree_node_t sentinel; 42 | }; 43 | 44 | extern context_t *context; 45 | 46 | extern sig_atomic_t bz_quit; 47 | extern sig_atomic_t bz_terminate; 48 | extern sig_atomic_t bz_reconfigure; 49 | extern sig_atomic_t bz_reopen; 50 | extern sig_atomic_t bz_child; 51 | 52 | context_t *context_create(struct bitzer_s *bz); 53 | int context_init(context_t *ctx); 54 | void context_run(context_t *ctx); 55 | void context_set_signal_callback(context_t *ctx, signal_callback_t cb, void *arg); 56 | void context_close(context_t *ctx); 57 | 58 | #endif 59 | -------------------------------------------------------------------------------- /src/list.h: -------------------------------------------------------------------------------- 1 | #ifndef _LINUX_LIST_H 2 | #define _LINUX_LIST_H 3 | 4 | /* 5 | * Simple doubly linked list implementation. 6 | * 7 | * Some of the internal functions ("__xxx") are useful when 8 | * manipulating whole lists rather than single entries, as 9 | * sometimes we already know the next/prev entries and we can 10 | * generate better code by using them directly rather than 11 | * using the generic single-entry routines. 12 | */ 13 | 14 | struct list_head { 15 | struct list_head *next, *prev; 16 | }; 17 | 18 | #define LIST_HEAD_INIT(name) { &(name), &(name) } 19 | 20 | #define LIST_HEAD(name) \ 21 | struct list_head name = LIST_HEAD_INIT(name) 22 | 23 | #define INIT_LIST_HEAD(ptr) do { \ 24 | (ptr)->next = (ptr); (ptr)->prev = (ptr); \ 25 | } while (0) 26 | 27 | /* 28 | * Insert a new entry between two known consecutive entries. 29 | * 30 | * This is only for internal list manipulation where we know 31 | * the prev/next entries already! 32 | */ 33 | static __inline__ void __list_add(struct list_head * _new, 34 | struct list_head * prev, 35 | struct list_head * next) 36 | { 37 | next->prev = _new; 38 | _new->next = next; 39 | _new->prev = prev; 40 | prev->next = _new; 41 | } 42 | 43 | /** 44 | * list_add - add a new entry 45 | * @new: new entry to be added 46 | * @head: list head to add it after 47 | * 48 | * Insert a new entry after the specified head. 49 | * This is good for implementing stacks. 50 | */ 51 | static __inline__ void list_add(struct list_head *_new, struct list_head *head) 52 | { 53 | __list_add(_new, head, head->next); 54 | } 55 | 56 | /** 57 | * list_add_tail - add a new entry 58 | * @new: new entry to be added 59 | * @head: list head to add it before 60 | * 61 | * Insert a new entry before the specified head. 62 | * This is useful for implementing queues. 63 | */ 64 | static __inline__ void list_add_tail(struct list_head *_new, struct list_head *head) 65 | { 66 | __list_add(_new, head->prev, head); 67 | } 68 | 69 | /* 70 | * Delete a list entry by making the prev/next entries 71 | * point to each other. 72 | * 73 | * This is only for internal list manipulation where we know 74 | * the prev/next entries already! 75 | */ 76 | static __inline__ void __list_del(struct list_head * prev, 77 | struct list_head * next) 78 | { 79 | next->prev = prev; 80 | prev->next = next; 81 | } 82 | 83 | /** 84 | * list_del - deletes entry from list. 85 | * @entry: the element to delete from the list. 86 | * Note: list_empty on entry does not return true after this, the entry is in an undefined state. 87 | */ 88 | static __inline__ void list_del(struct list_head *entry) 89 | { 90 | __list_del(entry->prev, entry->next); 91 | } 92 | 93 | /** 94 | * list_del_init - deletes entry from list and reinitialize it. 95 | * @entry: the element to delete from the list. 96 | */ 97 | static __inline__ void list_del_init(struct list_head *entry) 98 | { 99 | __list_del(entry->prev, entry->next); 100 | INIT_LIST_HEAD(entry); 101 | } 102 | 103 | /** 104 | * list_empty - tests whether a list is empty 105 | * @head: the list to test. 106 | */ 107 | static __inline__ int list_empty(struct list_head *head) 108 | { 109 | return head->next == head; 110 | } 111 | 112 | /** 113 | * list_splice - join two lists 114 | * @list: the new list to add. 115 | * @head: the place to add it in the first list. 116 | */ 117 | static __inline__ void list_splice(struct list_head *list, struct list_head *head) 118 | { 119 | struct list_head *first = list->next; 120 | 121 | if (first != list) { 122 | struct list_head *last = list->prev; 123 | struct list_head *at = head->next; 124 | 125 | first->prev = head; 126 | head->next = first; 127 | 128 | last->next = at; 129 | at->prev = last; 130 | } 131 | } 132 | 133 | /** 134 | * list_entry - get the struct for this entry 135 | * @ptr: the &struct list_head pointer. 136 | * @type: the type of the struct this is embedded in. 137 | * @member: the name of the list_struct within the struct. 138 | */ 139 | #define list_entry(ptr, type, member) \ 140 | ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) 141 | 142 | /** 143 | * list_first_entry - get the first element from a list 144 | * @ptr: the list head to take the element from. 145 | * @type: the type of the struct this is embedded in. 146 | * @member: the name of the list_head within the struct. 147 | * 148 | * Note, that list is expected to be not empty. 149 | */ 150 | #define list_first_entry(ptr, type, member) \ 151 | list_entry((ptr)->next, type, member) 152 | 153 | /** 154 | * list_last_entry - get the last element from a list 155 | * @ptr: the list head to take the element from. 156 | * @type: the type of the struct this is embedded in. 157 | * @member: the name of the list_head within the struct. 158 | * 159 | * Note, that list is expected to be not empty. 160 | */ 161 | #define list_last_entry(ptr, type, member) \ 162 | list_entry((ptr)->prev, type, member) 163 | 164 | /** 165 | * list_first_entry_or_null - get the first element from a list 166 | * @ptr: the list head to take the element from. 167 | * @type: the type of the struct this is embedded in. 168 | * @member: the name of the list_head within the struct. 169 | * 170 | * Note that if the list is empty, it returns NULL. 171 | */ 172 | #define list_first_entry_or_null(ptr, type, member) \ 173 | (!list_empty(ptr) ? list_first_entry(ptr, type, member) : NULL) 174 | 175 | /** 176 | * list_for_each - iterate over a list 177 | * @pos: the &struct list_head to use as a loop counter. 178 | * @head: the head for your list. 179 | */ 180 | #define list_for_each(pos, head) \ 181 | for (pos = (head)->next; pos != (head); pos = pos->next) 182 | 183 | /** 184 | * list_for_each_safe - iterate over a list safe against removal of list entry 185 | * @pos: the &struct list_head to use as a loop counter. 186 | * @n: another &struct list_head to use as temporary storage 187 | * @head: the head for your list 188 | */ 189 | #define list_for_each_safe(pos, n, head) \ 190 | for (pos = (head)->next, n = pos->next; pos != (head); \ 191 | pos = n, n = pos->next) 192 | 193 | #endif 194 | -------------------------------------------------------------------------------- /src/log.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #include 30 | #include 31 | #include 32 | 33 | #include "log.h" 34 | #include "strutil.h" 35 | 36 | #if defined(HAVE_BACKTRACE) && defined(HAVE_BACKTRACE_SYMBOLS) 37 | # include 38 | #endif 39 | 40 | static const char *loglevel_desc[] = { 41 | "emerge", 42 | "alert", 43 | "critical", 44 | "error", 45 | "warning", 46 | "notice", 47 | "info", 48 | "debug", 49 | "verb", 50 | }; 51 | 52 | #define BZ_LOG_MAX_LEVEL BZ_LOG_VERB 53 | #define MAX_LEVEL_DESC_LEN (sizeof("critical") - 1) 54 | 55 | static inline const char *bz_basename(const char *path) 56 | { 57 | const char *ptr = strrchr(path, '/'); 58 | 59 | return (ptr ? ptr + 1 : path); 60 | } 61 | 62 | bz_log_t *bz_log_create(int level, const char *filename) 63 | { 64 | bz_log_t *log = (bz_log_t *)malloc(sizeof(bz_log_t)); 65 | if (log == NULL) { 66 | return NULL; 67 | } 68 | 69 | log->log_level = min(BZ_LOG_VERB, max(BZ_LOG_EMERG, level)); 70 | log->file = (char *)filename; 71 | log->nerr = 0; 72 | if (!filename || !strlen(filename)) { 73 | log->fd = STDERR_FILENO; 74 | return log; 75 | } 76 | 77 | log->fd = open(filename, O_WRONLY | O_APPEND | O_CREAT, 0644); 78 | if (log->fd < 0) { 79 | bz_log_stderr("open log file '%s' failed: %s", filename, 80 | strerror(errno)); 81 | free(log); 82 | return NULL; 83 | } 84 | return log; 85 | } 86 | 87 | void bz_log_close(bz_log_t *log) 88 | { 89 | if (!log) { 90 | return; 91 | } 92 | 93 | if (log->fd > 0 && log->fd != STDERR_FILENO) { 94 | close(log->fd); 95 | } 96 | 97 | free(log); 98 | } 99 | 100 | void bz_log_reopen(bz_log_t *log) 101 | { 102 | if (!log || log->fd == STDERR_FILENO) { 103 | return; 104 | } 105 | 106 | if (log->fd > 0) { 107 | close(log->fd); 108 | } 109 | log->fd = open(log->file, O_WRONLY | O_APPEND | O_CREAT, 0644); 110 | if (log->fd < 0) { 111 | bz_log_stderr("reopen log file '%s' failed: %s", log->file, 112 | strerror(errno)); 113 | } 114 | } 115 | 116 | void _log(bz_log_t *log, const char *file, int line, int level, const char *fmt, ...) 117 | { 118 | int len, size, errno_save; 119 | char buf[BZ_MAX_ERR_STR]; 120 | va_list args; 121 | struct timeval tv; 122 | struct tm *tm; 123 | 124 | if (!log || log->fd < 0) { 125 | return; 126 | } 127 | 128 | gettimeofday(&tv, NULL); 129 | tm = localtime(&tv.tv_sec); 130 | 131 | errno_save = errno; 132 | len = 0; 133 | size = BZ_MAX_ERR_STR; 134 | len += bz_scnprintf(buf + len, size - len, "[%04d-%02d-%02d %02d:%02d:%02d.%ld] " 135 | "[%*s] [%-12s:%-4d] ", 136 | tm->tm_year + 1900, 137 | tm->tm_mon + 1, tm->tm_mday, 138 | tm->tm_hour, tm->tm_min, tm->tm_sec, 139 | tv.tv_usec, 140 | MAX_LEVEL_DESC_LEN, 141 | loglevel_desc[level], 142 | bz_basename(file), line); 143 | 144 | va_start(args, fmt); 145 | len += bz_vscnprintf(buf + len, size - len, fmt, args); 146 | va_end(args); 147 | 148 | // we do not need '\0' 149 | buf[len++] = '\n'; 150 | 151 | if (write(log->fd, buf, len) < 0) { 152 | log->nerr ++; 153 | } 154 | errno = errno_save; 155 | } 156 | 157 | void _log_stderr(const char *fmt, ...) 158 | { 159 | int len; 160 | char buf[BZ_MAX_ERR_STR]; 161 | va_list args; 162 | 163 | va_start(args, fmt); 164 | len = bz_vscnprintf(buf, BZ_MAX_ERR_STR, fmt, args); 165 | va_end(args); 166 | 167 | buf[len++] = '\n'; 168 | write(STDERR_FILENO, buf, len); 169 | } 170 | 171 | #if defined(HAVE_BACKTRACE) && defined(HAVE_BACKTRACE_SYMBOLS) 172 | void bz_log_backtrace(bz_log_t *log, int level){ 173 | void *bt_buffer[32]; 174 | size_t bt_size, i; 175 | char **bt_strings; 176 | 177 | bt_size = backtrace(bt_buffer, sizeof(bt_buffer) / sizeof(bt_buffer[0])); 178 | bt_strings = backtrace_symbols(bt_buffer, bt_size); 179 | 180 | for (i = 0; i < bt_size; i++) { 181 | bz_log(log, level, "%s", bt_strings[i]); 182 | } 183 | 184 | free(bt_strings); 185 | } 186 | #endif 187 | 188 | -------------------------------------------------------------------------------- /src/log.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_LOG_H 23 | #define BZ_LOG_H 24 | 25 | #include "config.h" 26 | #include "util.h" 27 | 28 | #define BZ_LOG_EMERG 0 29 | #define BZ_LOG_ALERT 1 30 | #define BZ_LOG_CRIT 2 31 | #define BZ_LOG_ERR 3 32 | #define BZ_LOG_ERROR BZ_LOG_ERR 33 | #define BZ_LOG_WARN 4 34 | #define BZ_LOG_WARNING BZ_LOG_WARN 35 | #define BZ_LOG_NOTICE 5 36 | #define BZ_LOG_INFO 6 37 | #define BZ_LOG_DEBUG 7 38 | #define BZ_LOG_VERB 8 39 | 40 | #define BZ_MAX_ERR_STR 1024 41 | 42 | struct bz_log_s { 43 | int log_level; 44 | char *file; 45 | int fd; 46 | size_t nerr; 47 | }; 48 | 49 | typedef struct bz_log_s bz_log_t; 50 | 51 | #ifdef BZ_DEBUG_LOG 52 | 53 | #define bz_log_debug(log, level, ...) do { \ 54 | if ((log)->log_level >= level) \ 55 | _log(log, __FILE__, __LINE__, level, \ 56 | __VA_ARGS__); \ 57 | } while(0) 58 | 59 | #else 60 | 61 | #define bz_log_debug(log, level, ...) 62 | 63 | #endif 64 | 65 | #define bz_log_stderr(...) \ 66 | _log_stderr(__VA_ARGS__) 67 | 68 | #define bz_log(log, level, ...) do { \ 69 | if ((log)->log_level >= level) \ 70 | _log(log, __FILE__, __LINE__, level, \ 71 | __VA_ARGS__); \ 72 | } while(0) 73 | 74 | #define bz_log_warn(log, ...) do { \ 75 | if ((log)->log_level >= BZ_LOG_WARN) \ 76 | _log(log, __FILE__, __LINE__, BZ_LOG_WARN, \ 77 | __VA_ARGS__); \ 78 | } while(0) 79 | 80 | #define bz_log_error(log, ...) do { \ 81 | if ((log)->log_level >= BZ_LOG_ERROR) \ 82 | _log(log, __FILE__, __LINE__,BZ_LOG_ERR, \ 83 | __VA_ARGS__); \ 84 | } while(0) 85 | 86 | #define bz_abort(log, ...) do { \ 87 | if ((log)->log_level >= BZ_LOG_EMERG) \ 88 | _log(log, __FILE__, __LINE__, BZ_LOG_EMERG, \ 89 | __VA_ARGS__); \ 90 | bz_log_backtrace(log, BZ_LOG_EMERG); \ 91 | abort(); \ 92 | } while(0) 93 | 94 | #if defined(HAVE_BACKTRACE) && defined(HAVE_BACKTRACE_SYMBOLS) 95 | void bz_log_backtrace(bz_log_t *log, int level); 96 | #else 97 | # define bz_log_backtrace(log, level) 98 | #endif 99 | 100 | bz_log_t *bz_log_create(int level, const char *filename); 101 | void bz_log_close(bz_log_t *log); 102 | void bz_log_reopen(bz_log_t *log); 103 | void _log(bz_log_t *log, const char *file, int line, int level, 104 | const char *fmt, ...) __attribute__((format(printf, 5, 6))); 105 | void _log_stderr(const char *fmt, ...) __attribute__((format(printf, 1, 2))); 106 | 107 | #endif 108 | -------------------------------------------------------------------------------- /src/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #include 23 | #include 24 | 25 | #include "bitzer.h" 26 | 27 | #define BZ_LOG_DEFAULT BZ_LOG_INFO 28 | 29 | #ifndef BZ_LOG_PATH 30 | # define BZ_LOG_PATH "log/bitzer.log" 31 | #endif 32 | 33 | #ifndef BZ_PID_PATH 34 | # define BZ_PID_PATH "log/bitzer.pid" 35 | #endif 36 | 37 | #ifndef BZ_CONF_PATH 38 | # define BZ_CONF_PATH "conf/bitzer.conf" 39 | #endif 40 | 41 | #define BZ_PROCTITLE "bitzer" 42 | 43 | static int show_help; 44 | static int show_version; 45 | static int test_conf; 46 | static int daemonize; 47 | 48 | static struct option long_options[] = { 49 | { "help", no_argument, NULL, 'h' }, 50 | { "version", no_argument, NULL, 'v' }, 51 | { "test-conf", no_argument, NULL, 't' }, 52 | { "not-daemonize", no_argument, NULL, 'D' }, 53 | { "prefix", required_argument, NULL, 'p' }, 54 | { "verbose", required_argument, NULL, 'l' }, 55 | { "conf-file", required_argument, NULL, 'c' }, 56 | { "log-file", required_argument, NULL, 'L' }, 57 | { "pid-file", required_argument, NULL, 'P' }, 58 | { NULL, 0, NULL, 0 } 59 | }; 60 | 61 | static char short_options[] = "hvtDp:l:c:L:P:"; 62 | 63 | static int bz_get_options(int argc, char *argv[], struct bitzer_s *bz) 64 | { 65 | int c, value; 66 | 67 | opterr = 0; 68 | 69 | // default it is a daemon 70 | daemonize = 1; 71 | 72 | for (;;) { 73 | c = getopt_long(argc, argv, short_options, long_options, NULL); 74 | if (c == -1) { 75 | break; 76 | } 77 | 78 | switch (c) { 79 | case 'h': 80 | show_version = 1; 81 | show_help = 1; 82 | break; 83 | 84 | case 'v': 85 | show_version = 1; 86 | break; 87 | 88 | case 't': 89 | test_conf = 1; 90 | break; 91 | 92 | case 'D': 93 | daemonize = 0; 94 | break; 95 | 96 | case 'p': 97 | bz->prefix = optarg; 98 | if (access(bz->prefix, X_OK) < 0) { 99 | bz_log_stderr("access prefix directory (%s) failed: %s", 100 | bz->prefix, strerror(errno)); 101 | return BZ_ERROR; 102 | } 103 | break; 104 | 105 | case 'l': 106 | value = atoi(optarg); 107 | if (value < 0) { 108 | bz_log_stderr(BITZER_NAME ": option -l requires a number"); 109 | return BZ_ERROR; 110 | } 111 | bz->log_level = value; 112 | break; 113 | 114 | case 'c': 115 | bz->conf_file = optarg; 116 | break; 117 | 118 | case 'L': 119 | bz->log_file = optarg; 120 | break; 121 | 122 | case 'P': 123 | bz->pid_file = optarg; 124 | break; 125 | 126 | case '?': 127 | switch (optopt) { 128 | case 'p': 129 | bz_log_stderr(BITZER_NAME ": option -%c requires a " 130 | "directory name", optopt); 131 | break; 132 | 133 | case 'c': 134 | case 'L': 135 | case 'P': 136 | bz_log_stderr(BITZER_NAME ": option -%c requires a file name", 137 | optopt); 138 | break; 139 | 140 | case 'l': 141 | bz_log_stderr(BITZER_NAME ": option -%c requires a number", 142 | optopt); 143 | break; 144 | 145 | default: 146 | bz_log_stderr(BITZER_NAME ": invalid option '-%c'", optopt); 147 | break; 148 | } 149 | return BZ_ERROR; 150 | 151 | default: 152 | bz_log_stderr(BITZER_NAME ": invalid option '-%c'", optopt); 153 | return BZ_ERROR; 154 | } 155 | } 156 | 157 | return BZ_OK; 158 | } 159 | 160 | static void bz_show_usage() 161 | { 162 | bz_log_stderr( 163 | "Usage: " BITZER_NAME " [-hvtD] [-p prefix] [-l log_level] " 164 | "[-L log_file] [-P pid_file]" BZ_LINEFEED 165 | ); 166 | bz_log_stderr( 167 | "Options:" BZ_LINEFEED 168 | " -h, --help : this help" BZ_LINEFEED 169 | " -v, --version : show version and exit" BZ_LINEFEED 170 | " -t, --test-conf : test configuration and exit" BZ_LINEFEED 171 | " -D, --not-daemonize : do not daemonize" BZ_LINEFEED 172 | " -p, --prefix : set prefix path (default: " 173 | BZ_INSTALL_PREFIX ")" BZ_LINEFEED 174 | " -l, --verbose : set log level (default: %d, min: %d " 175 | "(less verbose), max: %d (more verbose))" 176 | BZ_LINEFEED 177 | " -c, --conf-file : set configuration file (default: " 178 | BZ_CONF_PATH ")" BZ_LINEFEED 179 | " -L, --log-file : set log file (default: " 180 | BZ_LOG_PATH ")" BZ_LINEFEED 181 | " -P, --pid-file : set pid file (default: " 182 | BZ_PID_PATH ")" 183 | , BZ_LOG_DEFAULT, BZ_LOG_EMERG, BZ_LOG_VERB 184 | ); 185 | } 186 | 187 | static int bz_daemonize(bz_log_t *log) 188 | { 189 | pid_t pid; 190 | 191 | pid = fork(); 192 | switch(pid) { 193 | case 0: 194 | break; 195 | case -1: 196 | bz_log_error(log, "fork() failed: %s", strerror(errno)); 197 | return BZ_ERROR; 198 | default: 199 | // in parent 200 | _exit(0); 201 | } 202 | 203 | if (setsid() < 0) { 204 | bz_log_error(log, "setsid() failed: %s", strerror(errno)); 205 | return BZ_ERROR; 206 | } 207 | 208 | // fork again 209 | pid = fork(); 210 | switch(pid) { 211 | case 0: 212 | break; 213 | case -1: 214 | bz_log_error(log, "fork() again failed: %s", strerror(errno)); 215 | return BZ_ERROR; 216 | default: 217 | _exit(0); 218 | } 219 | 220 | return BZ_OK; 221 | } 222 | 223 | static int bz_redirect_io(struct bitzer_s *bz) 224 | { 225 | int fd; 226 | char *ptr; 227 | 228 | umask(0); 229 | 230 | fd = open(bz->log_file, O_RDWR | O_APPEND); 231 | if (fd < 0) { 232 | bz_log_error(bz->log, "open(\"%s\") failed: %s", 233 | bz->log_file, strerror(errno)); 234 | return BZ_ERROR; 235 | } 236 | 237 | if (dup2(fd, STDIN_FILENO) < 0) { 238 | ptr = "STDIN"; 239 | goto DUP2FAILED; 240 | } 241 | 242 | if (dup2(fd, STDOUT_FILENO) < 0) { 243 | ptr = "STDOUT"; 244 | goto DUP2FAILED; 245 | } 246 | 247 | if (dup2(fd, STDERR_FILENO) < 0) { 248 | ptr = "STDERR"; 249 | goto DUP2FAILED; 250 | } 251 | 252 | if (close(fd) == -1) { 253 | bz_log_error(bz->log, "close(\"%s\") failed: %s", 254 | bz->log_file, strerror(errno)); 255 | return BZ_ERROR; 256 | } 257 | return BZ_OK; 258 | 259 | DUP2FAILED: 260 | bz_log_error(bz->log, "dup2(%d, \"%s\") failed: %s", fd, ptr, strerror(errno)); 261 | close(fd); 262 | return BZ_ERROR; 263 | } 264 | 265 | static int bz_write_pidfile(struct bitzer_s *bz) 266 | { 267 | int fd, len; 268 | char pid[BZ_INT64_LEN + 1]; 269 | 270 | fd = open(bz->pid_file, O_WRONLY | O_CREAT | O_TRUNC, 0644); 271 | if (fd < 0) { 272 | bz_log_error(bz->log, "open pid file '%s' failed: %s", 273 | bz->pid_file, strerror(errno)); 274 | return BZ_ERROR; 275 | } 276 | 277 | len = snprintf(pid, BZ_INT64_LEN + 1, "%d", bz->pid); 278 | if (len < 0) { 279 | close(fd); 280 | return BZ_ERROR; 281 | } 282 | 283 | pid[len++] = '\n'; 284 | if (write(fd, pid, len) < 0) { 285 | bz_log_error(bz->log, "write pid file '%s' failed: %s", 286 | bz->pid_file, strerror(errno)); 287 | close(fd); 288 | return BZ_ERROR; 289 | } 290 | 291 | close(fd); 292 | return BZ_OK; 293 | } 294 | 295 | static int bz_remove_pidfile(struct bitzer_s *bz) 296 | { 297 | return (unlink(bz->pid_file) < 0) ? BZ_ERROR : BZ_OK; 298 | } 299 | 300 | static void bz_set_default_instance(struct bitzer_s *bz) 301 | { 302 | bz->prefix = BZ_INSTALL_PREFIX; 303 | bz->log_level = BZ_LOG_DEFAULT; 304 | bz->log_file = BZ_LOG_PATH; 305 | 306 | bz->conf_file = BZ_CONF_PATH; 307 | 308 | if (gethostname(bz->hostname, BZ_MAXHOSTNAMELEN)) { 309 | bz_log_warn(bz->log, "gethostname() failed: %s", strerror(errno)); 310 | strncpy(bz->hostname, "unknown", sizeof("unknown")); // no -1 here 311 | } 312 | bz->hostname[BZ_MAXHOSTNAMELEN - 1] = '\0'; 313 | 314 | bz->pid = (pid_t)-1; 315 | bz->pid_file = BZ_PID_PATH; 316 | 317 | bz->log_file_alloc = 0; 318 | bz->conf_file_alloc = 0; 319 | bz->pid_file_alloc = 0; 320 | } 321 | 322 | static void bz_print_sysinfo(struct bitzer_s *bz) 323 | { 324 | struct utsname uts; 325 | 326 | bz_log(bz->log, BZ_LOG_INFO, "bitzer version: " BITZER_VERSION); 327 | 328 | if (uname(&uts) < 0) { 329 | return; 330 | } 331 | bz_log(bz->log, BZ_LOG_INFO, "OS: %s %s %s", uts.sysname, 332 | uts.release, uts.machine); 333 | } 334 | 335 | static void bz_setproctitle(char **argv, const char *title) 336 | { 337 | size_t i, len; 338 | 339 | len = strlen(argv[0]); 340 | for (i = 0; i < len && title[i] != '\0'; i++) { 341 | argv[0][i] = title[i]; 342 | } 343 | while (i < len) { 344 | argv[0][i++] = ' '; 345 | } 346 | } 347 | 348 | #define BZ_MEMBER_ALLOC(_member) _member ## _alloc 349 | 350 | #define BZ_STRCAT_IF_RELATIVE(_instance, _member, _path) \ 351 | do { \ 352 | if (_instance->_member[0] != BZ_PATHSEP) { \ 353 | plen = strlen(bz->prefix); \ 354 | name = malloc(plen + strlen(_path) + 2); \ 355 | if (name == NULL) { \ 356 | return BZ_ERROR; \ 357 | } \ 358 | p = memcpy(name, bz->prefix, plen); \ 359 | p += plen; \ 360 | if (*(p - 1) != BZ_PATHSEP) { \ 361 | *p++ = BZ_PATHSEP; \ 362 | } \ 363 | memcpy(p, _path, strlen(_path) + 1); \ 364 | _instance->_member = name; \ 365 | _instance->BZ_MEMBER_ALLOC(_member) = 1; \ 366 | } \ 367 | } while(0) 368 | 369 | static int bz_init_instance(struct bitzer_s *bz) 370 | { 371 | size_t plen; 372 | char *p, *name; 373 | 374 | BZ_STRCAT_IF_RELATIVE(bz, log_file, bz->log_file); 375 | BZ_STRCAT_IF_RELATIVE(bz, conf_file, bz->conf_file); 376 | BZ_STRCAT_IF_RELATIVE(bz, pid_file, bz->pid_file); 377 | 378 | bz->log = bz_log_create(bz->log_level, bz->log_file); 379 | if (!bz->log) { 380 | return BZ_ERROR; 381 | } 382 | 383 | bz_print_sysinfo(bz); 384 | 385 | if (daemonize && bz_daemonize(bz->log) != BZ_OK) { 386 | return BZ_ERROR; 387 | } 388 | 389 | if (daemonize && bz_redirect_io(bz) != BZ_OK) { 390 | return BZ_ERROR; 391 | } 392 | 393 | if (signal_init(bz->log) != BZ_OK) { 394 | return BZ_ERROR; 395 | } 396 | 397 | bz->pid = getpid(); 398 | if (bz_write_pidfile(bz) != BZ_OK) { 399 | return BZ_ERROR; 400 | } 401 | 402 | return BZ_OK; 403 | } 404 | 405 | #define BZ_FREE_IF_ALLOC(_instance, _member) \ 406 | do { \ 407 | if (_instance->BZ_MEMBER_ALLOC(_member)) { \ 408 | free(_instance->_member); \ 409 | _instance->_member = NULL; \ 410 | } \ 411 | } while(0) 412 | 413 | static void bz_post_run(struct bitzer_s *bz) 414 | { 415 | signal_close(bz->log); 416 | 417 | if (bz_remove_pidfile(bz) != BZ_OK && bz->log) { 418 | bz_log_error(bz->log, "remove pid file '%s' failed: %s", 419 | bz->pid_file, strerror(errno)); 420 | } 421 | 422 | if (bz->log) { 423 | bz_log(bz->log, BZ_LOG_INFO, "exit"); 424 | bz_log_close(bz->log); 425 | } 426 | 427 | BZ_FREE_IF_ALLOC(bz, log_file); 428 | BZ_FREE_IF_ALLOC(bz, conf_file); 429 | BZ_FREE_IF_ALLOC(bz, pid_file); 430 | } 431 | 432 | static void bz_signal_callback(void *arg) 433 | { 434 | // not graceful termination 435 | if (bz_quit) { 436 | exit(2); 437 | } 438 | 439 | // graceful termination 440 | if (bz_terminate) { 441 | // here `context` is global variable 442 | context_close(context); 443 | bz_post_run((struct bitzer_s *)arg); 444 | exit(1); 445 | } 446 | } 447 | 448 | static void bz_run(struct bitzer_s *bz) 449 | { 450 | context_t *ctx; 451 | 452 | ctx = context_create(bz); 453 | if (ctx == NULL) { 454 | return; 455 | } 456 | 457 | if (context_init(ctx) != BZ_OK) { 458 | context_close(ctx); 459 | return; 460 | } 461 | 462 | context = ctx; 463 | context_set_signal_callback(ctx, bz_signal_callback, (void *)bz); 464 | context_run(ctx); 465 | 466 | context_close(ctx); 467 | } 468 | 469 | int main(int argc, char *argv[]) 470 | { 471 | int status; 472 | struct bitzer_s bz; 473 | 474 | bz_set_default_instance(&bz); 475 | 476 | if (bz_get_options(argc, argv, &bz) != BZ_OK) { 477 | bz_show_usage(); 478 | exit(1); 479 | } 480 | 481 | if (show_version) { 482 | bz_log_stderr(BITZER_NAME ": " BITZER_VERSION); 483 | if (show_help) { 484 | bz_show_usage(); 485 | } 486 | exit(0); 487 | } 488 | 489 | status = bz_init_instance(&bz); 490 | if (status != BZ_OK) { 491 | bz_post_run(&bz); 492 | exit(1); 493 | } 494 | 495 | bz_setproctitle(argv, BZ_PROCTITLE); 496 | 497 | bz_run(&bz); 498 | 499 | bz_post_run(&bz); 500 | exit(1); 501 | } 502 | -------------------------------------------------------------------------------- /src/rbtree.c: -------------------------------------------------------------------------------- 1 | #include "rbtree.h" 2 | 3 | void rbtree_init(rbtree_t *tree, rbtree_node_t *sentinel) 4 | { 5 | rbtree_node_init(sentinel); 6 | rbtree_black(sentinel); 7 | tree->root = sentinel; 8 | tree->sentinel = sentinel; 9 | } 10 | 11 | static rbtree_node_t * 12 | rbtree_node_min(rbtree_node_t *node, rbtree_node_t *sentinel) 13 | { 14 | /* traverse left links */ 15 | 16 | while (node->left != sentinel) { 17 | node = node->left; 18 | } 19 | 20 | return node; 21 | } 22 | 23 | rbtree_node_t *rbtree_min(rbtree_t *tree) 24 | { 25 | rbtree_node_t *node = tree->root; 26 | rbtree_node_t *sentinel = tree->sentinel; 27 | 28 | /* empty tree */ 29 | 30 | if (node == sentinel) { 31 | return NULL; 32 | } 33 | 34 | return rbtree_node_min(node, sentinel); 35 | } 36 | 37 | static rbtree_node_t * 38 | rbtree_node_max(rbtree_node_t *node, rbtree_node_t *sentinel) 39 | { 40 | /* traverse right links */ 41 | 42 | while (node->right != sentinel) { 43 | node = node->right; 44 | } 45 | 46 | return node; 47 | } 48 | 49 | rbtree_node_t *rbtree_max(rbtree_t *tree) 50 | { 51 | rbtree_node_t *node = tree->root; 52 | rbtree_node_t *sentinel = tree->sentinel; 53 | 54 | /* empty tree */ 55 | 56 | if (node == sentinel) { 57 | return NULL; 58 | } 59 | 60 | return rbtree_node_max(node, sentinel); 61 | } 62 | 63 | static void 64 | rbtree_left_rotate(rbtree_node_t **root, rbtree_node_t *sentinel, 65 | rbtree_node_t *node) 66 | { 67 | rbtree_node_t *temp; 68 | 69 | temp = node->right; 70 | node->right = temp->left; 71 | 72 | if (temp->left != sentinel) { 73 | temp->left->parent = node; 74 | } 75 | 76 | temp->parent = node->parent; 77 | 78 | if (node == *root) { 79 | *root = temp; 80 | } else if (node == node->parent->left) { 81 | node->parent->left = temp; 82 | } else { 83 | node->parent->right = temp; 84 | } 85 | 86 | temp->left = node; 87 | node->parent = temp; 88 | } 89 | 90 | static void 91 | rbtree_right_rotate(rbtree_node_t **root, rbtree_node_t *sentinel, 92 | rbtree_node_t *node) 93 | { 94 | rbtree_node_t *temp; 95 | 96 | temp = node->left; 97 | node->left = temp->right; 98 | 99 | if (temp->right != sentinel) { 100 | temp->right->parent = node; 101 | } 102 | 103 | temp->parent = node->parent; 104 | 105 | if (node == *root) { 106 | *root = temp; 107 | } else if (node == node->parent->right) { 108 | node->parent->right = temp; 109 | } else { 110 | node->parent->left = temp; 111 | } 112 | 113 | temp->right = node; 114 | node->parent = temp; 115 | } 116 | 117 | void 118 | rbtree_insert(rbtree_t *tree, rbtree_node_t *node) 119 | { 120 | rbtree_node_t **root = &tree->root; 121 | rbtree_node_t *sentinel = tree->sentinel; 122 | rbtree_node_t *temp, **p; 123 | 124 | /* empty tree */ 125 | 126 | if (*root == sentinel) { 127 | node->parent = NULL; 128 | node->left = sentinel; 129 | node->right = sentinel; 130 | rbtree_black(node); 131 | *root = node; 132 | return; 133 | } 134 | 135 | /* a binary tree insert */ 136 | 137 | temp = *root; 138 | for (;;) { 139 | 140 | p = (node->key < temp->key) ? &temp->left : &temp->right; 141 | if (*p == sentinel) { 142 | break; 143 | } 144 | temp = *p; 145 | } 146 | 147 | *p = node; 148 | node->parent = temp; 149 | node->left = sentinel; 150 | node->right = sentinel; 151 | rbtree_red(node); 152 | 153 | /* re-balance tree */ 154 | 155 | while (node != *root && rbtree_is_red(node->parent)) { 156 | 157 | if (node->parent == node->parent->parent->left) { 158 | temp = node->parent->parent->right; 159 | 160 | if (rbtree_is_red(temp)) { 161 | rbtree_black(node->parent); 162 | rbtree_black(temp); 163 | rbtree_red(node->parent->parent); 164 | node = node->parent->parent; 165 | } else { 166 | if (node == node->parent->right) { 167 | node = node->parent; 168 | rbtree_left_rotate(root, sentinel, node); 169 | } 170 | 171 | rbtree_black(node->parent); 172 | rbtree_red(node->parent->parent); 173 | rbtree_right_rotate(root, sentinel, node->parent->parent); 174 | } 175 | } else { 176 | temp = node->parent->parent->left; 177 | 178 | if (rbtree_is_red(temp)) { 179 | rbtree_black(node->parent); 180 | rbtree_black(temp); 181 | rbtree_red(node->parent->parent); 182 | node = node->parent->parent; 183 | } else { 184 | if (node == node->parent->left) { 185 | node = node->parent; 186 | rbtree_right_rotate(root, sentinel, node); 187 | } 188 | 189 | rbtree_black(node->parent); 190 | rbtree_red(node->parent->parent); 191 | rbtree_left_rotate(root, sentinel, node->parent->parent); 192 | } 193 | } 194 | } 195 | 196 | rbtree_black(*root); 197 | } 198 | 199 | void 200 | rbtree_delete(rbtree_t *tree, rbtree_node_t *node) 201 | { 202 | rbtree_node_t **root = &tree->root; 203 | rbtree_node_t *sentinel = tree->sentinel; 204 | rbtree_node_t *subst, *temp, *w; 205 | uint8_t red; 206 | 207 | /* a binary tree delete */ 208 | 209 | if (node->left == sentinel) { 210 | temp = node->right; 211 | subst = node; 212 | } else if (node->right == sentinel) { 213 | temp = node->left; 214 | subst = node; 215 | } else { 216 | subst = rbtree_node_min(node->right, sentinel); 217 | temp = subst->right; 218 | } 219 | 220 | if (subst == *root) { 221 | *root = temp; 222 | rbtree_black(temp); 223 | 224 | rbtree_node_init(node); 225 | 226 | return; 227 | } 228 | 229 | red = rbtree_is_red(subst); 230 | 231 | if (subst == subst->parent->left) { 232 | subst->parent->left = temp; 233 | } else { 234 | subst->parent->right = temp; 235 | } 236 | 237 | if (subst == node) { 238 | temp->parent = subst->parent; 239 | } else { 240 | 241 | if (subst->parent == node) { 242 | temp->parent = subst; 243 | } else { 244 | temp->parent = subst->parent; 245 | } 246 | 247 | subst->left = node->left; 248 | subst->right = node->right; 249 | subst->parent = node->parent; 250 | rbtree_copy_color(subst, node); 251 | 252 | if (node == *root) { 253 | *root = subst; 254 | } else { 255 | if (node == node->parent->left) { 256 | node->parent->left = subst; 257 | } else { 258 | node->parent->right = subst; 259 | } 260 | } 261 | 262 | if (subst->left != sentinel) { 263 | subst->left->parent = subst; 264 | } 265 | 266 | if (subst->right != sentinel) { 267 | subst->right->parent = subst; 268 | } 269 | } 270 | 271 | rbtree_node_init(node); 272 | 273 | if (red) { 274 | return; 275 | } 276 | 277 | /* a delete fixup */ 278 | 279 | while (temp != *root && rbtree_is_black(temp)) { 280 | 281 | if (temp == temp->parent->left) { 282 | w = temp->parent->right; 283 | 284 | if (rbtree_is_red(w)) { 285 | rbtree_black(w); 286 | rbtree_red(temp->parent); 287 | rbtree_left_rotate(root, sentinel, temp->parent); 288 | w = temp->parent->right; 289 | } 290 | 291 | if (rbtree_is_black(w->left) && rbtree_is_black(w->right)) { 292 | rbtree_red(w); 293 | temp = temp->parent; 294 | } else { 295 | if (rbtree_is_black(w->right)) { 296 | rbtree_black(w->left); 297 | rbtree_red(w); 298 | rbtree_right_rotate(root, sentinel, w); 299 | w = temp->parent->right; 300 | } 301 | 302 | rbtree_copy_color(w, temp->parent); 303 | rbtree_black(temp->parent); 304 | rbtree_black(w->right); 305 | rbtree_left_rotate(root, sentinel, temp->parent); 306 | temp = *root; 307 | } 308 | 309 | } else { 310 | w = temp->parent->left; 311 | 312 | if (rbtree_is_red(w)) { 313 | rbtree_black(w); 314 | rbtree_red(temp->parent); 315 | rbtree_right_rotate(root, sentinel, temp->parent); 316 | w = temp->parent->left; 317 | } 318 | 319 | if (rbtree_is_black(w->left) && rbtree_is_black(w->right)) { 320 | rbtree_red(w); 321 | temp = temp->parent; 322 | } else { 323 | if (rbtree_is_black(w->left)) { 324 | rbtree_black(w->right); 325 | rbtree_red(w); 326 | rbtree_left_rotate(root, sentinel, w); 327 | w = temp->parent->left; 328 | } 329 | 330 | rbtree_copy_color(w, temp->parent); 331 | rbtree_black(temp->parent); 332 | rbtree_black(w->left); 333 | rbtree_right_rotate(root, sentinel, temp->parent); 334 | temp = *root; 335 | } 336 | } 337 | } 338 | 339 | rbtree_black(temp); 340 | } 341 | -------------------------------------------------------------------------------- /src/rbtree.h: -------------------------------------------------------------------------------- 1 | #ifndef __RBTREE_H__ 2 | #define __RBTREE_H__ 3 | 4 | #include 5 | #include // for NULL 6 | 7 | typedef uint64_t rbtree_key_t; 8 | 9 | #define rbtree_red(_node) ((_node)->color = 1) 10 | #define rbtree_black(_node) ((_node)->color = 0) 11 | #define rbtree_is_red(_node) ((_node)->color) 12 | #define rbtree_is_black(_node) (!rbtree_is_red(_node)) 13 | #define rbtree_copy_color(_n1, _n2) ((_n1)->color = (_n2)->color) 14 | 15 | typedef struct rbtree_node_s rbtree_node_t; 16 | 17 | struct rbtree_node_s { 18 | rbtree_node_t *left; /* left link */ 19 | rbtree_node_t *right; /* right link */ 20 | rbtree_node_t *parent; /* parent link */ 21 | rbtree_key_t key; /* key for ordering */ 22 | unsigned char color; /* red | black */ 23 | }; 24 | 25 | typedef struct rbtree_s { 26 | rbtree_node_t *root; /* root node */ 27 | rbtree_node_t *sentinel; /* nil node */ 28 | } rbtree_t; 29 | 30 | #define rbtree_empty(tree) \ 31 | (tree)->root == (tree)->sentinel 32 | 33 | /* color is left uninitialized */ 34 | #define rbtree_node_init(_node) \ 35 | do { \ 36 | (_node)->left = NULL; \ 37 | (_node)->right = NULL; \ 38 | (_node)->parent = NULL; \ 39 | (_node)->key = 0ULL; \ 40 | } while(0) 41 | 42 | void rbtree_init(rbtree_t *tree, rbtree_node_t *sentinel); 43 | rbtree_node_t *rbtree_min(rbtree_t *tree); 44 | rbtree_node_t *rbtree_max(rbtree_t *tree); 45 | void rbtree_insert(rbtree_t *tree, rbtree_node_t *node); 46 | void rbtree_delete(rbtree_t *tree, rbtree_node_t *node); 47 | 48 | #define rbtree_entry(ptr, type, member) \ 49 | ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /src/sighandler.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #include "bitzer.h" 23 | 24 | static void signal_handler(int signo); 25 | 26 | signal_t signals[] = { 27 | { 28 | signal_value(SIGNAL_SHUTDOWN), 29 | signal_name(SIGNAL_SHUTDOWN), 30 | "quit", 31 | signal_handler 32 | }, 33 | 34 | { 35 | signal_value(SIGNAL_TERMINATE), 36 | signal_name(SIGNAL_TERMINATE), 37 | "stop", 38 | signal_handler 39 | }, 40 | 41 | { 42 | signal_value(SIGNAL_RECONFIGURE), 43 | signal_name(SIGNAL_RECONFIGURE), 44 | "reload", 45 | signal_handler 46 | }, 47 | 48 | { 49 | signal_value(SIGNAL_REOPEN), 50 | signal_name(SIGNAL_REOPEN), 51 | "reopen", 52 | signal_handler 53 | }, 54 | 55 | { 56 | SIGINT, 57 | "SIGINT", 58 | "stop", 59 | signal_handler 60 | }, 61 | 62 | { 63 | SIGCHLD, 64 | "SIGCHLD", 65 | "child", 66 | signal_handler 67 | }, 68 | 69 | { SIGTTIN, "SIGTTIN", "", signal_handler }, 70 | { SIGTTOU, "SIGTTOU", "", signal_handler }, 71 | { SIGPIPE, "SIGPIPE", "", SIG_IGN }, 72 | 73 | { 0, NULL, "", NULL } 74 | }; 75 | 76 | int signal_init(bz_log_t *log) 77 | { 78 | signal_t *sig; 79 | struct sigaction sa; 80 | 81 | for (sig = signals; sig->signo != 0; sig++) { 82 | memset(&sa, 0, sizeof(sa)); 83 | 84 | sa.sa_handler = sig->handler; 85 | sigemptyset(&sa.sa_mask); 86 | 87 | bz_log_debug(log, BZ_LOG_DEBUG, "sigaction(%s)", sig->signame); 88 | if (sigaction(sig->signo, &sa, NULL) < 0) { 89 | bz_log_error(log, "sigaction(%s) failed: %s", 90 | sig->signame, strerror(errno)); 91 | return ERROR; 92 | } 93 | } 94 | 95 | return OK; 96 | } 97 | 98 | void signal_close(bz_log_t *log) 99 | { 100 | return; 101 | } 102 | 103 | void signal_handler(int signo) 104 | { 105 | const char *action; 106 | signal_t *sig; 107 | 108 | for (sig = signals; sig->signo != 0; sig++) { 109 | if (sig->signo == signo) { 110 | break; 111 | } 112 | } 113 | 114 | action = ""; 115 | switch(signo) { 116 | case signal_value(SIGNAL_SHUTDOWN): 117 | bz_quit = 1; 118 | action = "shutting down"; 119 | break; 120 | case signal_value(SIGNAL_TERMINATE): 121 | case SIGINT: 122 | bz_terminate = 1; 123 | action = "exiting"; 124 | break; 125 | case signal_value(SIGNAL_RECONFIGURE): 126 | bz_reconfigure = 1; 127 | action = "reconfiguring"; 128 | break; 129 | case signal_value(SIGNAL_REOPEN): 130 | bz_reopen = 1; 131 | action = "reopening logs"; 132 | break; 133 | case SIGCHLD: 134 | bz_child = 1; 135 | action = "handling tasks"; 136 | default: 137 | break; 138 | } 139 | 140 | bz_log(context->log, BZ_LOG_NOTICE, "signal %d(%s) received, %s", 141 | signo, sig->signame, action); 142 | 143 | } 144 | 145 | -------------------------------------------------------------------------------- /src/sighandler.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_SIGNAL_H 23 | #define BZ_SIGNAL_H 24 | 25 | #include 26 | 27 | #define signal_name_help(n) "SIG" #n 28 | #define signal_name(n) signal_name_help(n) 29 | 30 | #define signal_value_help(n) SIG##n 31 | #define signal_value(n) signal_value_help(n) 32 | 33 | #define SIGNAL_SHUTDOWN QUIT 34 | #define SIGNAL_TERMINATE TERM 35 | #define SIGNAL_RECONFIGURE HUP 36 | #define SIGNAL_REOPEN USR1 37 | 38 | typedef struct { 39 | int signo; 40 | char *signame; 41 | char *name; 42 | void (*handler)(int signo); 43 | } signal_t; 44 | 45 | int signal_init(bz_log_t *log); 46 | void signal_close(bz_log_t *log); 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /src/strutil.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #include 23 | 24 | #include "strutil.h" 25 | 26 | int _scnprintf(char *buf, size_t size, const char *fmt, ...) 27 | { 28 | int n; 29 | va_list args; 30 | 31 | va_start(args, fmt); 32 | n = _vscnprintf(buf, size, fmt, args); 33 | va_end(args); 34 | 35 | return n; 36 | } 37 | 38 | int _vscnprintf(char *buf, size_t size, const char *fmt, va_list args) 39 | { 40 | int n; 41 | 42 | n = vsnprintf(buf, size, fmt, args); 43 | 44 | // if error occured, n <= 0 45 | return (n <= 0 ? 0 : (n < (int)size ? n : (int)(size -1))); 46 | } 47 | -------------------------------------------------------------------------------- /src/strutil.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_STRING_H 23 | #define BZ_STRING_H 24 | 25 | #include 26 | #include 27 | 28 | struct string { 29 | u_char *data; 30 | size_t len; 31 | }; 32 | 33 | #define string(_str) { _str, sizeof(_str) - 1 } 34 | #define null_string(_str) { NULL, 0 } 35 | 36 | #define bz_scnprintf(_buf, _size, ...) \ 37 | _scnprintf((char *)(_buf), (size_t)(_size), __VA_ARGS__) 38 | 39 | #define bz_vscnprintf(_buf, _size, _fmt, _args) \ 40 | _vscnprintf((char *)(_buf), (size_t)(_size), _fmt, _args) 41 | 42 | int _scnprintf(char *buf, size_t size, const char *fmt, ...); 43 | int _vscnprintf(char *buf, size_t size, const char *fmt, va_list args); 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /src/task.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #include "bitzer.h" 23 | 24 | static int task_reset(task_t *task); 25 | static int task_redirect_io(task_t *task); 26 | static int task_pre_run(task_t *task); 27 | 28 | task_t *task_create(context_t *ctx) 29 | { 30 | task_t *task; 31 | 32 | task = (task_t *)bz_alloc(sizeof(task_t), ctx->log); 33 | if (task == NULL) { 34 | bz_log_error(ctx->log, "create task failed"); 35 | return NULL; 36 | } 37 | 38 | task_init(task, ctx); 39 | 40 | return task; 41 | } 42 | 43 | int task_init(task_t *task, context_t *ctx) 44 | { 45 | task->pid = 0; 46 | task->start_time.tv_sec = 0; 47 | task->start_time.tv_usec = 0; 48 | task->start_count = 0 ; 49 | task->ctx = ctx; 50 | task->path = NULL; 51 | task->name = NULL; 52 | task->dir = NULL; 53 | task->args = NULL; 54 | task->args_len = 0; 55 | task->args_total = 0; 56 | task->envp = NULL; 57 | task->envp_len = 0; 58 | task->envp_total = 0; 59 | task->status = TASK_INIT; 60 | task->log_path = NULL; 61 | 62 | // NOTE: we have not init list and node 63 | 64 | return OK; 65 | } 66 | 67 | static int task_reset(task_t *task) 68 | { 69 | task->pid = 0; 70 | task->status = TASK_FINISHED; 71 | return OK; 72 | } 73 | 74 | static int task_redirect_io(task_t *task) 75 | { 76 | int fd; 77 | char *ptr; 78 | 79 | if (!task->log_path) { 80 | task->log_path = (char *)bz_alloc(strlen(task->ctx->instance->prefix) + 81 | strlen(task->name) + 10, task->ctx->log); 82 | if (!task->log_path) { 83 | return ERROR; 84 | } 85 | 86 | strcpy(task->log_path, task->ctx->instance->prefix); 87 | strcat(task->log_path, "/log/"); 88 | strcat(task->log_path, task->name); 89 | strcat(task->log_path, ".log"); 90 | } 91 | 92 | fd = open(task->log_path, O_RDWR | O_APPEND | O_CREAT, 0644); 93 | if (fd < 0) { 94 | bz_log_error(task->ctx->log, "open(\"%s\") failed: %s", 95 | task->log_path, strerror(errno)); 96 | return ERROR; 97 | } 98 | 99 | if (dup2(fd, STDIN_FILENO) < 0) { 100 | ptr = "STDIN"; 101 | goto DUP2FAILED; 102 | } 103 | 104 | if (dup2(fd, STDOUT_FILENO) < 0) { 105 | ptr = "STDOUT"; 106 | goto DUP2FAILED; 107 | } 108 | 109 | if (dup2(fd, STDERR_FILENO) < 0) { 110 | ptr = "STDERR"; 111 | goto DUP2FAILED; 112 | } 113 | 114 | close(fd); 115 | return OK; 116 | 117 | DUP2FAILED: 118 | bz_log_error(task->ctx->log, "redirect task io, dup2(%d, \"%s\") failed: %s", 119 | fd, ptr, strerror(errno)); 120 | close(fd); 121 | return ERROR; 122 | } 123 | 124 | static int task_pre_run(task_t *task) 125 | { 126 | task_redirect_io(task); 127 | if (task->dir && chdir(task->dir) < 0) { 128 | bz_log_error(task->ctx->log, 129 | "change working directory failed, task: %s, error: %s", 130 | task->name, strerror(errno)); 131 | return ERROR; 132 | } 133 | 134 | if (task->dir && setenv("PWD", task->dir, /* overwrite = */ 1) < 0) { 135 | bz_log_error(task->ctx->log, 136 | "set env PWD failed, task: %s, error: %s", 137 | task->name, strerror(errno)); 138 | return ERROR; 139 | } 140 | 141 | if (setenv("_", task->path, /* overwrite = */ 1) < 0) { 142 | bz_log_error(task->ctx->log, 143 | "set env _ failed, task: %s, error: %s", 144 | task->name, strerror(errno)); 145 | return ERROR; 146 | } 147 | 148 | if (sigprocmask(SIG_SETMASK, &task->ctx->origmask, NULL) < 0) { 149 | bz_log_error(task->ctx->log, 150 | "change back signal mask failed, task: %s, error: %s", 151 | task->name, strerror(errno)); 152 | return ERROR; 153 | } 154 | 155 | return OK; 156 | } 157 | 158 | int task_run(task_t *task) 159 | { 160 | int ret; 161 | pid_t pid; 162 | 163 | task_reset(task); 164 | 165 | if (!task->name || !task->path) { 166 | bz_log_error(task->ctx->log, 167 | "you must set task name and path"); 168 | return ERROR; 169 | } 170 | 171 | pid = fork(); 172 | switch(pid) { 173 | case 0: 174 | if (task_pre_run(task) != OK) { 175 | _exit(ERROR); 176 | } 177 | ret = execv(task->path, task->args); 178 | if (ret < 0) { 179 | bz_log_error(task->ctx->log, 180 | "call execv failed, task: %s, error: %s", 181 | task->name, strerror(errno)); 182 | _exit(ERROR); 183 | } 184 | break; 185 | case -1: 186 | bz_log_error(task->ctx->log, 187 | "fork process failed, task: %s, error: %s", 188 | task->name, strerror(errno)); 189 | return ERROR; 190 | } 191 | 192 | task->pid = pid; 193 | task->node.key = (rbtree_key_t)pid; 194 | task->status = TASK_RUNNING; 195 | task->start_count++; 196 | gettimeofday(&task->start_time, NULL); 197 | return OK; 198 | } 199 | 200 | int task_exit_handler(task_t *task, int status) 201 | { 202 | if (WIFEXITED(status)) { 203 | bz_log(task->ctx->log, BZ_LOG_INFO, 204 | "task(%s) finished, return value: %d", 205 | task->name, WEXITSTATUS(status)); 206 | return OK; 207 | } 208 | 209 | bz_log(task->ctx->log, BZ_LOG_INFO, 210 | "task(%s) finished, by signal: %d", 211 | task->name, WTERMSIG(status)); 212 | return OK; 213 | } 214 | 215 | int task_close(task_t *task) 216 | { 217 | char **ptr; 218 | 219 | ptr = task->args; 220 | while (*ptr) { 221 | free(*ptr++); 222 | } 223 | free(task->args); 224 | 225 | if (task->envp) { 226 | ptr = task->envp; 227 | while (*ptr) { 228 | free(*ptr++); 229 | } 230 | } 231 | // ok if envp is NULL 232 | free(task->envp); 233 | 234 | // NOTE: we can't free task->path here, 235 | // because it is already been freed in args[0] 236 | 237 | free((char *)task->name); 238 | free((char *)task->dir); 239 | free(task->log_path); 240 | return OK; 241 | } 242 | -------------------------------------------------------------------------------- /src/task.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_TASK_H 23 | #define BZ_TASK_H 24 | 25 | #include "bitzer.h" 26 | 27 | enum task_status_e { 28 | TASK_INIT = 0, 29 | TASK_RUNNING, 30 | TASK_FINISHED, 31 | }; 32 | 33 | typedef struct task_s { 34 | pid_t pid; 35 | struct timeval start_time; 36 | size_t start_count; 37 | context_t *ctx; 38 | char *log_path; 39 | const char *path; 40 | const char *name; 41 | const char *dir; 42 | char **args; 43 | size_t args_len; 44 | size_t args_total; 45 | char **envp; 46 | size_t envp_len; 47 | size_t envp_total; 48 | struct list_head list; 49 | rbtree_node_t node; 50 | unsigned int status:4; 51 | } task_t; 52 | 53 | task_t *task_create(context_t *ctx); 54 | int task_init(task_t *task, context_t *ctx); 55 | int task_run(task_t *task); 56 | int task_exit_handler(task_t *task, int status); 57 | int task_close(task_t *task); 58 | 59 | #endif 60 | -------------------------------------------------------------------------------- /src/util.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Shang Yuanchun 3 | * 4 | * 5 | * You may redistribute it and/or modify it under the terms of the 6 | * GNU General Public License, as published by the Free Software 7 | * Foundation; either version 3 of the License, or (at your option) 8 | * any later version. 9 | * 10 | * Bitzer is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | * See the GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with Bitzer. If not, write to: 17 | * The Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor 19 | * Boston, MA 02110-1301, USA. 20 | */ 21 | 22 | #ifndef BZ_UTIL_H 23 | #define BZ_UTIL_H 24 | 25 | #ifdef MAXHOSTNAMELEN 26 | # define BZ_MAXHOSTNAMELEN MAXHOSTNAMELEN 27 | #else 28 | # define BZ_MAXHOSTNAMELEN 256 29 | #endif 30 | 31 | #ifndef __GNUC__ 32 | # define __attribute__(x) 33 | # define __FUNCTION__ "" 34 | #endif 35 | 36 | #define min(a, b) ((a) < (b) ? (a) : (b)) 37 | #define max(a, b) ((a) > (b) ? (a) : (b)) 38 | 39 | #define BZ_INT32_LEN (sizeof("-2147483648") - 1) 40 | #define BZ_INT64_LEN (sizeof("-9223372036854775808") - 1) 41 | 42 | #ifndef BZ_ALIGNMENT 43 | #define BZ_ALIGNMENT sizeof(unsigned long) 44 | #endif 45 | 46 | #define BZ_PATHSEP '/' 47 | #define BZ_LINEFEED "\n" 48 | 49 | #define bz_align(d, a) (((d) + (a - 1)) & ~(a - 1)) 50 | #define bz_align_ptr(p, a) \ 51 | (u_char *) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1)) 52 | 53 | #endif 54 | --------------------------------------------------------------------------------