slaptest 10.5 KB
Newer Older
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#!/usr/bin/python
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2012 Vifib SARL and Contributors.
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# 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 3
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import ConfigParser
import logging
from optparse import OptionParser, Option
import os
import sys
36 37
import tempfile
import urllib2
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
38 39 40 41


# create console handler and set level to debug
ch = logging.StreamHandler()
42
ch.setLevel(logging.WARNING)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
43
# create formatter
44
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
# add formatter to ch
ch.setFormatter(formatter)



class Parser(OptionParser):
  """
  Parse all arguments.
  """
  def __init__(self, usage=None, version=None):
    """
    Initialize all options possibles.
    """
    OptionParser.__init__(self, usage=usage, version=version,
                          option_list=[
      Option("--slapos-configuration",
             help="path to slapos configuration directory",
             default='/etc/opt/slapos/',
             type=str),
      Option("--slapos-cron",
             help="path to slapos cron file",
             default='/etc/cron.d/slapos-node',
             type=str),
68 69 70 71
      Option("--check-upload",
             help="Check if upload parameters are ok (do not check certificates)",
             default=False,
             action="store_true"),
72 73 74 75
      Option("-v","--verbose",
             default=False,
             action="store_true",
             help="Verbose output."),
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89
      Option("-n", "--dry-run",
             help="Simulate the execution steps",
             default=False,
             action="store_true"),
   ])

  def check_args(self):
    """
    Check arguments
    """
    (options, args) = self.parse_args()
    return options


90
def get_slapos_conf_example():
91 92 93
  """
  Get slapos.cfg.example and return its path
  """
94 95 96 97 98 99 100 101 102
  register_server_url = "http://git.erp5.org/gitweb/slapos.core.git/blob_plain/HEAD:/slapos.cfg.example"
  request = urllib2.Request(register_server_url)
  url = urllib2.urlopen(request)  
  page = url.read()
  info, path = tempfile.mkstemp()
  slapos_cfg_example = open(path,'w')
  slapos_cfg_example.write(page)
  slapos_cfg_example.close()
  return path
103

104
  
105
def check_networkcache(config,logger,configuration_parser):
106 107 108
  """
  Check network cache download
  """
109 110 111 112 113 114 115 116 117 118 119 120
  slapos_cfg_example = get_slapos_conf_example()
  configuration_example_parser = ConfigParser.RawConfigParser()
  configuration_example_parser.read(slapos_cfg_example)  
  os.remove(slapos_cfg_example)
  section = "networkcache"
  configuration_example_dict = dict(configuration_example_parser.items(section))
  configuration_dict = dict(configuration_parser.items(section))
  for key in configuration_example_dict:
    try:
      if not configuration_dict[key] ==  configuration_example_dict[key] :
        logger.warn("%s parameter in %s section is out of date" % (key, section))
    except KeyError:
121
      logger.warn("No %s parameter in your file" % key)
122
      pass
123 124 125
  if config.check_upload == True :
    check_networkcache_upload(config,logger,configuration_dict)

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
class Upload:
  """
  Class used as a reference to check network cache upload 
  """
  def __init__(self):
    self.data = {'download-binary-dir-url': 'http://www.shacache.org/shadir',
                 'signature_certificate_file': '/etc/slapos-cache/signature.cert',
                 'upload-dir-url': 'https://www.shacache.org/shadir',
                 'shadir-cert-file': '/etc/slapos-cache/shacache.cert',
                 'download-cache-url': 'https://www.shacache.org/shacache',
                 'upload-cache-url': 'https://www.shacache.org/shacache', 
                 'shacache-cert-file': '/etc/slapos-cache/shacache.cert', 
                 'upload-binary-cache-url': 'https://www.shacache.org/shacache', 
                 'shacache-key-file': '/etc/slapos-cache/shacache.key', 
                 'download-binary-cache-url': 'http://www.shacache.org/shacache',
                 'upload-binary-dir-url':'https://www.shacache.org/shadir', 
                 'signature_private_key_file': '/etc/slapos-cache/signature.key', 
                 'shadir-key-file': '/etc/slapos-cache/shacache.key'}

145 146

def check_networkcache_upload(config,logger,configuration_dict):
147 148 149
  """
  Check network cache upload
  """
150 151 152 153 154 155 156 157 158
  upload_parameters = Upload()
  for key in upload_parameters.data:
    try:
      if not key.find("file") == -1:
        file = configuration_dict[key]
        if not os.path.exists(file) :
          logger.critical ("%s file for %s parameters does not exist " 
                         % (file,key)) 
        else :
159
          logger.info ("%s parameter:%s does exists" % (key,file))
160 161 162 163 164 165 166 167
      else :
        if not configuration_dict[key] == upload_parameters.data[key]:
          logger.warn("%s is %s sould be %s" 
                      %(key,configuration_dict[key]
                        ,upload_parameters.data[key]))
    except KeyError:
      logger.critical ("No %s parameter in your file" % key)
      pass
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

def slapos_conf_check (config):
  """
  Check if slapos.cfg look good
  """
  # Define logger for slapos.cfg verification
  logger = logging.getLogger('Checking slapos.cfg file:')
  logger.setLevel(logging.INFO)
  logger.addHandler(ch)
  # Load configuration file
  configuration_file_path = os.path.join (config.slapos_configuration
                                          ,'slapos.cfg')
  configuration_parser = ConfigParser.SafeConfigParser()
  configuration_parser.read(configuration_file_path)
  # Check if files for slapos and slapformat exists
  for section in ("slapformat", "slapos"):
    configuration_dict = dict(configuration_parser.items(section))
    for key in configuration_dict:
      if key in ("key_file","cert_file","certificate_repository_path"):
        files = configuration_dict[key]
        if not os.path.exists(files) :
          logger.critical ("%s file for %s parameters does not exist " 
                           % (files,key)) 
        else :
          logger.info ("%s parameter:%s does exists" % (key,files))
  # Check networkcache
  check_networkcache(config,logger,configuration_parser)


class CronLine:
  """
  Class to analyse each cron line individualy
  """
  def __init__(self):
    """ Init all value to None"""
    self.command = None
    self.pidfile = None
    self.logfile = None
    self.config = None

  def parse(self,cron_line):
    """ Parse cron line and give value to attributes """
    line = cron_line.split()
    self.command = line[6]
    for word in line:
      if "slapos.cfg" in word :
        self.config = word
      if "--pidfile" in word :
        self.pidfile = word[word.find("=")+1:]
      if "--log_file" in word and "format" in self.command:
        self.logfile = word[word.find("=")+1:]
      if "--logfile" in word and not "format" in self.command:
        self.logfile = word[word.find("=")+1:]

  def check(self,config,logger):
    """ Check if all attributes are correctly set"""
    if self.config != os.path.join(config.slapos_configuration,'slapos.cfg'):
      logger.critical("For %s command: slapos.cfg is %s should be in  %s" 
                       % (self.command,self.config,config.slapos_configuration))
    if self.pidfile == None:
      logger.warning("For %s command: No pidfile" 
                       % (self.command))
    if self.logfile == None:
      logger.warning("For %s command: No logfile" 
                       % (self.command))


def cron_check (config):
  """
  Check cron file
  """
  # Define logger for cron file verification
  logger = logging.getLogger('Checking slapos-node cron file:')
  logger.setLevel(logging.INFO)
  logger.addHandler(ch)
  cron = open(config.slapos_cron,"r")  
  for line in cron :
    if "/opt/slapos" in line and not line[0]=="#":
      cron_line = CronLine()
      cron_line.parse(line)
      cron_line.check(config,logger)

Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
251
def slapos_global_check (config):
252 253 254 255
  """
  Check for main files
  """
  # Define logger for computer chek
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
256 257 258
  logger = logging.getLogger('Checking your computer for SlapOS:')
  logger.setLevel(logging.INFO)
  logger.addHandler(ch)
259
  # checking slapos.cfg
260 261 262
  if not os.path.exists(os.path.join(config.slapos_configuration,'slapos.cfg')) :
    logger.critical("No slapos.cfg found in slapos configuration directory: %s" 
                    % config.slapos_configuration )
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
263 264 265
  else :
    logger.info("SlapOS configuration file found")
    slapos_conf_check(config)
266 267 268 269 270
  # checking cron file
  if not os.path.exists(config.slapos_cron) :
    logger.warn("No %s found for cron" % config.slapos_cron)
  else:
    logger.info("Cron file found at %s" %config.slapos_cron)
271
    cron_check(config)
Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

# Class containing all parameters needed for configuration
class Config:
  def setConfig(self, option_dict):
    """
    Set options given by parameters.
    """
    # Set options parameters
    for option, value in option_dict.__dict__.items():
      setattr(self, option, value)
    # Define logger for register
    self.logger = logging.getLogger('slaptest configuration')
    self.logger.setLevel(logging.DEBUG)
    # add ch to logger
    self.logger.addHandler(ch)

288 289 290 291
    if self.verbose :
      ch.setLevel(logging.DEBUG)


Cédric Le Ninivin's avatar
Cédric Le Ninivin committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
  def displayUserConfig(self):
    self.logger.debug ("Slapos.cfg : %s" % self.slapos_configuration)
    self.logger.debug ("slapos cron file: %s" % self.slapos_cron)


def main():
  """Checking computer state to run slapos"""
  usage = "usage: %s [options] " % sys.argv[0]
  # Parse arguments
  config = Config()
  config.setConfig(Parser(usage=usage).check_args())
  config.displayUserConfig()
  slapos_global_check(config)
  sys.exit()


if __name__ == "__main__":
  main()