pax_global_header00006660000000000000000000000064125266423440014522gustar00rootroot0000000000000052 comment=c6ff479e157331000ad42fa58664ffd9af322a0e safelease-1.0/000077500000000000000000000000001252664234400133125ustar00rootroot00000000000000safelease-1.0/AUTHORS000066400000000000000000000005371252664234400143670ustar00rootroot00000000000000The project current primary maintainers with commit access are: Saggi Mizrahi Yaniv Bronheim Dan Kenigsberg Patches have also been contributed by: Vitor de Lima Yoav Kleinberger [....send patches to get your name here....] safelease-1.0/COPYING000066400000000000000000000431221252664234400143470ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. safelease-1.0/Makefile.am000066400000000000000000000015471252664234400153550ustar00rootroot00000000000000# # Copyright 2014 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # SUBDIRS = src EXTRA_DIST = safelease.spec autogen.sh safelease-1.0/README000066400000000000000000000034011252664234400141700ustar00rootroot00000000000000Installation ============ Safelease can be used by following the standard autotools installation process, documented in the INSTALL file. As a quick start you can do ./configure --prefix=/usr --sysconfdir=/etc \ --localstatedir=/var --libdir=/usr/lib make sudo make install Packaging ========= The 'safelease.spec' file demonstrates how to distribute safelease as an RPM package. Getting Help ============ There are two mailing lists for discussions: - For technical discussions about the project and its code base. http://lists.ovirt.org/mailman/listinfo/devel - For questions by users, who do not want to be swamped by technicalities. http://lists.ovirt.org/mailman/listinfo/users The developers also hang out on IRC at #vdsm hosted on freenode.net The latest upstream code can be obtained from GIT: http://gerrit.ovirt.org/p/safelease.git Licensing ========= safelease is provided under the terms of the GNU General Public License, version 2 or later. Please see the COPYING file for complete GPLv2+ license terms. In addition, as a special exception, Red Hat, Inc. and its affiliates give you permission to distribute this program, or a work based on it, linked or combined with the OpenSSL project's OpenSSL library (or a modified version of that library) to the extent that the library, or modified version, is covered by the terms of the OpenSSL or SSLeay licenses. Corresponding source code for the object code form of such a combination shall include source code for the parts of OpenSSL contained in the combination. If you modify this program, you may extend this exception to your version, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. -- End of readme safelease-1.0/autogen.sh000077500000000000000000000014321252664234400153130ustar00rootroot00000000000000#!/bin/sh autoreconf -if if test "x$1" = "x--system"; then shift prefix=/usr libdir=$prefix/lib sysconfdir=/etc localstatedir=/var if [ -d /usr/lib64 ]; then libdir=$prefix/lib64 fi EXTRA_ARGS="--prefix=$prefix --sysconfdir=$sysconfdir --localstatedir=$localstatedir --libdir=$libdir" echo "Running ./configure with $EXTRA_ARGS $@" else if test -z "$*" && test ! -f "$THEDIR/config.status"; then echo "I am going to run ./configure with no arguments - if you wish " echo "to pass any to it, please specify them on the $0 command line." fi fi if test -z "$*" && test -f config.status; then ./config.status --recheck else ./configure $EXTRA_ARGS "$@" fi && { echo echo "Now type 'make' to compile safelease." } safelease-1.0/configure.ac000066400000000000000000000024161252664234400156030ustar00rootroot00000000000000# # Copyright 2014 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # AC_PREREQ([2.69]) AC_INIT([safelease], [1.0], [devel@ovirt.org]) AM_INIT_AUTOMAKE([1.13 foreign -Wall -Werror]) AC_PROG_CC AC_CONFIG_SRCDIR([src/safelease.c]) AC_CONFIG_HEADERS([config.h]) AC_CHECK_HEADERS([fcntl.h stdlib.h string.h sys/time.h unistd.h]) AC_C_INLINE AC_TYPE_OFF_T AC_CHECK_FUNCS([alarm gettimeofday memset strerror strrchr strtoul strtoull]) AC_SUBST([safeleaselibexecdir], ['${libexecdir}/safelease']) AC_CONFIG_FILES([Makefile src/Makefile]) AC_OUTPUT safelease-1.0/safelease.spec000066400000000000000000000036351252664234400161250ustar00rootroot00000000000000Name: safelease Version: 1.0 Release: 5%{?dist} Summary: Legacy locking utility for VDSM Group: System Environment/Libraries License: GPLv2+ URL: http://www.ovirt.org/Safelease Source0: https://bronhaim.fedorapeople.org/%{name}-%{version}.tar.gz BuildRequires: autoconf BuildRequires: automake ## # The following requirements are necessary for VDSM to avoid # platform dependencies. Those are not required by safelease code and should # remove once vdsm will be able to provide those requirements otherwise. # Numactl is not available on s390[x] and ARM %ifnarch s390 s390x %{arm} Requires: numactl %endif %ifarch x86_64 Requires: python-dmidecode Requires: dmidecode %endif ## hack end. %description Safelease is a legacy cluster lock utility used by VDSM. It is based on the algorithm presented in the article "Light-Weight Leases for Storage-Centric Coordination" by G Chockler and D Malkhi. %prep %autosetup -n %{name}-%{version} %build ./autogen.sh %configure make %{?_smp_mflags} %install %make_install %files %doc AUTHORS README %{!?_licensedir:%global license %%doc} %license COPYING %dir %{_libexecdir}/%{name} %{_libexecdir}/%{name}/%{name} %changelog * Sun May 17 2015 Yaniv Bronhaim - 1.0-5 - Adding vdsm hack to require platform depended packages which vdsm needs * Sun Apr 12 2015 Yaniv Bronhaim - 1.0-4 - Adding %%license macro for COPYING * Mon Dec 8 2014 Vitor de Lima - 1.0-3 - Use autotools to build the project - Dropped unused python_ver global - Replaced the %%libname macro with %%name - Included the target directory /usr/lib/safelease in the RPM file list - Included a description of the package * Mon Oct 20 2014 Yaniv Bronhaim - 1.0-2 - Adding URL to pypi and fix semantic issues for official fedora-review * Sun Aug 10 2014 Yoav Kleinberger - 1.0-1 - no changes safelease-1.0/src/000077500000000000000000000000001252664234400141015ustar00rootroot00000000000000safelease-1.0/src/Makefile.am000066400000000000000000000015631252664234400161420ustar00rootroot00000000000000# # Copyright 2014 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # safeleaselibexec_PROGRAMS=safelease safelease_SOURCES=safelease.c safelease-1.0/src/safelease.c000066400000000000000000000413401252664234400161770ustar00rootroot00000000000000/* Copyright (C) 2008-2014 Red Hat, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Refer to the README and COPYING files for full details of the license */ /* Locker */ #define _GNU_SOURCE 1 #include #include #include #include #include #include #include #include #include #include #include #include #define WARN(fmt, args...) warn(__FUNCTION__, fmt, ## args) #define PANIC(fmt, args...) panic(__FUNCTION__, fmt, ## args) #define DEBUG(fmt, args...) do { if (debug) warn(__FUNCTION__, fmt, ## args); } while (0) char *freetag = "------FREE------0000000000000000"; enum { idlen = 16, stamplen = 16, taglen = idlen + stamplen, }; char *progname; int debug; char *id; char *path; char *request; long lease_ms; long op_max_ms; char *iobuf; inline unsigned long long tv2msec(struct timeval *tv); int renew(int fd, off_t offset, char *id, long long *ts); void panic(const char const *fn, char *msg, ...) { char buf[512]; va_list va; int n; va_start(va, msg); n = vsprintf(buf, msg, va); va_end(va); buf[n] = 0; fprintf(stderr, "panic: [%d] %s: %s: (%m)\n", getpid(), fn, buf); exit(-1); } void warn(const char const *fn, char *msg, ...) { struct timeval tv; long long unsigned tscurr; char buf[512]; va_list va; int n; va_start(va, msg); n = vsprintf(buf, msg, va); va_end(va); buf[n] = 0; gettimeofday(&tv, 0); tscurr = tv2msec(&tv); fprintf(stderr, "[%s:%d:%llu]: %s: %s\n", progname, getpid(), tscurr, fn, buf); } void usage(void) { fprintf(stderr, "Usage: %s [ -h ] [...]\n", progname); fprintf(stderr, "Ops:\n" "acquire [ -r ] [ -b ] [ -o offset ] \n" "renew [ -r ] [ -o offset ] [ -t laststamp ] \n" "release [ -f ] [ -o offset ] \n" "query [ -o offset ] \n" "protect [ -r -i ] [ -o offset ] [ ...]\n" ); fprintf(stderr, "\nNotes:\n" "-b - busy loop on lease until lease acquired\n" "-f - force release even if lease id is not equal to id\n" "-o - offset to lease in path (default is 0)\n" "-t - timestamp of last successful renewal\n" "Path is a path to a device or a file to use as a sync object.\n" "Id is an arbitrary unique string\n" "lease_ms is the maximum time in msec that the owner of the lease\n" " may hold it without renewing it\n" "op_max_ms is the maximum time in msec that a single IO operation may take (must be <= lease_ms).\n" "if -r option is used, the path is a readable file/device.\n" " The program then validates that its 'id' is written at the given offset.\n" " If this is not the case, acquire and renew will fail immediately.\n" ); exit(1); } inline unsigned long long tv2msec(struct timeval *tv) { return tv->tv_sec * 1000ull + tv->tv_usec/1000; } int withintimelimits(struct timeval *start, struct timeval *stop) { unsigned long long delta; if (op_max_ms <= 0) return 1; delta = tv2msec(stop) - tv2msec(start); if (delta > op_max_ms) { DEBUG("Error - time limit breached: op_max_ms - %ld, time passed - %lld", op_max_ms, delta); errno = -ETIMEDOUT; return 0; } return 1; } int sametag(const char *tag1, const char *tag2) { return !memcmp(tag1, tag2, taglen); } int isfree(const char *tag) { return sametag(tag, freetag); } void settag(char *tag, const char *src) { memcpy(tag, src, taglen); } void buildtag(char *tag, const char *id, long long ts) { snprintf(tag, taglen+1, "%-*s%0*llx", idlen, id, stamplen, ts); DEBUG("'%s' ts %lld", tag, ts); } int sameid(const char *tag, const char *id) { char _id[idlen+1]; snprintf(_id, idlen+1, "%-*s", idlen, id); return !memcmp(tag, _id, idlen); } void querytag(const char *tag, char *id, long long *ts) { char _stamp[stamplen+1] = ""; memcpy(id, tag, idlen); id[idlen] = 0; memcpy(_stamp, tag+idlen, stamplen); *ts = strtoull(_stamp, 0, 16); } int readtag(int fd, off_t offset, char *tag, int limit) { struct timeval start, stop; int r; DEBUG("fd %d offset %ld", fd, offset); gettimeofday(&start, 0); r = pread(fd, iobuf, 512, offset); gettimeofday(&stop, 0); DEBUG("r %d %m", r); if (r <= 0 || (limit && !withintimelimits(&start, &stop))) return -1; memcpy(tag, iobuf, taglen); return r; } int writetag(int fd, off_t offset, const char *tag, int limit) { struct timeval start, stop; int r; DEBUG("Enter"); memcpy(iobuf, tag, taglen); gettimeofday(&start, 0); r = pwrite(fd, iobuf, 512, offset) < taglen ? -1 : 0; gettimeofday(&stop, 0); DEBUG("Exit r=%ld", r); if (r < 0 || (limit && !withintimelimits(&start, &stop))) return -1; return r; } int writetimestamp(int fd, off_t offset, const char *id, char *tag, long long *ts) { struct timeval tv; long long t; int r; gettimeofday(&tv, 0); t = tv.tv_sec * 1000000ll + tv.tv_usec; buildtag(tag, id, t); r = writetag(fd, offset, tag, 1); if (r > 0) *ts = t; return r; } /* * Attempt to acquire the lease. * Return 1 if succedded, 0 if not , and < 0 on errors. */ int acquire(int fd, off_t offset, char *id, int busyloop, long long *ts) { char curr[taglen+1] = "", last[taglen+1] = "", tag[taglen+1] = ""; long backoff_usec = (lease_ms + 6 * op_max_ms) * 1000; long contend_usec = (2 * op_max_ms) * 1000; char dummyid[idlen+1]; if (readtag(fd, offset, curr, 1) < 0) return -errno; settag(last, freetag); do { DEBUG("restart: curr tag is '%s'", curr); if (!sametag(curr, last) && !isfree(curr)) do { DEBUG("backoff: curr tag is '%s'", curr); settag(last, curr); usleep(backoff_usec); if (readtag(fd, offset, curr, 1) < 0) return -errno; } while (busyloop && !sametag(curr, last) && !isfree(curr)); if (!sametag(curr, last) && !isfree(curr)) { DEBUG("fail: curr tag is '%s'", curr); return 0; } DEBUG("contend: curr tag is '%s'", curr); if (writetimestamp(fd, offset, id, tag, ts) < 0) { DEBUG("lost (writetimestamp failed) : curr tag is %s", curr); return -errno; } usleep(contend_usec); if (readtag(fd, offset, curr, 1) < 0) { DEBUG("lost (readtag failed) : curr tag is %s", curr); return -errno; } } while (busyloop && !sametag(curr, tag)); if (busyloop || sametag(curr, tag)) { DEBUG("won : curr tag is %s", curr); querytag(curr, dummyid, ts); return renew(fd, offset, id, ts); } DEBUG("lost : curr tag is %s\n our tag is %s", curr, tag); return 0; } static void handler(int sig) { PANIC("IO op too long"); } long long timeleft_ms(long long tsprev) { struct timeval tv; long long tscurr; tsprev /= 1000; gettimeofday(&tv, 0); tscurr = tv2msec(&tv); DEBUG("time elapsed: %lld/%lld", tscurr - tsprev, lease_ms); return lease_ms - (tscurr - tsprev); } /* * Attempt to renew the lease. * Return 1 if succeded, 0 if not , and < 0 on errors. */ int renew(int fd, off_t offset, char *id, long long *ts) { char curr[taglen+1] = "", tag[taglen+1] = ""; char dummyid[idlen+1]; struct sigaction sa; long long msleft; int rc = 0; sa.sa_flags = !SA_RESTART; sigemptyset(&sa.sa_mask); sa.sa_handler = handler; if (sigaction(SIGALRM, &sa, NULL) == -1) PANIC("sigaction: can't set alarm"); if (readtag(fd, offset, curr, 0) < 0) { rc = -errno; goto out; } DEBUG("curr tag is '%s'", curr); if (!sameid(curr, id)) { *ts = 0; goto out; } querytag(curr, dummyid, ts); msleft = timeleft_ms(*ts); if (msleft <= 0) { rc = -ETIMEDOUT; goto out; } alarm(msleft / 1000); DEBUG("updating tag: msleft %lld", msleft); if (writetimestamp(fd, offset, id, tag, ts) < 0) { rc = -errno; goto out; } DEBUG("All good"); /* disable the alarm because usleep might use the same signal */ alarm(0); return 1; out: alarm(0); return rc; } /* * Attempt to release the lease. * Return 1 if succedded, 0 if not , and < 0 on errors. */ int release(int fd, off_t offset, char *id, int force) { char curr[taglen+1] = ""; if (!force) { if (readtag(fd, offset, curr, 0) < 0) return -errno; if (!sameid(curr, id)) return 0; } return writetag(fd, offset, freetag, 0) < 0 ? -1 : 1; } /* * Qeury the lease. * Return 1 if succedded, 0 if not , and < 0 on errors. */ int query(int fd, off_t offset) { char curr[taglen+1] = ""; char id[idlen+1] = ""; long long ts; time_t tsec; int tusec; char *t; if (readtag(fd, offset, curr, 0) < 0) return -errno; querytag(curr, id, &ts); tsec = ts / 1000000; tusec = ts % 1000000; t = ctime(&tsec); t[strlen(t)-1] = 0; printf("%s: ID %-*s TS %0*llx (%s, %d usec)\n", sameid(curr, freetag) ? "FREE" : "LOCKED", idlen, id, stamplen, ts, t, tusec); return 1; } void validate_path(const char *path) { if (access(path, R_OK | W_OK) < 0) PANIC("can't access '%s'", path); } void validate_id(const char *id) { if (strlen(id) > idlen) PANIC("id must be <= 8 characters"); if (!strncmp(id, freetag, idlen)) PANIC("can't lease free stamp"); } void validate_lease_params(int lease_ms, int op_max_ms) { if (lease_ms <= 0 || op_max_ms <= 0 || lease_ms < op_max_ms || op_max_ms < 1000 || op_max_ms % 1000 != 0) PANIC("bad lease/op max timeouts"); } /* * Initialize the timeout to one op_max_ms. */ long long renew_timeout(void) { struct timeval tv; gettimeofday(&tv, 0); return tv.tv_sec * 1000000ull + tv.tv_usec - (lease_ms - op_max_ms) * 1000; } int cmd_acquire(int argc, char **argv) { int opt, fd, r, b = 0; off_t offset = 0; long long ts; optind = 0; while ((opt = getopt(argc, argv, "+hdr:bo:")) != -1) { switch (opt) { case 'h': usage(); break; case 'd': debug++; break; case 'r': request = optarg; break; case 'b': b = 1; break; case 'o': offset = strtoul(optarg, 0, 0); break; } } if (argc - optind < 4) usage(); path = argv[optind++]; validate_path(path); id = argv[optind++]; validate_id(id); lease_ms = strtoul(argv[optind++], 0, 0); op_max_ms = strtoul(argv[optind++], 0, 0); validate_lease_params(lease_ms, op_max_ms); DEBUG("path '%s' offset %ld id '%s' lease_ms %ld op_max_ms %ld", path, offset, id, lease_ms, op_max_ms); if ((fd = open(path, O_RDWR | O_DIRECT)) < 0) panic("can't open '%s'", path); r = acquire(fd, offset, id, b, &ts); close(fd); if (r == 1) { /* print last successful timestamp == aquire time */ printf("%lld", ts); DEBUG("Succeeded"); return 0; } else DEBUG("%s (%s)", "Failed", strerror(r)); return 1; } int cmd_renew(int argc, char **argv) { long long ts = renew_timeout(); off_t offset = 0; int opt, fd, r; optind = 0; while ((opt = getopt(argc, argv, "+hdr:o:t:")) != -1) { switch (opt) { case 'h': usage(); break; case 'd': debug++; break; case 'r': request = optarg; break; case 'o': offset = strtoul(optarg, 0, 0); break; case 't': ts = strtoll(optarg, 0, 0); break; } } if (argc - optind < 4) usage(); path = argv[optind++]; validate_path(path); id = argv[optind++]; validate_id(id); lease_ms = strtoul(argv[optind++], 0, 0); op_max_ms = strtoul(argv[optind++], 0, 0); validate_lease_params(lease_ms, op_max_ms); DEBUG("path '%s' offset %ld id '%s' lease_ms %ld op_max_ms %ld", path, offset, id, lease_ms, op_max_ms); if ((fd = open(path, O_RDWR | O_DIRECT)) < 0) panic("can't open '%s'", path); r = renew(fd, offset, id, &ts); close(fd); /* print out the last successful renewal timestamp, or zero for don't renew */ printf("%lld\n", ts); if (r == 1) { DEBUG("Succeeded"); return 0; } DEBUG("%s (%s)", "Failed", strerror(r)); return 1; } int cmd_release(int argc, char **argv) { int opt, fd, r; int force = 0; off_t offset = 0; optind = 0; while ((opt = getopt(argc, argv, "+hdfo:")) != -1) { switch (opt) { case 'h': usage(); break; case 'd': debug++; break; case 'f': force++; break; case 'o': offset = strtoul(optarg, 0, 0); break; } } if (argc - optind < 2) usage(); path = argv[optind++]; validate_path(path); id = argv[optind++]; validate_id(id); DEBUG("path '%s' offset %ld id '%s' force %d", path, offset, id, force); if ((fd = open(path, O_RDWR | O_DIRECT)) < 0) panic("can't open '%s'", path); r = release(fd, offset, id, force); close(fd); if (r == 1) { DEBUG("Succeeded"); return 0; } else DEBUG("%s (%s)", "Failed", strerror(r)); return 1; } int cmd_query(int argc, char **argv) { int opt, fd, r; off_t offset = 0; optind = 0; while ((opt = getopt(argc, argv, "+hdr:o:")) != -1) { switch (opt) { case 'h': usage(); break; case 'd': debug++; break; case 'r': request = optarg; break; case 'o': offset = strtoul(optarg, 0, 0); break; } } if (argc - optind < 4) usage(); path = argv[optind++]; validate_path(path); DEBUG("path '%s' offset %ld id '%s'", path, offset, id); if ((fd = open(path, O_RDWR | O_DIRECT)) < 0) panic("can't open '%s'", path); r = query(fd, offset); close(fd); if (r == 1) { DEBUG("Succeeded"); return 0; } else DEBUG("%s (%s)", "Failed", strerror(r)); return 1; } int cmd_protect(int argc, char **argv) { return 0; } void sig_handler(int sig) { fprintf(stderr, "%s: Exiting due to signal %d\n", progname, sig); exit(0); } int main(int argc, char **argv) { int opt; void *v = 0; signal(SIGTERM, sig_handler); signal(SIGINT, sig_handler); signal(SIGTRAP, sig_handler); if (posix_memalign(&v, 4096, 512) != 0) { fprintf(stderr, "fatal memory allocation error\n"); return 1; } iobuf = v; memset(iobuf, 0, 512); progname = strrchr(argv[0], '/'); if (!progname) progname = argv[0]; else progname++; while ((opt = getopt(argc, argv, "+hd")) != -1) { switch (opt) { case 'h': usage(); break; case 'd': debug++; break; } } if (optind >= argc) usage(); if (!strcmp(argv[optind], "acquire")) return cmd_acquire(argc - optind, argv + optind); if (!strcmp(argv[optind], "renew")) return cmd_renew(argc - optind, argv + optind); if (!strcmp(argv[optind], "release")) return cmd_release(argc - optind, argv + optind); if (!strcmp(argv[optind], "query")) return cmd_query(argc - optind, argv + optind); if (!strcmp(argv[optind], "protect")) return cmd_protect(argc - optind, argv + optind); fprintf(stderr, "unknonwn op <%s>\n", argv[optind]); usage(); return 1; }