pax_global_header00006660000000000000000000000064126213760400014513gustar00rootroot0000000000000052 comment=6db666bd8f102fec1b457180c05685446c40b223 tuptime-3.2.01+git6db666b/000077500000000000000000000000001262137604000150445ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/LICENSE000066400000000000000000000431771262137604000160650ustar00rootroot00000000000000 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 Lesser 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. {description} Copyright (C) {year} {fullname} 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. {signature of Ty Coon}, 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 Lesser General Public License instead of this License. tuptime-3.2.01+git6db666b/README.md000066400000000000000000000067511262137604000163340ustar00rootroot00000000000000tuptime ======= Tuptime is a tool for report the historical and statistical running time of the system, keeping it between restarts. Like uptime command but with more interesting output. ### Basic Installation and usage In a Linux, FreeBSD or OSX system... Clone the repo: git clone https://github.com/rfrail3/tuptime.git Copy the "tuptime" file located under "latest/" directory to "/usr/bin/" and make it executable: cp tuptime/latest/tuptime /usr/bin/tuptime chmod ugo+x /usr/bin/tuptime Assure that the system pass the prerequisites: python 2.7 or 3.X Run first with a privileged user: tuptime And you will get some similar to this: System startups: 1 since 21:54:09 24/09/15 System shutdowns: 0 ok - 0 bad System uptime: 100.0 % - 21 minutes and 30 seconds System downtime: 0.0 % - 0 seconds System life: 21 minutes and 30 seconds Largest uptime: 21 minutes and 30 seconds from 21:54:09 24/09/15 Shortest uptime: 21 minutes and 30 seconds from 21:54:09 24/09/15 Average uptime: 21 minutes and 30 seconds Largest downtime: 0 seconds Shortest downtime: 0 seconds Average downtime: 0 seconds Current uptime: 21 minutes and 30 seconds since 21:54:09 24/09/15 If you do the same a few days after, the output may will be more similar to this: System startups: 110 since 10:15:27 08/08/15 System shutdowns: 107 ok - 2 bad System uptime: 4.04 % - 1 days, 22 hours, 4 minutes and 44 seconds System downtime: 95.96 % - 45 days, 13 hours, 57 minutes and 30 seconds System life: 47 days, 12 hours, 2 minutes and 15 seconds Largest uptime: 2 hours, 10 minutes and 44 seconds from 20:49:17 09/08/15 Shortest uptime: 9 seconds from 10:23:36 08/08/15 Average uptime: 25 minutes and 8 seconds Largest downtime: 7 days, 10 hours, 17 minutes and 26 seconds from 06:09:45 10/08/15 Shortest downtime: 15 seconds from 19:27:24 19/09/15 Average downtime: 9 hours, 56 minutes and 42 seconds Current uptime: 23 minutes and 33 seconds since 21:54:09 24/09/15 Or this, with -t | --table option: No. Startup Date Uptime Shutdown Date End Downtime 1 10:15:27 08/08/15 42 seconds 10:16:09 08/08/15 OK 16 seconds 2 10:16:26 08/08/15 49 seconds 10:17:15 08/08/15 OK 16 seconds 3 10:17:32 08/08/15 5 minutes and 47 seconds 10:23:19 08/08/15 OK 16 seconds 4 10:23:36 08/08/15 9 seconds 10:23:45 08/08/15 BAD 42 seconds 5 10:24:28 08/08/15 2 hours, 9 minutes and 27 seconds 12:33:55 08/08/15 OK 41 minutes and 44 seconds . . . Or this, with -l | --list option: Startup: 1 at 10:15:27 08/08/15 Uptime: 42 seconds Shutdown: OK at 10:16:09 08/08/15 Downtime: 16 seconds Startup: 2 at 10:16:26 08/08/15 Uptime: 49 seconds Shutdown: OK at 10:17:15 08/08/15 Downtime: 16 seconds Startup: 3 at 10:17:32 08/08/15 Uptime: 5 minutes and 47 seconds Shutdown: OK at 10:23:19 08/08/15 Downtime: 16 seconds . . . Don't forget! For keep it updated, add it to the init system and to the cron service. (Scripts/Units/Files provided inside this repo) ### More information Please, read tuptime-manual.txt for a complete reference guide. tuptime-3.2.01+git6db666b/freebsd-port/000077500000000000000000000000001262137604000174405ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/freebsd-port/Makefile000066400000000000000000000020261262137604000211000ustar00rootroot00000000000000# Created by: Jeremy Johnston # $FreeBSD$ PORTNAME= tuptime DISTVERSIONPREFIX= v DISTVERSION= 3.2.01 CATEGORIES= sysutils MAINTAINER= jeremy@smart-serv.net COMMENT= Historical and statistical system running time report tool LICENSE= GPLv2 RUN_DEPENDS= ${PYTHON_PKGNAMEPREFIX}sqlite3>=2.7:${PORTSDIR}/databases/py-sqlite3 USES= python:run shebangfix USE_GITHUB= yes GH_ACCOUNT= rfrail3 NO_BUILD= yes USE_RC_SUBR= ${PORTNAME} SHEBANG_FILES= ${WRKSRC}/latest/tuptime ${WRKSRC}/scripts/* SUB_FILES= pkg-message PLIST_FILES= bin/tuptime \ ${EXAMPLESDIR}/db-tuptime-migrate.sh \ ${EXAMPLESDIR}/db-tuptime-migrate-3.0-to-3.1.sh do-install: @${MKDIR} ${STAGEDIR}${EXAMPLESDIR} ${INSTALL_SCRIPT} ${WRKSRC}/latest/tuptime ${STAGEDIR}${PREFIX}/bin/tuptime ${INSTALL_SCRIPT} ${WRKSRC}/scripts/db-tuptime-migrate.sh ${STAGEDIR}${EXAMPLESDIR}/db-tuptime-migrate.sh ${INSTALL_SCRIPT} ${WRKSRC}/scripts/db-tuptime-migrate-3.0-to-3.1.sh ${STAGEDIR}${EXAMPLESDIR}/db-tuptime-migrate-3.0-to-3.1.sh .include tuptime-3.2.01+git6db666b/freebsd-port/distinfo000066400000000000000000000002411262137604000211770ustar00rootroot00000000000000SHA256 (rfrail3-tuptime-v3.2.01_GH0.tar.gz) = 330fbb7f9163fd1ec1c139a3e7652f86ddd2987f3e94e3b481f1a3f3e3da64c2 SIZE (rfrail3-tuptime-v3.2.01_GH0.tar.gz) = 51114 tuptime-3.2.01+git6db666b/freebsd-port/files/000077500000000000000000000000001262137604000205425ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/freebsd-port/files/pkg-message.in000066400000000000000000000006571262137604000233050ustar00rootroot00000000000000====================================================================== tuptime requires the following be added to /etc/crontab: */5 * * * * root %%PREFIX%%/bin/tuptime -x > /dev/null If you are upgrading from an older version you need to run the following scripts: %%EXAMPLESDIR%%/db-tuptime-migrate.sh %%EXAMPLESDIR%%/db-tuptime-migrate-3.0-to-3.1.sh ====================================================================== tuptime-3.2.01+git6db666b/freebsd-port/files/tuptime.in000066400000000000000000000005601262137604000225620ustar00rootroot00000000000000#!/bin/sh # # PROVIDE: tuptime # KEYWORD: nojail shutdown . /etc/rc.subr name="tuptime" rcvar=tuptime_enable command="%%PREFIX%%/bin/tuptime" start_cmd="${name}_start" stop_cmd="${name}_stop" tuptime_start() { command_args="-x" $command $command_args } tuptime_stop() { command_args="-xg" $command $command_args } load_rc_config $name run_rc_command "$1" tuptime-3.2.01+git6db666b/freebsd-port/pkg-descr000066400000000000000000000003241262137604000212410ustar00rootroot00000000000000Tuptime is a tool for report the historical and statistical running time of the system, keeping it between restarts. Like uptime command but with more interesting output. WWW: https://github.com/rfrail3/tuptime tuptime-3.2.01+git6db666b/latest/000077500000000000000000000000001262137604000163405ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/latest/cron.d/000077500000000000000000000000001262137604000175235ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/latest/cron.d/tuptime000066400000000000000000000004761262137604000211440ustar00rootroot00000000000000# /etc/cron.d/tuptime: crontab entrie for tuptime update. # Execute tuptime each hour for avoid loss time if system don't shutdown correctly. # NOTE: Decrease the execution time for increase the accuracity. MAILTO=root */5 * * * * root if [ -x /usr/bin/tuptime ]; then /usr/bin/tuptime -x > /dev/null; fi tuptime-3.2.01+git6db666b/latest/init.d/000077500000000000000000000000001262137604000175255ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/latest/init.d/tuptime.init.d-debian7000077500000000000000000000035541262137604000236440ustar00rootroot00000000000000#!/bin/sh # tuptime - Report the historical and statistical running time of the system, keeping it between restarts. # Copyright (C) 2015 - Ricardo F. # 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, see . # ### BEGIN INIT INFO # Provides: tuptime # Required-Start: $local_fs $time # Required-Stop: $local_fs $time # Should-Start: # Default-Start: 1 2 3 4 5 # Default-Stop: 0 6 # Short-Description: Start tuptime at boot time # Description: Update tuptime. ### END INIT INFO PATH=/sbin:/usr/sbin:/bin:/usr/bin . /lib/init/vars.sh . /lib/lsb/init-functions F_BIN='tuptime' SERVC="/usr/bin/$F_BIN" do_start () { # Start service log_action_begin_msg "Starting $F_BIN" log_end_msg 0 $SERVC -x > /dev/null } do_stop () { # Stop service log_action_begin_msg "Stopping $F_BIN" log_end_msg 0 $SERVC -xg > /dev/null } do_status () { # Status service $SERVC } case "$1" in start|"") do_start ;; restart) log_action_begin_msg "Restarting $F_BIN" log_end_msg 0 do_stop do_start ;; stop) do_stop ;; status) do_status exit $? ;; *) echo "Usage: $F_BIN [start|stop|restart|status]" >&2 exit 3 ;; esac tuptime-3.2.01+git6db666b/latest/init.d/tuptime.init.d-redhat6000077500000000000000000000025551262137604000236700ustar00rootroot00000000000000#!/bin/sh # # tuptime - Historical and statistical running time of the system. # # chkconfig: 12345 25 90 # description: Report the historical and statistical running time \ # of the system, keeping it between restarts. ### BEGIN INIT INFO # Provides: tuptime # Required-Start: $local_fs $time # Required-Stop: $local_fs $time # Short-Description: start and stop tuptime # Description: Report the historical and statistical running time # of the system, keeping it between restarts. ### END INIT INFO # Source function library. . /etc/rc.d/init.d/functions F_BIN='tuptime' SERVC="/usr/bin/$F_BIN" lockfile="/var/lock/subsys/$F_BIN" do_start () { # Start service echo -n $"Starting tuptime: " daemon $SERVC -x retval=$? echo [ $retval -eq 0 ] && touch ${lockfile} return $retval } do_stop () { # Stop service echo -n $"Stopping tuptime: " daemon $SERVC -xg $SERVC -xg retval=$? echo [ $RETVAL = 0 ] && rm -f ${lockfile} } do_status () { # Status service $SERVC } case "$1" in start|"") do_start ;; restart) do_stop do_start ;; stop) do_stop ;; status) do_status exit $? ;; *) echo "Usage: $F_BIN [start|stop|restart|status]" >&2 exit 3 ;; esac tuptime-3.2.01+git6db666b/latest/rc.d/000077500000000000000000000000001262137604000171665ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/latest/rc.d/tuptime-freebsd000077500000000000000000000005531262137604000222160ustar00rootroot00000000000000#!/bin/sh # # PROVIDE: tuptime # KEYWORD: nojail shutdown . /etc/rc.subr name="tuptime" rcvar=tuptime_enable start_cmd="${name}_start" stop_cmd="${name}_stop" export PATH=$PATH:/usr/local/bin/ tuptime_start() { command_args="-x" $name $command_args } tuptime_stop() { command_args="-xg" $name $command_args } load_rc_config $name run_rc_command "$1" tuptime-3.2.01+git6db666b/latest/systemd/000077500000000000000000000000001262137604000200305ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/latest/systemd/tuptime.service000066400000000000000000000002671262137604000231060ustar00rootroot00000000000000[Unit] Description=Tuptime service [Service] Type=oneshot User=root RemainAfterExit=true ExecStart=/usr/bin/tuptime -x ExecStop=/usr/bin/tuptime -xg [Install] WantedBy=basic.target tuptime-3.2.01+git6db666b/latest/tuptime000077500000000000000000000514251262137604000177640ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # tuptime - Report the historical and statistical running time of the system, keeping it between restarts. # Copyright (C) 2011-2015 - Ricardo F. # 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, see . try: import sys, os, optparse, locale, platform, subprocess, time, sqlite3 from datetime import datetime except Exception as e: sys.exit('ERROR modules are not imported correctly: ' + str(e)) version = '3.2.10' def_db_file = '/var/lib/tuptime/tuptime.db' def_seconds = False locale.setlocale(locale.LC_ALL, '') def_date_format = '%X %x' dec = int(2) # Decimals for percentage output dec_av = int(2) # Decimals for average output def vprint(*args): """Print verbose information""" if opt.verbose: for arg in args: sys.stdout.write(str(arg)) print('') def maxwidth(table, index): """Get the maximum width of the given column index""" return max([len(str(row[index])) for row in table]) def time_conv(secs): """Convert seconds to human readable syle""" try: if secs == 0: return '0 seconds' secs = round(secs, 0) # Rounded to 0 in human style tm = {'years': int(0), 'days': int(0), 'hours': int(0), 'minutes': int(0), 'seconds': int(0)} tm_tuple = ('years', 'days', 'hours', 'minutes', 'seconds') zero_enter = True human_tm = '' tm['minutes'], tm['seconds'] = divmod(secs, 60) tm['hours'], tm['minutes'] = divmod(tm['minutes'], 60) tm['days'], tm['hours'] = divmod(tm['hours'], 24) tm['years'], tm['days'] = divmod(tm['days'], 365) for key in tm_tuple: # Avoid print empty values at the beginning if (tm[key] == 0) and zero_enter: continue else: if (int(tm[key])) == 1: # Not plural for 1 unit human_tm += str(int(tm[key]))+' '+str(key[:-1]) + ', ' else: human_tm += str(int(tm[key]))+' '+str(key) + ', ' zero_enter = False # Nice sentence end, remove comma if human_tm.find('minutes, ') or human_tm.find('minute, '): human_tm = human_tm.replace('minutes, ', 'minutes and ') human_tm = human_tm.replace('minute, ', 'minute and ') return str(human_tm[:-2]) # return without last comma and space chareacter except Exception as e: sys.exit('ERROR converting seconds: '+ str(e)) def rows_to_dict(db_rows): """Create dictionary from database rows""" keys_dict = ('startup', 'btime', 'uptime', 'offbtime', 'endst', 'downtime', 'kernel') row_dict = [] for db_row_value in db_rows: row_dict.append(dict(zip(keys_dict, db_row_value))) return row_dict def main(): global opt parser = optparse.OptionParser() parser.add_option( '-c', '--ckernel', dest='ckernel', action='store_true', default=False, help='classify / order by kernel' ) parser.add_option( '-d', '--date', dest='date_format', default=def_date_format, action='store', help='date format output' ) parser.add_option( '-e', '--end', dest='end', default=False, action='store_true', help='order by end state' ) parser.add_option( '-f', '--filedb', dest='db_file', default=def_db_file, action='store', help='database file', metavar='FILE' ) parser.add_option( '-g', '--graceful', dest='endst', action='store_const', default='0', const='1', help='register a gracefully shutdown' ) parser.add_option( '-k', '--kernel', dest='kernel', action='store_true', default=False, help='print kernel information' ) parser.add_option( '-l', '--list', dest='lst', default=False, action='store_true', help='enumerate system life as list' ) parser.add_option( '-o', '--offtime', dest='downtime', default=False, action='store_true', help='order by offtime / downtime' ) parser.add_option( '-r', '--reverse', dest='reverse', default=False, action='store_true', help='reverse order' ) parser.add_option( '-s', '--seconds', dest='seconds', default=def_seconds, action='store_true', help='output time in seconds and epoch' ) parser.add_option( '-t', '--table', dest='table', default=False, action='store_true', help='enumerate system life as table' ) parser.add_option( '-u', '--uptime', dest='uptime', default=False, action='store_true', help='order by uptime' ) parser.add_option( '-v', '--verbose', dest='verbose', default=False, action='store_true', help='verbose output' ) parser.add_option( '-V', '--version', dest='version', default=False, action='store_true', help='show version' ) parser.add_option( '-x', '--silent', dest='silent', default=False, action='store_true', help='update values into db without output' ) opt, _ = parser.parse_args() if opt.version: print ('tuptime version ' + version) sys.exit(0) # - Check requirements of combination of operators if opt.reverse or opt.uptime or opt.end or opt.downtime or opt.ckernel: if opt.ckernel: if not opt.kernel: sys.exit('ERROR used operator must be combined with [-k|--kernel]') if not opt.table and not opt.lst: sys.exit('ERROR used operators must be combined with [-t|--table] or [-l|--list]') # - Swich for running in FreeBSD, Darwin (MacOSX) or Linux platform_env = platform.system() if platform_env in ('FreeBSD', 'Darwin'): try: if platform_env == 'FreeBSD': sysctl_bin = '/sbin/sysctl' if platform_env == 'Darwin': sysctl_bin = '/usr/sbin/sysctl' sysctl = subprocess.check_output([sysctl_bin, 'kern.boottime']); sec = sysctl.split()[4].replace(',', '') btime = int(sec) uptime = round(float((time.time() - btime)), 2) vprint('uptime = ' + str(uptime)) vprint('btime = ' + str(btime)) except Exception as e: sys.exit('ERROR reading BSD sysctl ' + str(e)) else: procfs = "/proc" try: with open(procfs + '/uptime') as fl: uptime = float(fl.readline().split()[0]) vprint(procfs + '/uptime = ' + str(uptime)) except Exception as e: sys.exit('ERROR reading ' + procfs + '/uptime'+ str(e)) try: with open(procfs + '/stat') as fl: for line in fl: if line.startswith('btime'): btime = int(line.split()[1]) vprint(procfs + '/stat btime = ' + str(btime)) except Exception as e: sys.exit('ERROR reading Linux ' + procfs + '/stat'+ str(e)) kernel = platform.platform() try: # - Assure state of db file if os.path.isdir(os.path.dirname(opt.db_file)): vprint('Directory exists = ', os.path.dirname(opt.db_file)) else: vprint('Creating directory = ', opt.db_file) os.makedirs(os.path.dirname(opt.db_file)) if os.path.isfile(opt.db_file): vprint('DB file exists = ', opt.db_file) else: vprint('Creating DB file = ', opt.db_file) db = sqlite3.connect(opt.db_file) conn = db.cursor() conn.execute('create table if not exists tuptime(btime integer, uptime real, offbtime integer, endst integer, downtime real, kernel text)') conn.execute('insert into tuptime values (?,?,?,?,?,?)', (str(btime), str(uptime), str('-1'), str(opt.endst), str('-1'), str(kernel))) db.commit() db.close() except Exception as e: sys.exit('ERROR creating db file: '+ str(e)) try: db = sqlite3.connect(opt.db_file) conn = db.cursor() except Exception as e: sys.exit('ERROR connecting db: '+ str(e)) try: # - Reading last btime and uptime registered in db conn.execute('select btime, uptime from tuptime where oid = (select max(oid) from tuptime)') last_btime, last_uptime = conn.fetchone() vprint('Last btime from db = ', last_btime) vprint('Last uptime from db = ', str(last_uptime)) lasts = last_uptime + last_btime except Exception as e: sys.exit('ERROR reading from db: '+ str(e)) # - Test if system was resterted # How tuptime do it: # Checking if last_btime saved into db plus uptime is lower than actual btime # # In some particular cases the btime value from /proc/stat may change. Testing only last_btime vs # actual btime can produce a false endst register. # Usually happend on virtualized enviroments, servers with high load or when ntp are running. # Related to kernel system clock frequency, computation of jiffies / HZ and the problem of lost ticks. # More info in Debian bug 119971 and rfc1589 # # For avoid problems with extreme corner cases, please be sure that the init/systemd script and cron # line works as expected. A uptime record can be lost if tuptime is executed, at first time after boot, # when the uptime is greater than the difference between btime - last_btime. try: if (last_btime + uptime) < btime: vprint('System was restarted') offbtime_db = int(round(lasts, 0)) downtime_db = round((btime - lasts), 2) vprint('Recording offbtime into db = ', str(offbtime_db)) vprint('Recording downtime into db = ', str(downtime_db)) # Save downtimes for previous boot conn.execute('update tuptime set offbtime = '+ str(offbtime_db) +', downtime = '+ str(downtime_db) +' where oid = (select max(oid) from tuptime)') # Create entry for new boot conn.execute('insert into tuptime values (?,?,?,?,?,?)', (str(btime), str(uptime), str('-1'), str(opt.endst), str('-1'), str(kernel))) else: vprint('System wasn\'t restarted. Updating db values...') conn.execute('update tuptime set uptime = '+ str(uptime) +', endst = '+ str(opt.endst) +', kernel = \''+ str(kernel) +'\' where oid = (select max(oid) from tuptime)') except Exception as e: if type(e).__name__ == 'OperationalError': vprint('WARNING values not saved into db - Test file permissions') vprint('WARNING ', str(e)) if (last_btime + uptime) < btime: # If you see this error, maybe systemd script isn't executed at startup # or the db file (def_db_file) have wrong permissions. sys.exit('ERROR After system restart, the values must be saved into db. Please, execute tuptime with a privileged user.') if not opt.silent: # - Get all rows and correct last for cover outdate db if the user can only read it conn.execute('select oid, * from tuptime') db_rows = conn.fetchall() db_rows[-1] = list(db_rows[-1]) db_rows[-1][2] = uptime db_rows[-1][4] = opt.endst db_rows[-1][6] = kernel db_rows[-1] = tuple(db_rows[-1]) startups = len(db_rows) startups_num = db_rows[-1][0] if startups != startups_num: vprint('WARNING real startups are not equal to enumerate startups - possible deleted rows in db') try: db.commit() db.close() except Exception as e: sys.exit('ERROR closing db connection: '+ str(e)) if opt.silent: vprint('Only update') elif opt.lst or opt.table: lst = [] # Initialize list tbl = [] # Initialize table plus its header tbl.append(['No.', 'Startup Date', 'Uptime', 'Shutdown Date', 'End', 'Downtime', 'Kernel']) tbl.append([''] * len(tbl[0])) if opt.uptime or opt.downtime or opt.end or opt.ckernel: # In the case of multiple matches the order is: uptime > end > downtime > kernel key_lst = [] opt.reverse = not opt.reverse if opt.uptime: key_lst.append(2) if opt.end: key_lst.append(4) if opt.downtime: key_lst.append(5) if opt.ckernel: key_lst.append(6) db_rows = sorted(db_rows, key=lambda x: tuple(x[i] for i in key_lst), reverse=opt.reverse) else: if opt.reverse: db_rows = list(reversed(db_rows)) for row_dict in rows_to_dict(db_rows): # vprint('Processing row: '+ str(row_dict)) if row_dict['endst'] == 1: row_dict['endst'] = 'OK' else: row_dict['endst'] = 'BAD' if not opt.seconds: # Human readable style row_dict['btime'] = datetime.fromtimestamp(row_dict['btime']).strftime(opt.date_format) row_dict['uptime'] = time_conv(row_dict['uptime']) row_dict['offbtime'] = datetime.fromtimestamp(row_dict['offbtime']).strftime(opt.date_format) row_dict['downtime'] = time_conv(row_dict['downtime']) if opt.lst: # Fill list lst.append('Startup: ' + str(row_dict['startup']) + ' at '+ str(row_dict['btime'])) if row_dict['startup'] == startups_num: lst.append('Uptime: ' + str(row_dict['uptime'])) else: lst.append('Uptime: ' + str(row_dict['uptime'])) lst.append('Shutdown: ' + str(row_dict['endst']) + ' at '+ str(row_dict['offbtime'])) lst.append('Downtime: ' + str(row_dict['downtime'])) if opt.kernel: lst.append('Kernel: ' + str(row_dict['kernel'])) lst.append('') if opt.table: # Fill table if row_dict['startup'] == startups_num: tbl.append([str(row_dict['startup']), str(row_dict['btime']), str(row_dict['uptime']), str(''), str(''), str(''), str(row_dict['kernel'])]) else: tbl.append([str(row_dict['startup']), str(row_dict['btime']), str(row_dict['uptime']), str(row_dict['offbtime']), str(row_dict['endst']), str(row_dict['downtime']), str(row_dict['kernel'])]) # - Print list if opt.lst: for l in lst: print(l) # - Print table if opt.table: colpad = [] side_spaces = 3 if not opt.kernel: # Delete kernel if is not used tbl_no_kern = [] for x in tbl: del x[-1] tbl_no_kern.append(x) tbl = tbl_no_kern for i in range(len(tbl[0])): colpad.append(maxwidth(tbl, i)) for row in tbl: sys.stdout.write(str(row[0]).ljust(colpad[0])) for i in range(1, len(row)): col = str(row[i]).rjust(colpad[i] + side_spaces) sys.stdout.write(str(''+ col)) print ('') else: # - Calculate values row_dict = rows_to_dict(db_rows) total_uptime = 0 bad_shdown = 0 kernel_cnt = [] for row in row_dict: total_uptime += row['uptime'] if row['endst'] == 0 and row['startup'] != startups_num: bad_shdown += 1 kernel_cnt.append(row['kernel']) kernel_cnt = len(set(kernel_cnt)) first_btime = int(row_dict[0]['btime']) ok_shdown = startups - bad_shdown - 1 sys_life = round(((btime + uptime) - first_btime), 2) average_up = round((total_uptime / startups), dec_av) uprate = round((total_uptime * 100) / (sys_life), dec) if startups == 1: total_downtime = 0 else: total_downtime = round((sys_life - total_uptime), 2) downrate = round((total_downtime * 100) / (sys_life), dec) average_down = round((total_downtime / startups), dec_av) larg_up_uptime_row = max(row_dict, key=lambda x: x['uptime']) larg_up_uptime, larg_up_btime, larg_up_kern = larg_up_uptime_row['uptime'], larg_up_uptime_row['btime'], larg_up_uptime_row['kernel'] shrt_up_uptime_row = min(row_dict, key=lambda x: x['uptime']) shrt_up_uptime, shrt_up_btime, shrt_up_kern = shrt_up_uptime_row['uptime'], shrt_up_uptime_row['btime'], shrt_up_uptime_row['kernel'] if startups > 1: larg_down_downtime_row = max(row_dict[:-1], key=lambda x: x['downtime']) larg_down_downtime, larg_down_offbtime, larg_down_kern = larg_down_downtime_row['downtime'], larg_down_downtime_row['offbtime'], larg_down_downtime_row['kernel'] shrt_down_downtime_row = min(row_dict[:-1], key=lambda x: x['downtime']) shrt_down_downtime, shrt_down_offbtime, shrt_down_kern = shrt_down_downtime_row['downtime'], shrt_down_downtime_row['offbtime'], shrt_down_downtime_row['kernel'] else: larg_down_downtime = 0; larg_down_offbtime = 0; larg_down_kern = None shrt_down_downtime = 0; shrt_down_offbtime = 0; shrt_down_kern = None if not opt.seconds: # - Human readable style first_btime = datetime.fromtimestamp(first_btime).strftime(opt.date_format) larg_up_uptime = time_conv(larg_up_uptime) larg_up_btime = datetime.fromtimestamp(larg_up_btime).strftime(opt.date_format) average_up = time_conv(average_up) shrt_up_uptime = time_conv(shrt_up_uptime) shrt_up_btime = datetime.fromtimestamp(shrt_up_btime).strftime(opt.date_format) larg_down_downtime = time_conv(larg_down_downtime) larg_down_offbtime = datetime.fromtimestamp(larg_down_offbtime).strftime(opt.date_format) average_down = time_conv(average_down) shrt_down_downtime = time_conv(shrt_down_downtime) shrt_down_offbtime = datetime.fromtimestamp(shrt_down_offbtime).strftime(opt.date_format) uptime = time_conv(uptime) btime = datetime.fromtimestamp(btime).strftime(opt.date_format) total_uptime = time_conv(total_uptime) total_downtime = time_conv(total_downtime) sys_life = time_conv(sys_life) print('System startups:\t' + str(startups) + ' since ' + str(first_btime)) print('System shutdowns:\t' + str(ok_shdown) + ' ok - ' + str(bad_shdown) + ' bad') print('System uptime: \t\t' + str(uprate) + ' % - ' + str(total_uptime)) print('System downtime: \t' + str(downrate) + ' % - ' + str(total_downtime)) print('System life: \t\t' + str(sys_life)) if opt.kernel: print('System kernels: \t' + str(kernel_cnt)) print('') print('Largest uptime:\t\t'+ str(larg_up_uptime) + ' from ' + str(larg_up_btime)) if opt.kernel: print('...with kernel: \t'+ str(larg_up_kern)) print('Shortest uptime:\t'+ str(shrt_up_uptime) + ' from ' + str(shrt_up_btime)) if opt.kernel: print('...with kernel: \t'+ str(shrt_up_kern)) print('Average uptime: \t' + str(average_up)) print('') if startups == 1: print('Largest downtime:\t'+ str(larg_down_downtime)) if opt.kernel: print('...with kernel: \t'+ str(larg_down_kern)) print('Shortest downtime:\t'+ str(shrt_down_downtime)) if opt.kernel: print('...with kernel: \t'+ str(shrt_down_kern)) else: print('Largest downtime:\t'+ str(larg_down_downtime) + ' from ' + str(larg_down_offbtime)) if opt.kernel: print('...with kernel: \t'+ str(larg_down_kern)) print('Shortest downtime:\t'+ str(shrt_down_downtime) + ' from ' + str(shrt_down_offbtime)) if opt.kernel: print('...with kernel: \t'+ str(shrt_down_kern)) print('Average downtime: \t' + str(average_down)) print('') print('Current uptime: \t' + str(uptime) + ' since ' + str(btime)) if opt.kernel: print('...with kernel: \t'+ str(kernel)) if __name__ == "__main__": main() tuptime-3.2.01+git6db666b/scripts/000077500000000000000000000000001262137604000165335ustar00rootroot00000000000000tuptime-3.2.01+git6db666b/scripts/db-tuptime-migrate-3.0-to-3.1.sh000066400000000000000000000034601262137604000240070ustar00rootroot00000000000000#!/bin/bash # This script update the tuptime database format from version 3.0.00 to 3.1.00 # Change the db origin: # btime integer, uptime real, offbtime integer, endst integer, downtime real # to: # btime integer, uptime real, offbtime integer, endst integer, downtime real, kernel text SOURCE_DB='/var/lib/tuptime/tuptime.db' # Test file permissions if [ -w "${SOURCE_DB}" ]; then echo "Migrating tuptime database format" else echo "Please, execute this script with a privileged user that can write in: ${SOURCE_DB}" exit 1 fi # Test sqlite3 command sqlite3 -version > /dev/null if [ $? -ne 0 ]; then echo "Please, install "sqlite3" command for manage sqlite v3 databases." exit 2 fi # Test bc command bc -version > /dev/null if [ $? -ne 0 ]; then echo "Please, install "bc" command." exit 2 fi TMP_DB=`mktemp` # For temporary process db cp ${SOURCE_DB} ${TMP_DB} # Adding new column sqlite3 ${TMP_DB} "ALTER TABLE tuptime RENAME TO tuptime_old;" sqlite3 ${TMP_DB} "CREATE TABLE tuptime (btime INT, uptime REAL, offbtime INT, endst INT, downtime REAL, kernel TEXT);" sqlite3 ${TMP_DB} "INSERT INTO tuptime(btime, uptime, offbtime, endst, downtime, kernel) SELECT btime, uptime, offbtime, endst, downtime, '' FROM tuptime_old;" sqlite3 ${TMP_DB} "DROP TABLE tuptime_old;" ## Adding values for new columns downtime and offbtime #ROWS=`sqlite3 ${TMP_DB} "select max(oid) from tuptime;"` # #for I in $(seq 1 ${ROWS}); do # KERNEL='Linux-3.16.0-4-amd64-x86_64-with-debian-8.0' # sqlite3 ${TMP_DB} "UPDATE tuptime SET kernel = \'${KERNEL}\' where oid = ${I}" #done # Backup old db and restore the new mv ${SOURCE_DB} ${SOURCE_DB}.back mv ${TMP_DB} ${SOURCE_DB} chmod 644 ${SOURCE_DB} rm -f ${TMP_DB} echo "Backup file in: ${SOURCE_DB}.back" echo "Process completed OK" tuptime-3.2.01+git6db666b/scripts/db-tuptime-migrate.sh000066400000000000000000000061301262137604000225670ustar00rootroot00000000000000#!/bin/bash # This script update the tuptime database format from versions previous 3.0.00 # Change the db origin: # uptime real, btime integer, shutdown integer # to: # btime integer, uptime real, offbtime integer, endst integer, downtime real SOURCE_DB='/var/lib/tuptime/tuptime.db' # Test file permissions if [ -w "${SOURCE_DB}" ]; then echo "Migrating tuptime database format" else echo "Please, execute this script with a privileged user that can write in: ${SOURCE_DB}" exit 1 fi # Test sqlite3 command sqlite3 -version > /dev/null if [ $? -ne 0 ]; then echo "Please, install "sqlite3" command for manage sqlite v3 databases." exit 2 fi # Test bc command bc -version > /dev/null if [ $? -ne 0 ]; then echo "Please, install "bc" command." exit 2 fi TMP_DB=`mktemp` # For temporary process db cp ${SOURCE_DB} ${TMP_DB} # Check db format sqlite3 ${TMP_DB} "PRAGMA table_info(tuptime);" | grep -E 'end_state|downtime|offbtime' > /dev/null if [ $? -eq 0 ]; then echo "Database is already in new format" exit 3 fi # Change shutdown column to end_state sqlite3 ${TMP_DB} "ALTER TABLE tuptime RENAME TO tuptime_old;" sqlite3 ${TMP_DB} "CREATE TABLE tuptime (uptime REAL, btime INT, endst INT, downtime REAL, offbtime INT);" sqlite3 ${TMP_DB} "INSERT INTO tuptime(uptime, btime, endst) SELECT uptime, btime, shutdown FROM tuptime_old;" sqlite3 ${TMP_DB} "DROP TABLE tuptime_old;" # Adding values for new columns downtime and offbtime ROWS=`sqlite3 ${TMP_DB} "select max(oid) from tuptime;"` for I in $(seq 1 ${ROWS}); do UPTIME=`sqlite3 ${TMP_DB} "SELECT uptime from tuptime where oid = ${I};"` BTIME=`sqlite3 ${TMP_DB} "SELECT btime from tuptime where oid = ${I};"` Z=$((I+1)) NEXT_BTIME=`sqlite3 ${TMP_DB} "SELECT btime from tuptime where oid = ${Z};"` OFFBTIME=$(echo ${UPTIME} + ${BTIME} | bc) DOWNBTIME=$(echo ${NEXT_BTIME} - ${OFFBTIME} | bc) sqlite3 ${TMP_DB} "UPDATE tuptime SET downtime = ${DOWNBTIME}, offbtime = ${OFFBTIME} where oid = ${I}" done # Clear last row shutdown values sqlite3 ${TMP_DB} "UPDATE tuptime SET downtime = '-1', offbtime = '-1' where oid = ${I}" # Order columns sqlite3 ${TMP_DB} "ALTER TABLE tuptime RENAME TO tuptime_old;" sqlite3 ${TMP_DB} "CREATE TABLE tuptime (btime INT, uptime REAL, offbtime INT, endst INT, downtime REAL);" sqlite3 ${TMP_DB} "INSERT INTO tuptime(btime, uptime, offbtime, endst, downtime) SELECT btime, uptime, offbtime, endst, downtime FROM tuptime_old;" sqlite3 ${TMP_DB} "DROP TABLE tuptime_old;" # Adding new column sqlite3 ${TMP_DB} "ALTER TABLE tuptime RENAME TO tuptime_old;" sqlite3 ${TMP_DB} "CREATE TABLE tuptime (btime INT, uptime REAL, offbtime INT, endst INT, downtime REAL, kernel TEXT);" sqlite3 ${TMP_DB} "INSERT INTO tuptime(btime, uptime, offbtime, endst, downtime, kernel) SELECT btime, uptime, offbtime, endst, downtime, '' FROM tuptime_old;" sqlite3 ${TMP_DB} "DROP TABLE tuptime_old;" # Backup old db and restore the new mv ${SOURCE_DB} ${SOURCE_DB}.back mv ${TMP_DB} ${SOURCE_DB} chmod 644 ${SOURCE_DB} rm -f ${TMP_DB} echo "Backup file in: ${SOURCE_DB}.back" echo "Process completed OK" tuptime-3.2.01+git6db666b/scripts/uptimed-to-tuptime.sh000066400000000000000000000072361262137604000226530ustar00rootroot00000000000000#!/bin/bash # This script migrate the uprecords registers to tuptime db # # Note the following: # Uptimed is an uptime record daemon keeping track of the highest uptimes a computer system ever had. # Tuptime is a tool for report the historical and statistical running time of the system, keeping it between restarts. # # If you used Uptimed for the purpose of Tuptime, wich is possible changing some variables (for example, usually Uptimed # keep only last 50 max uptimes), this script can convert the register values to Tuptime format. # For achieve that: # 1- Uptimed must be running and Tuptimne installed. # 2- Execute this script and accept replace database if the values are ok. Previous Tuptime values will be lost. # 3- Done. # Usually the kernel name is not exactly the same, is it possible to correct it directly into Tuptime db sqlite3. SOURCE_F='/var/spool/uptimed/records' DEST_F='/var/lib/tuptime/tuptime.db' echo '- Uprecors to Tuptime migrate script' echo '' # Test file permissions if [ -r "${SOURCE_F}" ]; then echo "Migrating from: ${SOURCE_F}" else echo "Please, execute this script with a privileged user that can read in: ${SOURCE_F}" exit 1 fi if [ -w "${DEST_F}" ]; then echo "To: ${DEST_F}" else echo "Please, execute this script with a privileged user that can write in: ${DEST_F}" exit 1 fi echo '' while true; do read -p "Correct? (y/n)" yn case ${yn} in [Yy]* ) break;; [Nn]* ) echo 'Please, modify SOURCE_F or DEST_F in the header of the script with the correct location'; exit;; * ) echo "Please answer yes or no.";; esac done # Test sqlite3 command sqlite3 -version > /dev/null if [ $? -ne 0 ]; then echo "Please, install "sqlite3" command for manage sqlite v3 databases." exit 2 fi # Test bc command bc -version > /dev/null if [ $? -ne 0 ]; then echo "Please, install "bc" command." exit 2 fi TMP_F=`mktemp` # For ordered uprecords values TMP_F2=`mktemp` # For backup Tuptime db file TMP_FDB=`mktemp` # For temporary tuptime db echo 'Ordering Uprecors registers by btime...' cat ${SOURCE_F} | sort -k2 -t\: > ${TMP_F} LINES_S_F=`wc -l ${TMP_F} | awk '{print $1}'` # Create database sqlite3 ${TMP_FDB} "CREATE TABLE tuptime (btime INT, uptime REAL, offbtime INT, endst INT, downtime REAL, kernel TEXT);" # For each line in the file for I in $(seq 1 ${LINES_S_F}); do L_ACT=`cat ${TMP_F} | sed -n ${I}p` # Actual line UPTIME=`echo ${L_ACT} | cut -d: -f1` BTIME=`echo ${L_ACT} | cut -d: -f2` KERNEL=`echo ${L_ACT} | cut -d: -f3` OFFBTIME=$(echo ${UPTIME} + ${BTIME} | bc) ENDST='1' # Following line needed for calculate downtime if [ $I -ne ${LINES_S_F} ]; then Z=$((I+1)) L_NEXT=`cat ${TMP_F} | sed -n ${Z}p` # Following line BTIME_NEXT=`echo ${L_NEXT} | cut -d: -f2` DOWNTIME=$(echo ${BTIME_NEXT} - ${OFFBTIME} | bc) else DOWNTIME='-1' fi echo "Processing line ${I}: " ${L_ACT} echo 'btime:' ${BTIME} echo 'uptime:' ${UPTIME} echo 'offbtime:' ${OFFBTIME} echo 'endst:' ${ENDST} echo 'downtime:' ${DOWNTIME} echo 'kernel:' ${KERNEL} echo '' sqlite3 ${TMP_FDB} "INSERT INTO tuptime values (${BTIME}, ${UPTIME}, ${OFFBTIME}, ${ENDST}, ${DOWNTIME}, "\'"${KERNEL}"\'")" done tuptime -tf ${TMP_FDB} echo '' while true; do read -p "Do you want to replace the entire Tuptime database with this values? Are they correct? (y/n)" yn case ${yn} in [Yy]* ) echo "Creating backup of ${DEST_F} in ${TMP_F2}" cp ${DEST_F} ${TMP_F2} echo "Replacing ${DEST_F}" cp ${TMP_FDB} ${DEST_F} echo 'Done' break;; [Nn]* ) echo 'Exit without doing nothing.' break;; * ) echo "Please answer yes or no.";; esac done rm -f ${TMP_F} rm -f ${TMP_FDB} tuptime-3.2.01+git6db666b/tuptime-install.sh000066400000000000000000000044701262137604000205400ustar00rootroot00000000000000#!/bin/bash # # Tuptime installation linux script # v.1.5 # if [ "$(expr substr $(uname -s) 1 5)" != "Linux" ]; then echo "Sorry, only for Linux systems" exit 1 fi git --version &> /dev/null if [ $? -ne 0 ]; then echo "ERROR: \"git\" command not available" echo "Please, install it"; exit 1 fi pyver=`python --version 2>&1 /dev/null` if [ $? -ne 0 ]; then echo "ERROR: Python not available" echo "Please, install version 2.7 or greater (3.X recomended)"; exit 1 else pynum=`echo ${pyver} | tr -d '.''' | grep -Eo '[0-9]*' | cut -c 1-2` if [ $pynum -lt 27 ] ; then echo "ERROR: Its needed Python version 2.7 or greater (3.X recomended), not ${pyver}" echo "Please, upgrade it."; exit 1 else pymod=`python -c "import sys, os, optparse, sqlite3, locale, platform, subprocess, time, datetime, operator"` if [ $? -ne 0 ]; then echo "ERROR: Please, ensure that these Python modules are available in the local system:" echo "sys, os, optparse, sqlite3, locale, platform, subprocess, time, datetime, operator" fi fi fi F_TMP1=`mktemp -d` D_BIN='/usr/bin' echo "Tuptime installation script" echo "" echo "Clonning repository..." git clone https://github.com/rfrail3/tuptime.git ${F_TMP1} echo "Copying files..." cp -a ${F_TMP1}/latest/tuptime ${D_BIN}/tuptime chmod 755 ${D_BIN}/tuptime systemctl --version &> /dev/null if [ $? -eq 0 ]; then echo "Copying systemd file..." cp -a ${F_TMP1}/latest/systemd/tuptime.service /lib/systemd/system/ systemctl daemon-reload systemctl enable tuptime.service elif [ -f /lib/lsb/init-functions ]; then echo "Copying init file..." cp -a ${F_TMP1}/latest/init.d/tuptime.init.d-debian7 /etc/init.d/tuptime chmod 755 /etc/init.d/tuptime update-rc.d tuptime defaults elif [ -f /etc/rc.d/init.d/functions ]; then echo "Copying init file..." cp -a ${F_TMP1}/latest/init.d/tuptime.init.d-redhat6 /etc/init.d/tuptime chmod 755 /etc/init.d/tuptime chkconfig --add tuptime chkconfig tuptime on else echo "#####################################" echo "ERROR - Any init file for your system" echo "#####################################" fi echo "Copying cron file..." cp -a ${F_TMP1}/latest/cron.d/tuptime /etc/cron.d/tuptime echo "Enjoy!" tuptime tuptime-3.2.01+git6db666b/tuptime-manual.txt000066400000000000000000000307361262137604000205600ustar00rootroot00000000000000 ---------------------- Tuptime Manual ---------------------- version 3.2.10 Ricardo F. 13/November/2015 ============ | Abstract | ============ Tuptime report historical and statistical running time of the system, keeping it between restarts. Indeed, it can: - Count system startups - Register first boot time (a.k.a. installation time) - Count nicely and accidentally shutdowns - Uptime and downtime percentage since first boot time - Accumulated system uptime, downtime and total - Largest, shortest and average uptime and downtime - Current uptime - Print formatted table or list with most of the previous values - Register used kernels ================= | Prerequisites | ================= Operating system: - Linux - FreeBSD - OSX (Darwin) Software: - Python 2.7 or Python 3.X (Latest recomended) - Python modules (most included in python core by default): sys, os, optparse, sqlite3, datetime, locale, platform, subprocess, time If a distro is used, all is met with: - In Linux: 'python' package >= 2.7 - In FreeBSD: '/usr/ports/lang/python' and '/usr/ports/databases/py-sqlite3' - In OSX: 'python' installed by default in base system ================ | Installation | ================ For Linux systems: + Using .deb package If is a system based on .deb package, install tuptime_x.deb located in this repo under tuptime/deb-package/ Note that systemd is required. + Using .rpm package If is a system based on .rpm package, install tuptime-x.rpm located in this repo under tuptime/rpm-package/ Note that systemd is required. + Using .sh script: Download and execute the installation script: # bash <(curl -s https://raw.githubusercontent.com/rfrail3/tuptime/master/tuptime-install.sh) + Manual install Clone repository and copy executable file: # cp tuptime/latest/tuptime /usr/bin/tuptime # chmod 755 /usr/bin/tuptime Copy cron file: # cp tuptime/latest/cron.d/tuptime /etc/cron.d/tuptime # chmod 644 /etc/cron.d/tuptime If is a system with systemd, copy service file and enable it: # cp tuptime/latest/systemd/tuptime.service /lib/systemd/system/ # chmod 644 /lib/systemd/system/tuptime.service # systemctl enable tuptime.service If have upstart system, copy the file: # cp tuptime/latest/init.d/tuptime.init.d-redhat6 /etc/init.d/tuptime # chmod 755 /etc/init.d/tuptime # chkconfig --add tuptime # chkconfig tuptime on If have init system, copy the file: # cp tuptime/latest/init.d/tuptime.init.d-debian7 /etc/init.d/tuptime # chmod 755 /etc/init.d/tuptime # update-rc.d tuptime defaults # /etc/init.d/tuptime start For FreeBSD system: * Using FreeBSD ports Located at /usr/ports/sysutils/tuptime * Using FreeBSD alternative packages FreeBSD packages for tuptime can be found at the following URLs FreeBSD 10 64bit: http://pkg.ssnet.ca/10amd64-default/All/tuptime-3.2.01.txz FreeBSD 10 32bit: http://pkg.ssnet.ca/10i386-default/All/tuptime-3.2.01.txz FreeBSD 11 64bit: http://pkg.ssnet.ca/11amd64-default/All/tuptime-3.2.01.txz FreeBSD 11 ARMv6: http://pkg.ssnet.ca/11armv6-default/All/tuptime-3.2.01.txz After downloading the correct package you can install it using pkg: # pkg add tuptime-3.2.01.txz # echo 'tuptime_enable="YES"' >> /etc/rc.conf Add an entry to /etc/crontab */5 * * * * root /usr/local/bin/tuptime -x + Manual install Clone repository and copy executable file: # cp tuptime/latest/tuptime /usr/local/bin/tuptime # chmod 755 /usr/local/bin/tuptime Add an entry to /etc/crontab */5 * * * * root /usr/local/bin/tuptime -x Copy rc.d file: # cp tuptime/latest/rc.d/tuptime-freebsd /usr/local/etc/rc.d/tuptime # chmod 555 /usr/local/etc/rc.d/tuptime # echo 'tuptime_enable="YES"' >> /etc/rc.conf For OSX system: Tuptime is compatible with OSX but, for now, the project lacks of launchd files for the startup and the schedule run. ============================ | Command line parameters | ============================ These are the command line options, no configuration file is used: -h, --help show this help message and exit -c, --ckernel classify / order by kernel -d DATE_FORMAT, --date=DATE_FORMAT date format output -e, --end order by end state -f FILE, --filedb=FILE database file -g, --graceful register a gracefully shutdown -k, --kernel print kernel information -l, --list enumerate system life as list -o, --offtime order by offtime / downtime -r, --reverse reverse order -s, --seconds output time in seconds and epoch -t, --table enumerate system life as table -u, --uptime order by uptime -v, --verbose verbose output -V, --version show version -x, --silent update values into db without output -h, --help Print a quick reference of the command line parameters. Examples: tuptime -h tuptime --help -c, --ckernel Order table or list by kernel name. Therefore, only works in conjunction with (-k) and (-t) or (-l) options. Examples: tuptime -ckl tuptime -ckt tuptime -t --ckernel tuptime -l --ckernel -d , --date= Change the date format. By default it's printed based on system locales. Allow values are: %a Weekday as locale’s abbreviated name. %A Weekday as locale’s full name. %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. %d Day of the month as a zero-padded decimal number. %b Month as locale’s abbreviated name. %B Month as locale’s full name. %m Month as a zero-padded decimal number. %y Year without century as a zero-padded decimal number. %Y Year with century as a decimal number. %H Hour (24-hour clock) as a zero-padded decimal number. %I Hour (12-hour clock) as a zero-padded decimal number. %p Locale’s equivalent of either AM or PM. %M Minute as a zero-padded decimal number. %S Second as a zero-padded decimal number. %f Microsecond as a decimal number, zero-padded on the left. %z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). %Z Time zone name (empty string if the object is naive). %j Day of the year as a zero-padded decimal number. %U Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. %W Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. %c Locale’s appropriate date and time representation. %x Locale’s appropriate date representation. %X Locale’s appropriate time representation. %% A literal '%' character. Examples: tuptime -d '%X %x' # (Default) tuptime -d '%H:%M:%S %m-%d-%Y' # British style tuptime -d '%H:%M:%S %d-%b-%Y' # Spanish style -e, --end Order table or list by end status at power off. Therefore, only works in conjunction with (-t) or (-l) options. Examples: tuptime -te tuptime -le tuptime -t --end tuptime -l --end -f , --filedb= Define an alternative database file. Default is located in '/var/lib/tuptime/tuptime.db' Examples: tuptime -f /var/lib/tuptime/tuptime.db # (Default) tuptime -f /tmp/test1.db tuptime --filedb /tmp/test2.db -g, --graceful Register last time in the db as a graceful shutdown. This option is the way that tuptime have for know if is a good or a bad shutdown, like a hang of the system, for example. This is used in the init.d and systemd files at the shutdown process. Examples: tuptime -g tuptime --graceful -k, --kernel Add kernel information to the output. Examples: tuptime -k tuptime -lk tuptime --kernel tuptime -t --kernel -l, --list Enumerate as list each startup number, startup date, uptime, shutdown date, end status and offtime. Multiple order options can be combined together. Examples: tuptimoe -l tuptimoe --list -o, --offtime Order table or list by offtime / downtime. Therefore, only works in conjunction with (-t) or (-l) options. Examples: tuptime -to tuptime -lo tuptime -t --offtime tuptime -l --offtime -r, --reverse Reverse the order for table or list output. Therefore, only works in conjunction with any of (-t), (-l), (-e), (-o), (-u) and (-c) options. Examples: tuptime -tr tuptime -lur tuptime -teo --reverse tuptime -l --reverse -s, --seconds Change default human readable date style and print times in seconds and dates in epoch. Examples: tuptime -s tuptime --seconds -t, --table Enumerate as table each startup number, startup date, uptime, shutdown date, end status and downtime. Multiple order options can be combined together. Examples: tuptimoe -t tuptimoe --table -u, --uptime Order table or list by uptime. Therefore, only works in conjunction with (-t) or (-l) options. Examples: tuptime -tu tuptime -lu tuptime -t --uptime tuptime -l --uptime -v, --verbose Print information about the internals of tuptime. It's good for debugging how it gets the variables. Examples: tuptime -v tuptime --verbose -V, --version: Print version number and exit. Examples: tuptime -V tuptime --version -x, --silent Any output is printed. Only update values and save them into disk. Examples: tuptime -x tuptime --silent ====================== | Schedule execution | ====================== It's importat to have a schedule execution. If the init or systemd scripts are installed as it needs, the program only update values at startup and shutdown, but if the system fails, hangs or whatever, the uptime time will be lost. Be sure that the cron entry is installed as expected. ============================================= | DB format changes from 2.x to 3.x version | ============================================= If this error appears: ...(a few lines)... sqlite3.OperationalError: no such column: endst or: ...(a few lines)... db_rows[-1][4] = opt.endst IndexError: list assignment index out of range Is because the database have the format of the 2.x release. For migrate it, please, execute the script "db-tuptime-migrate.sh" which is located at: https://github.com/rfrail3/tuptime/blob/master/scripts/db-tuptime-migrate.sh ===================================== | Reset and modify or delete values | ===================================== Tuptime use a sqlite3 database located in "/var/lib/tuptime/tuptime.db" with the following format: tuptime (btime integer, uptime real, offbtime integer, endst integer, downtime real, kernel text) For reset all the values, simply detele the database file. Is it possible to query and modify it directly. But if a complete row is deleted and the db is not recreate completely (vacuum), rowid keep the real information about startup number. Tuptime will advert about it if the verbose mode is enabled. ================ | Some Toughts | ================ Usually the installation is made with a privileged user, for that reason, the database file is created with restricted permissions and the unprivileged users can only read it. This situation is covered for print values, but not for update database. In this habitual case, a privileged user need to execute tuptime for update values at startup and shutdown at least. Kernel name is registered each time that tuptime update values. If ksplice is used to update the kernel, last kernel will have the whole time asignement since the last system start. Table output can be processed with awk, for example: # tuptime -t | awk -F'[[:space:]][[:space:]][[:space:]]*' '{print $1}'