slaprunner.py 10.3 KB
Newer Older
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
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2013 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 adviced 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.
#
##############################################################################

from .resiliencytestsuite import ResiliencyTestSuite

31
import base64
32
from six.moves import http_cookiejar as cookielib
33
import json
34
from lxml import etree
35
import random
36
import ssl
37 38
import string
import time
39 40 41
from six.moves.urllib.request import HTTPCookieProcessor, HTTPSHandler, \
                                     build_opener
from six.moves.urllib.error import HTTPError
42 43 44 45 46 47 48 49 50

class NotHttpOkException(Exception):
  pass

class SlaprunnerTestSuite(ResiliencyTestSuite):
  """
  Run Slaprunner Resiliency Test.
  It is highly suggested to read ResiliencyTestSuite code.
  """
51
  def __init__(self, *args, **kwargs):
52 53
    # Setup urllib2 with cookie support
    cookie_jar = cookielib.CookieJar()
54 55
    ssl_context = ssl._create_unverified_context()

56 57 58
    self._opener_director = build_opener(
        HTTPCookieProcessor(cookie_jar),
        HTTPSHandler(context=ssl_context)
59
    )
60

61
    ResiliencyTestSuite.__init__(self, *args, **kwargs)
62

63 64 65 66 67 68 69 70 71 72 73 74 75
  def _getPartitionParameterDict(self):
    """
    Helper.
    Return the partition parameter dict of the main root ("resilient") instance.
    """
    # XXX Hardcoded parameters, should be obtained dynamically
    return self.partition.request(
      software_release=self.software,
      software_type='resilient',
      partition_reference=self.root_instance_name,
      partition_parameter_kw={
        'resiliency-backup-periodicity': '*/6 * * * *',
        'auto-deploy-instance': 'false',
76 77 78
        'auto-deploy': 'true',
        # XXX HACK!
        "slapos-reference": 'slaprunner-erp5-resiliency'
79 80 81
        }
    ).getConnectionParameterDict()
    self.deleteTimestamp()
82

83 84 85 86 87 88
  def _connectToSlaprunner(self, resource, data=None):
    """
    Utility.
    Connect through HTTP to the slaprunner instance.
    Require self.slaprunner_backend_url to be set.
    """
89 90 91 92 93 94
    try:
      url = "%s/%s" % (self.slaprunner_backend_url, resource)
      if data:
        result = self._opener_director.open(url, data=data)
      else:
        result = self._opener_director.open(url)
95

96 97 98
      if result.getcode() is not 200:
        raise NotHttpOkException(result.getcode())
      return result.read()
99
    except HTTPError:
100 101
      self.logger.error('Error when contacting slaprunner at URL: {}'.format(url))
      raise
102 103 104

  def _login(self):
    self.logger.debug('Logging in...')
105
    b64string = base64.encodestring('%s:%s' % (self.slaprunner_user, self.slaprunner_password))[:-1]
106 107 108 109 110 111
    self._opener_director.addheaders = [
        ('Authorization', 'Basic %s' % b64string),
        # By default we will prefer to receive JSON to simplify
        # treatments of the response
        ("Accept", "application/json"),
    ]
112 113 114

  def _retrieveInstanceLogFile(self):
    """
115 116
    Store the logfile (=data) of the instance, check it is not empty nor it is
    html.
117
    """
118
    time.sleep(30)
119
    data = self._connectToSlaprunner(
120 121
        resource='getFileContent',
        data="file=instance_root/slappart0/var/log/log.log"
122
    )
123
    try:
124
        json_data = json.loads(data)
125 126
        if json_data['code'] == 0:
          raise IOError(json_data['result'])
127
        data = json_data['result']
128 129
        self.logger.info('Retrieved data are:\n%s' % data)
    except (ValueError, KeyError):
130
        if data.find('<') != -1:
131 132 133
          raise IOError(
              'Could not retrieve logfile content: retrieved content is html.'
          )
134
        if data.find('Could not load') != -1:
135 136 137
          raise IOError(
              'Could not retrieve logfile content: server could not load the file.'
          )
138
        if data.find('Hello') == -1:
139 140 141
          raise IOError(
              'Could not retrieve logfile content: retrieve content does not match "Hello".'
          )
142 143
    return data

144 145 146 147 148 149
  def _retrieveSoftwareLogFileTail(self, truncate=100):
    """
      Retrieve the tail of the software.log file.
    """
    data = self._connectToSlaprunner(
             resource='getFileLog',
150
             data="filename=instance_root/../software.log&truncate=%s" % truncate)
151 152 153 154 155 156
    try:
      data = json.loads(data)['result']
      self.logger.info('Tail of software.log:\n%s' % data)
    except (ValueError, KeyError):
      self.logger.info("Fail to get software.log")

157 158 159 160 161 162 163 164 165 166 167

  def _waitForSoftwareBuild(self, limit=5000):
    """
    Wait until SR is built or limit reach 0
    """
    def getSRStatus():
      """
      Return current status (-1 in case of connection problem)
      """
      try:
        return self._connectToSlaprunner(resource='isSRReady')
168
      except (NotHttpOkException, HTTPError) as error:
169 170 171 172 173 174 175 176
        # The nginx frontend might timeout before software release is finished.
        self.logger.warning('Problem occured when contacting the server: %s' % error)
        return -1

    status = getSRStatus()
    while limit > 0 and status != '1':
      status = getSRStatus()
      limit -= 1
177 178 179 180
      if status == '0':
        self.logger.info('Software release is Failing to Build. Sleeping...')
      else:
        self.logger.info('Software release is still building. Sleeping...')
181 182 183 184
      time.sleep(20)
      for sleep_wait in range(3):
        self._retrieveSoftwareLogFileTail(truncate=100)
        time.sleep(10)
185

186

187
  def _buildSoftwareRelease(self):
188 189 190
    self.logger.info('Building the Software Release...')
    try:
      self._connectToSlaprunner(resource='runSoftwareProfile')
191
    except (NotHttpOkException, HTTPError):
192 193
      # The nginx frontend might timeout before software release is finished.
      pass
194

195
    self._waitForSoftwareBuild()
196

197
  def _deployInstance(self):
198 199 200
    self.logger.info('Deploying instance...')
    try:
      self._connectToSlaprunner(resource='runInstanceProfile')
201
    except (NotHttpOkException, HTTPError):
202 203
      # The nginx frontend might timeout before someftware release is finished.
      pass
204
    while True:
205
      time.sleep(15)
206 207 208 209
      result = json.loads(self._connectToSlaprunner(resource='slapgridResult', data='position=0&log='))
      if result['instance']['state'] is False:
        break
      self.logger.info('Buildout is still running. Sleeping...')
210 211
    self.logger.info('Instance has been deployed.')

212
  def _gitClone(self):
213
    self.logger.debug('Doing git clone of https://lab.nexedi.com/nexedi/slapos.git..')
214
    try:
215
      data = self._connectToSlaprunner(
216
          resource='cloneRepository',
217
          data='repo=https://lab.nexedi.com/nexedi/slapos.git&name=workspace/slapos&email=slapos@slapos.org&user=slapos'
218
      )
219
      data = json.loads(data)
220
      if data['code'] == 0:
221
        self.logger.warning(data['result'])
222

223
    except (NotHttpOkException, HTTPError):
224 225
      # cloning can be very long.
      # XXX: quite dirty way to check.
226
      while self._connectToSlaprunner('getProjectStatus', data='project=workspace/slapos').find('On branch master') == -1:
227 228
        self.logger.info('git-cloning ongoing, sleeping...')

229
  def _openSoftwareRelease(self, software_release='erp5testnode/testsuite/dummy'):
230
    self.logger.debug('Opening %s software release...' % software_release)
231
    data = self._connectToSlaprunner(
232
        resource='setCurrentProject',
233
        data='path=workspace/slapos/software/%s/' % software_release
234
    )
235
    assert json.loads(data)['code'] != 0, 'Unexpecting result in call to setCurrentProject: %s' % data
236 237

  def generateData(self):
238 239 240
    """
    Generate Data for slaprunner
    """
241 242 243 244 245 246 247 248 249 250

  def pushDataOnMainInstance(self):
    """
    Create a dummy Software Release,
    Build it,
    Wait for build to be successful,
    Deploy instance,
    Wait for instance to be started.
    Store the main IP of the slaprunner for future use.
    """
251
    self.logger.debug('Getting the backend URL...')
252
    parameter_dict = self._getPartitionParameterDict()
253
    self.slaprunner_backend_url = parameter_dict['backend-url']
254
    self.logger.info('backend_url is %s.' % self.slaprunner_backend_url)
255 256
    self.slaprunner_user = parameter_dict['init-user']
    self.slaprunner_password = parameter_dict['init-password']
257 258 259 260 261

    self._login()

    self._gitClone()
    # XXX should be taken from parameter.
262
    self._openSoftwareRelease()
263 264

    self._buildSoftwareRelease()
265
    time.sleep(15)
266 267 268
    self._deployInstance()

    self.data = self._retrieveInstanceLogFile()
269 270 271 272 273 274 275 276 277 278 279 280

  def checkDataOnCloneInstance(self):
    """
    Check that:
      * backend_url is different
      * Software Release profile is the same,
      * Software Release is built and is the same, (?)
      * Instance is deployed and is the same.
    """
    # XXX: does the promise wait for the software to be built and the instance to be ready?
    old_slaprunner_backend_url = self.slaprunner_backend_url
    self.slaprunner_backend_url = self._returnNewInstanceParameter(
281
        parameter_key='backend-url',
282 283
        old_parameter_value=old_slaprunner_backend_url,
        force_new=True,
284 285
    )
    self._login()
286
    self._waitForSoftwareBuild()
287
    time.sleep(15)
288 289
    new_data = self._retrieveInstanceLogFile()

290
    if new_data.startswith(self.data):
291
      self.logger.info('Data are the same: success.')
292
      return True
293 294 295 296 297 298 299 300 301 302
    else:
      self.logger.info('Data are different: failure.')


def runTestSuite(*args, **kwargs):
  """
  Run Slaprunner Resiliency Test.
  """
  return SlaprunnerTestSuite(*args, **kwargs).runTestSuite()