Browse Source

converted tabs to spaces, pulled in changes to the daemon class from jwmud, fixed some errors reported by pycharm

Helmut Pozimski 9 years ago
parent
commit
506bfc4308
6 changed files with 196 additions and 176 deletions
  1. 4 0
      Changelog
  2. 6 0
      debian/changelog
  3. 12 11
      setup.py
  4. 13 26
      stdd
  5. 58 54
      stddlib/configuration.py
  6. 103 85
      stddlib/daemon.py

+ 4 - 0
Changelog

@@ -1,3 +1,7 @@
+2014-07-12  Helmut Pozimski  <helmut@pozimski.eu>
+
+    converted tabs to spaces, pulled in changes to the daemon class from jwmud, fixed some errors reported by pycharm
+
 2014-02-27  Helmut Pozimski  <helmut@pozimski.eu>
 
 	Fix unneeded space in process name, only write time to display when the minute changes and not every second

+ 6 - 0
debian/changelog

@@ -1,3 +1,9 @@
+stdd (0.9.2~beta-1) unstable; urgency=low
+
+  * New upstream beta release
+
+ -- Helmut Pozimski <helmut@pozimski.eu>  Sat, 12 Jul 2014 10:11:00 +0200
+
 stdd (0.9.1-2) unstable; urgency=low
 
   * Bump standards to version 3.9.5 (no changes needed)

+ 12 - 11
setup.py

@@ -9,14 +9,15 @@
 from distutils.core import setup
 
 setup(
-	name="stdd",
-	version="0.9.1",
-	author_email="helmut@pozimski.eu",
-	description="stdd, simple time display daemon",
-	long_description=("stdd is a small daemon written in python which displays"
-			"the current time on a 7 segment display from Adafruit attached via i2c"),
-	license="3-clause BSD license",
-	packages=["adafruit_7segment", "stddlib"],
-	scripts=["stdd"],
-	data_files=[('/etc', ['config/stdd.conf'])]
-)	
+    name="stdd",
+    version="0.9.1",
+    author_email="helmut@pozimski.eu",
+    description="stdd, simple time display daemon",
+    long_description=("stdd is a small daemon written in python which displays"
+            "the current time on a 7 segment display from Adafruit attached "
+            "via i2c"),
+    license="3-clause BSD license",
+    packages=["adafruit_7segment", "stddlib"],
+    scripts=["stdd"],
+    data_files=[('/etc', ['config/stdd.conf'])]
+)

+ 13 - 26
stdd

@@ -86,14 +86,17 @@ elif config.syslog_level == "error":
 else:
     logger.setLevel(logging.INFO)
 
-if config.syslog_facility == "user":
+if config.syslog_facility == "daemon":
+    syslog_handler = logging.handlers.SysLogHandler(
+        "/dev/log",
+        facility=logging.handlers.SysLogHandler.LOG_DAEMON)
+else:
     syslog_handler = logging.handlers.SysLogHandler("/dev/log")
-elif config.syslog_facility == "daemon":
-    syslog_handler = logging.handlers.SysLogHandler("/dev/log",facility=logging.handlers.SysLogHandler.LOG_DAEMON)
+
 console_handler = logging.StreamHandler()
 
 formatter = logging.Formatter("%(name)s[" + str(os.getpid()) +
-        "]: %(message)s")
+                              "]: %(message)s")
 
 syslog_handler.setFormatter(formatter)
 console_handler.setFormatter(formatter)
@@ -118,28 +121,12 @@ if options.daemon is True:
             cmdline = cmdline + " " + element
         else:
             cmdline = cmdline + element
-        cmdcounter = cmdcounter + 1
+        cmdcounter += 1
     daemon.SetName("stdd", cmdline)
     if options.user is not None and options.group is not None:
-        """ To determine the user and group id, use the passwd
-        and group files
-
-        """
-        passwd = open("/etc/passwd", "r")
-        group = open("/etc/group", "r")
-        for line in passwd:
-            if options.user in line:
-                uid = line.split(":")[2]
-                break
-        for line in group:
-            if options.group in line:
-                gid = line.split(":")[2]
-                break
-        passwd.close()
-        group.close()
-        daemon.DropPriv(int(uid), int(gid))
+        daemon.DropPriv(options.user, options.group)
         logger.debug("dropped privileges, now running as " + options.user +
-            " and group" + options.group)
+                     " and group" + options.group)
 
 """Initialize the display object"""
 display = SevenSegment(config.hw_address)
@@ -147,7 +134,7 @@ logger.debug("opened hardware address")
 
 """Set the brightness according to the configuration"""
 if datetime.datetime.now().time() > config.set_brightness_high and \
-datetime.datetime.now().time() < config.set_brightness_low:
+        datetime.datetime.now().time() < config.set_brightness_low:
     logger.debug("setting display brightness high")
     display.setBrightness(config.brightness_high)
 else:
@@ -169,8 +156,8 @@ def main():
             display.setColon(date_now.second % 2)
         else:
             display.setColon(True)
-        """set the display brightness high or low when the point in time defined
-        is reached
+        """set the display brightness high or low when the point in time
+        defined is reached.
 
         """
         if config.set_brightness_low.hour == hour:

+ 58 - 54
stddlib/configuration.py

@@ -8,61 +8,65 @@ import datetime
 
 
 class Conf(object):
-	def __init__(self):
-		"""creates the object prepopulated with some reasonable default values"""
-		self.__values = {
-				"hw_address": "",
-				"blink_colon": "0",
-				"brightness_high": "15",
-				"brightness_low": "2",
-				"set_brightness_low": "00:00",
-				"set_brightness_high": "00:00",
-				"syslog_level": "info",
-				"syslog_facility": "user"
-				}
+    def __init__(self):
+        """creates the object prepopulated with some reasonable default
+        values
 
-		""" declare empty variables to write the checked values into """
-		self.hw_address = 0
-		self.blink_colon = False
-		self.brightness_high = 0
-		self.brightness_low = 0
-		self.set_brightness_low = None
-		self.set_brightness_high = None
-		self.syslog_level = ""
-		self.syslog_facility = ""
+        """
+        self.__values = {
+            "hw_address": "",
+            "blink_colon": "0",
+            "brightness_high": "15",
+            "brightness_low": "2",
+            "set_brightness_low": "00:00",
+            "set_brightness_high": "00:00",
+            "syslog_level": "info",
+            "syslog_facility": "user"
+            }
 
-	def Read(self, file_path="/etc/stdd.conf"):
-		"""reads the configuration file from the path given to the function,
-		default to /etc/stdd.conf if empty"""
-		self.__conffile = open(file_path, "r")
-		for line in self.__conffile:
-			if "#" in line:
-				continue
-			else:
-				self.__line_stripped = line.strip()
-				if self.__line_stripped != "":
-					self.__tmpvalue = self.__line_stripped.split("=")
-					self.__values[self.__tmpvalue[0].lower()] = self.__tmpvalue[1]
-		self.__conffile.close()
+        """ declare empty variables to write the checked values into """
+        self.hw_address = 0
+        self.blink_colon = False
+        self.brightness_high = 0
+        self.brightness_low = 0
+        self.set_brightness_low = None
+        self.set_brightness_high = None
+        self.syslog_level = ""
+        self.syslog_facility = ""
 
-	def Analyze(self):
-		"""takes the values from the list, converts them to the needed data types
-		and writes them into the prepared attributes
+    def Read(self, file_path="/etc/stdd.conf"):
+        """reads the configuration file from the path given to the function,
+        default to /etc/stdd.conf if empty"""
+        self.__conffile = open(file_path, "r")
+        for line in self.__conffile:
+            if "#" in line:
+                continue
+            else:
+                self.__line_stripped = line.strip()
+                if self.__line_stripped != "":
+                    self.__tmpvalue = self.__line_stripped.split("=")
+                    self.__values[self.__tmpvalue[0].lower()] =\
+                        self.__tmpvalue[1]
+        self.__conffile.close()
 
-		"""
-		self.hw_address = int(self.__values["hw_address"], 16)
-		if self.__values["blink_colon"] == "1":
-			self.blink_colon = True
-		else:
-			self.blink_colon = False
-		self.brightness_high = int(self.__values["brightness_high"])
-		self.brightness_low = int(self.__values["brightness_low"])
-		self.__timetemp = self.__values["set_brightness_high"].split(":")
-		self.set_brightness_high = datetime.time(int(self.__timetemp[0]),
-			int(self.__timetemp[1]))
-		self.__timetemp = self.__values["set_brightness_low"].split(":")
-		self.set_brightness_low = datetime.time(int(self.__timetemp[0]),
-			int(self.__timetemp[1]))
-		self.syslog_level = self.__values["syslog_level"]
-		self.syslog_facility = self.__values["syslog_facility"]
-		del self.__values
+    def Analyze(self):
+        """takes the values from the list, converts them to the needed data
+        types and writes them into the prepared attributes
+
+        """
+        self.hw_address = int(self.__values["hw_address"], 16)
+        if self.__values["blink_colon"] == "1":
+            self.blink_colon = True
+        else:
+            self.blink_colon = False
+        self.brightness_high = int(self.__values["brightness_high"])
+        self.brightness_low = int(self.__values["brightness_low"])
+        self.__timetemp = self.__values["set_brightness_high"].split(":")
+        self.set_brightness_high = datetime.time(int(self.__timetemp[0]),
+                                                 int(self.__timetemp[1]))
+        self.__timetemp = self.__values["set_brightness_low"].split(":")
+        self.set_brightness_low = datetime.time(int(self.__timetemp[0]),
+                                                int(self.__timetemp[1]))
+        self.syslog_level = self.__values["syslog_level"]
+        self.syslog_facility = self.__values["syslog_facility"]
+        del self.__values

+ 103 - 85
stddlib/daemon.py

@@ -9,100 +9,118 @@ import sys
 
 
 class Daemon(object):
-	""" Tries to implement a well behaving unix daemon in a generic way,
-	so the code could be used in different projects.
+    """ Tries to implement a well behaving unix daemon in a generic way,
+    so the code could be used in different projects.
 
-	"""
+    """
 
-	def __init__(self, pfile_path, pfile_name):
-		""" Initializes the object. """
-		self.__pfile_path = pfile_path
-		self.__pfile_name = pfile_name
-		self.__daemon = False
+    def __init__(self, pfile_path, pfile_name):
+        """ Initializes the object. """
+        self.__pfile_path = pfile_path
+        self.__pfile_name = pfile_name
+        self.__daemon = False
 
-	def Daemonize(self):
-		""" Turns the calling prozess into a daemon running on it's own """
+    def Daemonize(self):
+        """ Turns the calling prozess into a daemon running on it's own """
 
-		try:
-			# Fork for the first time
-			self.__pid = os.fork()
-		except OSError:
-			sys.exit(os.EX_OSERR)
-		else:
-			if self.__pid > 0:
-				sys.exit(os.EX_OK)
-		# Become session and group leader
-		os.setsid()
-		try:
-			#Fork for the second time
-			self.__pid = os.fork()
-		except OSError:
-			sys.exit(os.EX_OSERR)
-		else:
-			if self.__pid > 0:
-				sys.exit(os.EX_OK)
-		# Change cwd to / to avoid interfering with other mounted file systems
-		os.chdir("/")
-		# Reset the umask
-		os.umask(0)
+        try:
+            # Fork for the first time
+            self.__pid = os.fork()
+        except OSError:
+            sys.exit(os.EX_OSERR)
+        else:
+            if self.__pid > 0:
+                sys.exit(os.EX_OK)
+        # Become session and group leader
+        os.setsid()
+        try:
+            #Fork for the second time
+            self.__pid = os.fork()
+        except OSError:
+            sys.exit(os.EX_OSERR)
+        else:
+            if self.__pid > 0:
+                sys.exit(os.EX_OK)
+        # Change cwd to / to avoid interfering with other mounted file systems
+        os.chdir("/")
+        # Reset the umask
+        os.umask(0)
 
-		# Close possibly open file descriptors
-		os.close(0)
-		os.close(1)
-		os.close(2)
+        # Close possibly open file descriptors
+        os.close(0)
+        os.close(1)
+        os.close(2)
 
-		# And redirect them to /dev/null
-		os.open("/dev/null", 0)
-		os.open("/dev/null", 1)
-		os.open("/dev/null", 2)
+        # And redirect them to /dev/null
+        os.open("/dev/null", 0)
+        os.open("/dev/null", 1)
+        os.open("/dev/null", 2)
 
-		self.__daemon = True
+        self.__daemon = True
 
-	def DropPriv(self, uid, gid):
-		""" If the daemon is running as root user, drop privileges and continue
-		running as the defined unprivileged user """
-		if os.getuid() == 0:
-			os.setgid(gid)
-			os.setuid(uid)
+    def DropPriv(self, user, group):
+        """ If the daemon is running as root user, drop privileges and continue
+        running as the defined unprivileged user. """
+        pid_file_path = os.path.join(self.__pfile_path, self.__pfile_name)
+        passwd_file = open("/etc/passwd", "r")
+        group_file = open("/etc/group", "r")
+        uid = ""
+        gid = ""
+        for line in passwd_file:
+            if user in line:
+                uid = line.split(":")[2]
+                break
+        for line in group_file:
+            if group in line.split(":")[0]:
+                gid = line.split(":")[2]
+                break
+        passwd_file.close()
+        group_file.close()
+        if os.getuid() == 0:
+            os.chown(pid_file_path, int(uid), int(gid))
+            os.setgid(int(gid))
+            os.setuid(int(uid))
 
-	def SetName(self, name, cmdline):
-		""" Sets the name of the process shown visible in ps and top,
-		this allows to make your daemon look more like a standalone
-		program instead of a python script.
+    def SetName(self, name, cmdline):
+        """ Sets the name of the process shown visible in ps and top,
+        this allows to make your daemon look more like a standalone
+        program instead of a python script.
 
-		"""
-		try:
-			# First check if prctl is available, otherwise this function does nothing
-			import prctl
-		except ImportError:
-			return False
-		else:
-			prctl.set_name(name)
-			prctl.set_proctitle(cmdline)
-			return True
+        """
+        try:
+            # First check if prctl is available, otherwise this function
+            # does nothing
+            import prctl
+        except ImportError:
+            return False
+        else:
+            prctl.set_name(name)
+            prctl.set_proctitle(cmdline)
+            return True
 
-	def Start(self):
-		""" Performs the operations needed to "start" the daemon """
-		if self.__daemon is True:
-			if os.access(self.__pfile_path, os.F_OK & os.W_OK):
-				self.__pidfile = open(os.path.join(self.__pfile_path, self.__pfile_name),
-						"w")
-				self.__pidfile.write(unicode(os.getpid()) + "\n")
-				self.__pidfile.close()
-				return True
-			else:
-				return False
-		else:
-			return False
+    def Start(self):
+        """ Performs the operations needed to "start" the daemon """
+        if self.__daemon is True:
+            if os.access(self.__pfile_path, os.F_OK & os.W_OK):
+                self.__pidfile = open(os.path.join(self.__pfile_path,
+                                                   self.__pfile_name),
+                                      "w")
+                self.__pidfile.write(unicode(os.getpid()) + "\n")
+                self.__pidfile.close()
+                return True
+            else:
+                return False
+        else:
+            return False
 
-	def Stop(self):
-		""" Performs the operations needed to stop the daemon """
-		if self.__daemon is True:
-			try:
-				os.remove(os.path.join(self.__pfile_path, self.__pfile_name))
-			except OSError:
-				return False
-			else:
-				return True
-		else:
-			return True
+    def Stop(self):
+        """ Performs the operations needed to stop the daemon """
+        if self.__daemon is True:
+            try:
+                os.remove(os.path.join(self.__pfile_path, self.__pfile_name))
+            except OSError:
+                return False
+            else:
+                return True
+        else:
+            return True