Blame view

slapos/grid/promise/generic.py 16.9 KB
Alain Takoudjou 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 36 37
# -*- coding: utf-8 -*-
# vim: set et sts=2:
##############################################################################
#
# Copyright (c) 2018 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 os
import logging
import re
import time
import random
import traceback
import slapos.slap
Bryton Lacquement committed
38
from slapos.util import bytes2str, mkdir_p
Alain Takoudjou committed
39
from abc import ABCMeta, abstractmethod
Bryton Lacquement committed
40 41
import six
from six import PY3, with_metaclass
Alain Takoudjou committed
42 43 44 45 46 47
from datetime import datetime, timedelta

PROMISE_STATE_FOLDER_NAME = '.slapgrid/promise'
PROMISE_RESULT_FOLDER_NAME = '.slapgrid/promise/result'
PROMISE_LOG_FOLDER_NAME = '.slapgrid/promise/log'

Alain Takoudjou committed
48 49
PROMISE_PARAMETER_NAME = 'extra_config_dict'

Bryton Lacquement committed
50 51 52 53
LOGLINE_RE = r"(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+\-?\s*(\w{4,7})\s+\-?\s+(\d+\-\d{3})\s+\-?\s*(.*)"
matchLogStr = re.compile(LOGLINE_RE).match
matchLogBytes = re.compile(LOGLINE_RE.encode()).match if PY3 else matchLogStr

Alain Takoudjou committed
54 55 56
class BaseResult(object):
  def __init__(self, problem=False, message=None, date=None):
    self.__problem = problem
Alain Takoudjou committed
57 58 59
    # The promise message should be very short,
    # a huge message size can freeze the process Pipe
    # XXX this is important to prevent process deadlock
Alain Takoudjou committed
60
    if message is not None and len(message) > 5000:
Alain Takoudjou committed
61
      message = '...%s' % message[-5000:]
Alain Takoudjou committed
62 63 64 65 66 67 68 69
    self.__message = message
    self.__date = date
    if self.__date is None:
      self.__date = datetime.utcnow()

  def hasFailed(self):
    return self.__problem

Alain Takoudjou committed
70 71
  @staticmethod
  def type():
Alain Takoudjou committed
72 73 74 75 76 77 78 79 80 81 82 83
    return "Base Result"

  @property
  def message(self):
    return self.__message

  @property
  def date(self):
    return self.__date

class TestResult(BaseResult):

Alain Takoudjou committed
84 85
  @staticmethod
  def type():
Alain Takoudjou committed
86 87 88 89
    return "Test Result"

class AnomalyResult(BaseResult):

Alain Takoudjou committed
90 91
  @staticmethod
  def type():
Alain Takoudjou committed
92 93
    return "Anomaly Result"

Alain Takoudjou committed
94 95 96 97 98 99 100 101 102
class EmptyResult(BaseResult):

  def __init__(self):
    BaseResult.__init__(self, False, None, None)

  @staticmethod
  def type():
    return "Empty Result"

Alain Takoudjou committed
103 104
class PromiseQueueResult(object):

Alain Takoudjou committed
105 106
  def __init__(self, path=None, name=None, title=None,
               item=None, execution_time=0):
Alain Takoudjou committed
107 108 109 110 111
    self.path = path
    self.name = name
    self.item = item
    self.title = title
    self.execution_time = execution_time
Alain Takoudjou committed
112 113 114
    if self.item is None:
      # if no result set, then set EmptyResult
      self.item = EmptyResult()
Alain Takoudjou committed
115 116 117 118 119 120 121 122

  def serialize(self):
    return {
      'title': self.title,
      'name': self.name,
      'path': self.path,
      'execution-time': self.execution_time,
      'result': {
Alain Takoudjou committed
123
        'type': self.item.type(),
Alain Takoudjou committed
124
        'failed': self.item.hasFailed(),
Alain Takoudjou committed
125
        'date': self.item.date.strftime('%Y-%m-%dT%H:%M:%S+0000'),
Alain Takoudjou committed
126 127 128 129
        'message': self.item.message
      }
    }

Alain Takoudjou committed
130 131 132 133 134
  def load(self, data):
    if data['result']['type'] == AnomalyResult.type():
      self.item = AnomalyResult(
        problem=data['result']['failed'],
        message=data['result']['message'],
Alain Takoudjou committed
135
        date=datetime.strptime(data['result']['date'], '%Y-%m-%dT%H:%M:%S+0000'))
Alain Takoudjou committed
136 137 138 139
    elif data['result']['type'] == TestResult.type():
      self.item = TestResult(
        problem=data['result']['failed'],
        message=data['result']['message'],
Alain Takoudjou committed
140
        date=datetime.strptime(data['result']['date'], '%Y-%m-%dT%H:%M:%S+0000'))
Alain Takoudjou committed
141 142 143 144 145 146 147 148
    else:
      raise ValueError('Unknown result type: %r' % data['result']['type'])

    self.title = data['title']
    self.name = data['name']
    self.path = data['path']
    self.execution_time = data['execution-time']

Bryton Lacquement committed
149
class GenericPromise(with_metaclass(ABCMeta, object)):
Alain Takoudjou committed
150 151 152 153 154 155 156 157 158 159 160

  def __init__(self, config):
    self.__config = config

    self.__log_folder = self.__config.pop('log-folder', None)
    self.__partition_folder = self.__config.pop('partition-folder', None)
    self.__debug = self.__config.pop('debug', True)
    self.__name = self.__config.pop('name', None)
    self.__promise_path = self.__config.pop('path', None)
    self.__queue = self.__config.pop('queue', None)
    self.__logger_buffer = None
Alain Takoudjou committed
161
    self.setPeriodicity(self.__config.pop('periodicity', 2))
Alain Takoudjou committed
162 163

    self.__transaction_id = '%s-%s' % (int(time.time()), random.randint(100, 999))
Alain Takoudjou committed
164 165 166
    self.__is_tested = True
    # XXX - JP asked to use __is_anomaly_detected = True, but __is_anomaly_less seems more convenient
    self.__is_anomaly_detected = True
Alain Takoudjou committed
167 168 169 170 171 172 173 174 175

    self._validateConf()
    self._configureLogger()

  def _configureLogger(self):
    self.logger = logging.getLogger(self.__name)
    for handler in self.logger.handlers:
      self.logger.removeHandler(handler)
    if self.__log_folder is None:
Bryton Lacquement committed
176
      self.__logger_buffer = six.StringIO()
Alain Takoudjou committed
177 178 179
      logger_handler = logging.StreamHandler(self.__logger_buffer)
      self.__log_file = None
    else:
Alain Takoudjou committed
180
      mkdir_p(self.__log_folder)
Alain Takoudjou committed
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
      self.__log_file = os.path.join(
        self.__log_folder,
        '%s.log' % self.__title
      )
      logger_handler = logging.FileHandler(self.__log_file)

    self.logger.setLevel(logging.DEBUG if self.__debug else logging.INFO)
    logger_handler.setFormatter(
      fmt=logging.Formatter("%(asctime)s - %(levelname)s - " +
          self.__transaction_id + " - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S")
    )
    self.logger.addHandler(logger_handler)

  def _validateConf(self):
    if self.__queue is None:
      raise ValueError("Queue object is not set in configuration")
    if self.__name is None:
      raise ValueError("Monitor name is not set in configuration")
    self.__title = os.path.splitext(self.__name)[0]
    if self.__promise_path is None:
      raise ValueError("Promise path is not set in configuration")
    if self.__partition_folder is None:
      raise ValueError("Monitor partition folder is not set in configuration")

  def getConfig(self, key, default=None):
    return self.__config.get(key, default)

  def setConfig(self, key, value):
    self.__config[key] = value

  def getTitle(self):
    return self.__title

  def getName(self):
    return self.__name

  def getLogFile(self):
    return self.__log_file

  def getLogFolder(self):
    return self.__log_folder

  def getPartitionFolder(self):
    return self.__partition_folder

  def getPromiseFile(self):
    return self.__promise_path

  def setPeriodicity(self, minute):
    if minute <= 0:
      raise ValueError("Cannot set promise periodicity to a value less than 1")
    self.__periodicity = minute

  def getPeriodicity(self):
    return self.__periodicity

Alain Takoudjou committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  def setTestLess(self):
    """
      Ask to skip test method. Only Anomaly will run
    """
    self.__is_tested = False

  def isTested(self):
    return self.__is_tested

  def setAnomalyLess(self):
    """
      Ask to skip anomaly method. Only Test will run
    """
    self.__is_anomaly_detected = False

Alain Takoudjou committed
253
  def isAnomalyDetected(self):
Alain Takoudjou committed
254 255
    return self.__is_anomaly_detected

Alain Takoudjou committed
256 257 258 259
  def __bang(self, message):
    """
      Call bang if requested
    """
Bryton Lacquement committed
260 261 262
    if 'master-url' in self.__config and \
       'partition-in' in self.__config and \
       'computer-id' in self.__config:
Alain Takoudjou committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

      slap = slapos.slap.slap()
      slap.initializeConnection(
          self.__config['master-url'],
          self.__config.get('partition-key'),
          self.__config.get('partition-cert'),
      )
      computer_partition = slap.registerComputerPartition(
          self.__config['computer-id'],
          self.__config['partition-id'],
      )
      computer_partition.bang(message)
      self.logger.info("Bang with message %r." % message)

  def __getResultFromString(self, result_string, only_failure=False):
    line_list = result_string.split('\n')
    result_list = []
    line_part = ""
    for line in line_list:
      if not line:
        continue
Bryton Lacquement committed
284
      match = matchLogStr(line)
Alain Takoudjou committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
      if match is not None:
        if not only_failure or (only_failure and match.groups()[1] == 'ERROR'):
          result_list.append({
            'date': datetime.strptime(match.groups()[0], '%Y-%m-%d %H:%M:%S'),
            'status': match.groups()[1],
            'message': (match.groups()[3] + line_part).strip(),
          })
        line_part = ""
      else:
        line_part += '\n' + line
    result_list

    return [result_list]

  def getLastPromiseResultList(self, latest_minute=0, result_count=1,
      only_failure=False):
    """
      Return the latest log result of the promise starting from the most recent

      @param last_minute: the number of minutes in the past. If last_minute is
        1, it will return the log of the latest minute execution. 0 => disabled
      @param only_failure: only return the lines which contain failures.
      @param result_count: maximum number of promise result to check, will not
        exceed the `latest_minute`
      @return Return a list of logs. The format is
        [[{"date": "DATE", "status": "STATUS", "message": MESSAGE}, ...], ...]
    """

    if self.__log_file is None:
      if self.__logger_buffer is not None:
        return self.__getResultFromString(self.__logger_buffer.getvalue(),
                                          only_failure)
      else:
        return []

    if not os.path.exists(self.__log_file):
      return []

    if latest_minute > 0:
      date = datetime.now() - timedelta(minutes=latest_minute)
      max_date_string = date.strftime('%Y-%m-%d %H:%M:%S')
Bryton Lacquement committed
326 327
    else:
      max_date_string = ""
Alain Takoudjou committed
328 329 330 331 332

    line_list = []
    result_list = []
    transaction_id = None
    transaction_count = 0
Bryton Lacquement committed
333
    with open(self.__log_file, 'rb') as f:
Alain Takoudjou committed
334
      f.seek(0, 2)
Bryton Lacquement committed
335 336 337 338
      offset = f.tell()
      line = b""
      line_part = ""
      while offset:
Alain Takoudjou committed
339
        offset -= 1
Bryton Lacquement committed
340
        f.seek(offset)
Alain Takoudjou committed
341
        char = f.read(1)
Bryton Lacquement committed
342
        if char != b'\n':
Alain Takoudjou committed
343
          line = char + line
Bryton Lacquement committed
344
          if offset:
Alain Takoudjou committed
345
            continue
Bryton Lacquement committed
346 347
        if line:
            result = matchLogBytes(line)
Alain Takoudjou committed
348
            if result is not None:
Bryton Lacquement committed
349 350
              date, level, tid, msg = map(bytes2str, result.groups())
              if max_date_string and date <= max_date_string:
Alain Takoudjou committed
351
                break
Bryton Lacquement committed
352
              if transaction_id != tid:
Alain Takoudjou committed
353 354 355 356 357 358 359
                if transaction_id is not None:
                  # append new result
                  result_list.append(line_list)
                  line_list = []
                transaction_count += 1
                if transaction_count > result_count:
                  break
Bryton Lacquement committed
360 361
                transaction_id = tid
              if not only_failure or level == 'ERROR':
Alain Takoudjou committed
362
                line_list.insert(0, {
Bryton Lacquement committed
363
                  'date': datetime.strptime(date,
Alain Takoudjou committed
364
                                            '%Y-%m-%d %H:%M:%S'),
Bryton Lacquement committed
365 366
                  'status': level,
                  'message': (msg + line_part).strip(),
Alain Takoudjou committed
367
                })
Bryton Lacquement committed
368
              line_part = ""
Alain Takoudjou committed
369
            else:
Bryton Lacquement committed
370 371
              line_part = '\n' + bytes2str(line) + line_part
            line = b""
Alain Takoudjou committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

    if len(line_list):
      result_list.append(line_list)
    return result_list

  def __readResultList(self, result_list):
    failed = False
    message = ""
    for result in result_list:
      if result['status'] == 'ERROR':
        failed = True
      message += "\n%s" % result['message']
    return failed, message.strip()

  def __checkPromiseResult(self, result_count=1, failure_amount=1,
      latest_minute=0, is_anomaly=False):
    """
      Test if the latest messages contain `failure_amount` failures.

      @param result_count: maximum number of promise result to check, will not
        exceed the `latest_minute`
      @param latest_minute: test the result from now to the latest X minutes in
        the past.
      @param failure_amount: fail is this amount of failure is found in result
      @param is_anomaly: Say if the result is an AnomalyResult of TestResult
    """

    module = TestResult if not is_anomaly else AnomalyResult
    latest_result_list = self.getLastPromiseResultList(
      result_count=result_count,
      latest_minute=latest_minute,
      only_failure=False
    )
    result_size = len(latest_result_list)
    if result_size == 0:
      return module(problem=False, message="No result found!")
    problem, message = self.__readResultList(latest_result_list[0])
    if not problem:
      # latest execution is OK
      return module(problem=False, message=message)

    i = 1
    failure_found = 1
    while i < result_size and failure_found < failure_amount:
      for result in latest_result_list[i]:
        if result['status'] == 'ERROR':
          failure_found += 1
          break
      i += 1

    if failure_found != failure_amount:
      return module(problem=False, message=message)
    return module(problem=True, message=message)

Alain Takoudjou committed
426 427 428 429 430 431 432
  def __sendResult(self, result_item, retry_amount=3):
    """Send result to queue, retry if error (non blocking)"""
    error = None
    for i in range(0, retry_amount):
      try:
        self.__queue.put_nowait(result_item)
        break
Bryton Lacquement committed
433
      except Queue.Full as e:
Alain Takoudjou committed
434 435 436 437 438
        error = e
        time.sleep(0.5)
    if error:
      raise error

Alain Takoudjou committed
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  def _test(self, result_count=1, failure_amount=1, latest_minute=0):
    """
      Default promise test method
    """
    return self.__checkPromiseResult(
      result_count=result_count,
      failure_amount=failure_amount,
      latest_minute=latest_minute,
      is_anomaly=False
    )

  def _anomaly(self, result_count=1, failure_amount=1, latest_minute=0):
    """
      Default anomaly check method
    """
    return self.__checkPromiseResult(
      result_count=result_count,
      failure_amount=failure_amount,
      latest_minute=latest_minute,
      is_anomaly=True
    )

  @abstractmethod
  def sense(self):
    """Run the promise code and log the result"""

  def anomaly(self):
    """Called to detect if there is an anomaly which require to bang."""
    return self._anomaly()

  def test(self):
    """Test promise and say if problem is detected or not"""
    return self._test()

  def run(self, check_anomaly=False, can_bang=True):
    """
      Method called to run the Promise
      @param check_anomaly: Say if anomaly method should be called
      @param can_bang: Set to True if bang can be called, this parameter should
        be set to False if bang is already called by another promise.
    """
Alain Takoudjou committed
480 481 482 483
    if not self.__is_tested and not self.__is_anomaly_detected:
      message = "It's not allowed to disable both Test and Anomaly in promise!"
      if check_anomaly:
        result = AnomalyResult(problem=True, message=message)
Alain Takoudjou committed
484
      else:
Alain Takoudjou committed
485 486 487 488 489 490 491 492 493 494
        result = TestResult(problem=True, message=message)
      self.__sendResult(PromiseQueueResult(
        path=self.__promise_path,
        name=self.__name,
        title=self.__title,
        item=result
      ))
    elif (not self.__is_tested and not check_anomaly) or \
        (not self.__is_anomaly_detected and check_anomaly):
      # Anomaly or Test is disabled on this promise, send empty result
Alain Takoudjou committed
495 496 497 498 499
      if self.getConfig('slapgrid-version', '') <= '1.4.17':
        # old version cannot send EmptyResult
        self.__sendResult(PromiseQueueResult(item=TestResult()))
      else:
        self.__sendResult(PromiseQueueResult())
Alain Takoudjou committed
500 501
    else:
      try:
Alain Takoudjou committed
502
        self.sense()
Bryton Lacquement committed
503
      except Exception as e:
Alain Takoudjou committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        # log the result
        self.logger.error(str(e))
      if check_anomaly:
        # run sense, anomaly
        try:
          result = self.anomaly()
          if result is None:
            raise ValueError("Promise anomaly method returned 'None'")
        except Exception as e:
          result = AnomalyResult(problem=True, message=str(e))
        else:
          if isinstance(result, AnomalyResult) and result.hasFailed() and can_bang:
            try:
              self.__bang("Promise %s is failing" % self.__title)
            except:
              self.logger.warning(traceback.format_exc())
      else:
        # run sense, test
        try:
          result = self.test()
          if result is None:
            raise ValueError("Promise test method returned 'None'")
        except Exception as e:
          result = TestResult(problem=True, message=str(e))

      # send the result of this promise
      self.__sendResult(PromiseQueueResult(
        path=self.__promise_path,
        name=self.__name,
        title=self.__title,
        item=result
      ))
Alain Takoudjou committed
536 537 538

    if self.__logger_buffer is not None:
      self.__logger_buffer.close()