bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/plugins/utils.py (about)

     1  #!/usr/bin/python
     2  # This file is part of tcollector.
     3  # Copyright (C) 2013  The tcollector Authors.
     4  #
     5  # This program is free software: you can redistribute it and/or modify it
     6  # under the terms of the GNU Lesser General Public License as published by
     7  # the Free Software Foundation, either version 3 of the License, or (at your
     8  # option) any later version.  This program is distributed in the hope that it
     9  # will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
    10  # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
    11  # General Public License for more details.  You should have received a copy
    12  # of the GNU Lesser General Public License along with this program.  If not,
    13  # see <http://www.gnu.org/licenses/>.
    14  
    15  """Common utility functions shared for Python collectors"""
    16  
    17  import os
    18  import stat
    19  import pwd
    20  import errno
    21  import sys
    22  
    23  # If we're running as root and this user exists, we'll drop privileges.
    24  USER = "nobody"
    25  
    26  
    27  def drop_privileges(user=USER):
    28      """Drops privileges if running as root."""
    29      try:
    30          ent = pwd.getpwnam(user)
    31      except KeyError:
    32          return
    33  
    34      if os.getuid() != 0:
    35          return
    36  
    37      os.setgid(ent.pw_gid)
    38      os.setuid(ent.pw_uid)
    39  
    40  
    41  def is_sockfile(path):
    42      """Returns whether or not the given path is a socket file."""
    43      try:
    44          s = os.stat(path)
    45      except OSError, (no, e):
    46          if no == errno.ENOENT:
    47              return False
    48          err("warning: couldn't stat(%r): %s" % (path, e))
    49          return None
    50      return s.st_mode & stat.S_IFSOCK == stat.S_IFSOCK
    51  
    52  
    53  def err(msg):
    54      print >> sys.stderr, msg
    55  
    56  
    57  def is_numeric(value):
    58      return isinstance(value, (int, long, float))