Package Products :: Package ZenUtils :: Module ZenBackupBase |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenUtils.ZenBackupBase

      1  #! /usr/bin/env python
      2  ###########################################################################
      3  #
      4  # This program is part of Zenoss Core, an open source monitoring platform.
      5  # Copyright (C) 2007, 2009 Zenoss Inc.
      6  #
      7  # This program is free software; you can redistribute it and/or modify it
      8  # under the terms of the GNU General Public License version 2 or (at your
      9  # option) any later version as published by the Free Software Foundation.
     10  #
     11  # For complete information please visit: http://www.zenoss.com/oss/
     12  #
     13  ###########################################################################
     14
     15
     16  __doc__='''ZenBackupBase
     17
     18  Common code for zenbackup.py and zenrestore.py
     19  '''
     20  import tempfile
     21  from subprocess import Popen, PIPE
     22
     23  from CmdBase import CmdBase
     24
     25
     26  BACKUP_DIR = 'zenbackup'
     27  CONFIG_FILE = 'backup.settings'
     28  CONFIG_SECTION = 'zenbackup'
     29
     30 -class ZenBackupBase(CmdBase):
     31      doesLogging = False
     32
     33
     34 -    def __init__(self, noopts=0):
     35          CmdBase.__init__(self, noopts)
     36
     37 -    def msg(self, msg):
     38          '''
     39          If --verbose then send msg to stdout
     40          '''
     41          if self.options.verbose:
     42              print(msg)
     43
     44
     45 -    def buildOptions(self):
     46          """
     47          Command-line options setup
     48          """
     49          CmdBase.buildOptions(self)
     50          self.parser.add_option('-v', '--verbose',
     51                                 dest="verbose",
     52                                 default=False,
     53                                 action='store_true',
     54                                 help='Send progress messages to stdout.')
     55          self.parser.add_option('--temp-dir',
     56                                 dest="tempDir",
     57                                 default=None,
     58                                 help='Directory to use for temporary storage.')
     59          self.parser.add_option('--host',
     60                      dest="host",default="localhost",
     61                      help="hostname of MySQL object store")
     62          self.parser.add_option('--port',
     63                      dest="port", default='3306',
     64                      help="port of MySQL object store")
     65          self.parser.add_option('--mysqluser', dest='mysqluser', default='zenoss',
     66                      help='username for MySQL object store')
     67          self.parser.add_option('--mysqlpasswd', dest='mysqlpasswd', default='zenoss',
     68                      help='passwd for MySQL object store')
     69          self.parser.add_option('--mysqldb', dest='mysqldb', default='zodb',
     70                      help='Name of database for MySQL object store')
     71          self.parser.add_option('--cacheservers', dest='cacheservers',
     72                      help='memcached servers to use for object cache (eg. 127.0.0.1:11211)')
     73          self.parser.add_option('--zepdbname',
     74                                 dest='zepdbname',
     75                                 default='zenoss_zep',
     76                                 help='ZEP database name.'
     77                                  ' By default this will be fetched from Zenoss'
     78                                  ' unless --dont-fetch-args is set.'),
     79          self.parser.add_option('--zepdbuser',
     80                                 dest='zepdbuser',
     81                                 default='zenoss',
     82                                 help='ZEP database username.'
     83                                  ' By default this will be fetched from Zenoss'
     84                                  ' unless --dont-fetch-args is set.'),
     85          self.parser.add_option('--zepdbpass',
     86                                 dest='zepdbpass',
     87                                 default='zenoss',
     88                                 help='ZEP database password.'
     89                                  ' By default this will be fetched from Zenoss'
     90                                  ' unless --dont-fetch-args is set.'),
     91          self.parser.add_option('--zepdbhost',
     92                                 dest='zepdbhost',
     93                                 default='localhost',
     94                                 help='ZEP database server host.'
     95                                  ' By default this will be fetched from Zenoss'
     96                                  ' unless --dont-fetch-args is set.'),
     97          self.parser.add_option('--zepdbport',
     98                                 dest='zepdbport',
     99                                 default='3306',
    100                                 help='ZEP database server port number.'
    101                                  ' By default this will be fetched from Zenoss'
    102                                  ' unless --dont-fetch-args is set.'),
    103          self.parser.add_option('--compress-transport',
    104                                 dest="compressTransport",
    105                                 default=True,
    106                                 help='Compress transport for MySQL backup/restore.'
    107                                 ' True by default, set to False to disable over'
    108                                 ' fast links that do not benefit from compression.')
    109
    110
    111 -    def getPassArg(self, optname='dbpass'):
    112          """
    113          Return string to be used as the -p (including the "-p")
    114          to MySQL commands.
    115
    116          @return: password and flag
    117          @rtype: string
    118          """
    119          password = getattr(self.options, optname, None)
    120          if not password:
    121              return []
    122          return ['-p%s' % password]
    123
    124
    125 -    def getTempDir(self):
    126          """
    127          Return directory to be used for temporary storage
    128          during backup or restore.
    129
    130          @return: directory name
    131          @rtype: string
    132          """
    133          if self.options.tempDir:
    134              dir = tempfile.mkdtemp('', '', self.options.tempDir)
    135          else:
    136              dir = tempfile.mkdtemp()
    137          return dir
    138
    139
    140 -    def runCommand(self, cmd=[], obfuscated_cmd=None):
    141          """
    142          Execute a command and return the results, displaying pre and
    143          post messages.
    144
    145          @parameter cmd: command to run
    146          @type cmd: list
    147          @return: results of the command (output, warnings, returncode)
    148          """
    149          if obfuscated_cmd:
    150              self.log.debug(' '.join(obfuscated_cmd))
    151          else:
    152              self.log.debug(' '.join(cmd))
    153          proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
    154          output, warnings = proc.communicate()
    155          if proc.returncode:
    156              self.log.warn(warnings)
    157          self.log.debug(output or 'No output from command')
    158          return (output, warnings, proc.returncode)
    159
    160 -    def runMysqlCmd(self, sql, switchDB=False):
    161          """
    162          Run a command that executes SQL statements in MySQL.
    163          Return true if the command was able to complete, otherwise
    164          (eg permissions or login error), return false.
    165
    166          @parameter sql: an executable SQL statement
    167          @type sql: string
    168          @parameter switchDB: use -D options.dbname to switch to a database?
    169          @type switchDB: boolean
    170          @return: boolean
    171          @rtype: boolean
    172          """
    173          cmd = ['mysql', '-u', self.options.dbuser]
    174
    175          obfuscatedCmd = None
    176          if self.options.dbpass:
    177              cmd.append('--password=%s' % self.options.dbpass)
    178
    179          if self.options.dbhost and self.options.dbhost != 'localhost':
    180              cmd.append('--host=%s' % self.options.dbhost)
    181          if self.options.dbport and self.options.dbport != '3306':
    182              cmd.append('--port=%s' % self.options.dbport)
    183
    184          if switchDB:
    185              cmd.extend(['-D', self.options.dbname])
    186
    187          cmd.extend(['-e', sql])
    188
    189          if self.options.dbpass:
    190              obfuscatedCmd = cmd[:]
    191              obfuscatedCmd[3] = '--pasword=%s' % ('*' * 8)
    192
    193          result = self.runCommand(cmd, obfuscated_cmd=obfuscatedCmd)
    194          if result[2]: # Return code from the command
    195              return False
    196          return True
    197