ganeti.hooks_unittest.py 9.6 KB
Newer Older
Iustin Pop's avatar
Iustin Pop 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
#!/usr/bin/python
#

# Copyright (C) 2006, 2007 Google Inc.
#
# 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 2 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., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Script for unittesting the hooks module"""


import unittest
import os
import time
import tempfile
import os.path

from ganeti import errors
from ganeti import opcodes
from ganeti import mcpu
from ganeti import backend
from ganeti import constants
from ganeti import cmdlib
37
from ganeti import rpc
Iustin Pop's avatar
Iustin Pop committed
38
39
from ganeti.constants import HKR_SUCCESS, HKR_FAIL, HKR_SKIP

Michael Hanselmann's avatar
Michael Hanselmann committed
40
from mocks import FakeConfig, FakeProc, FakeContext
Iustin Pop's avatar
Iustin Pop committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

class FakeLU(cmdlib.LogicalUnit):
  HPATH = "test"
  def BuildHooksEnv(self):
    return {}, ["localhost"], ["localhost"]

class TestHooksRunner(unittest.TestCase):
  """Testing case for HooksRunner"""
  def setUp(self):
    self.torm = []
    self.tmpdir = tempfile.mkdtemp()
    self.torm.append((self.tmpdir, True))
    self.logdir = tempfile.mkdtemp()
    self.torm.append((self.logdir, True))
    self.hpath = "fake"
    self.ph_dirs = {}
    for i in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      dname = "%s/%s-%s.d" % (self.tmpdir, self.hpath, i)
      os.mkdir(dname)
      self.torm.append((dname, True))
      self.ph_dirs[i] = dname
    self.hr = backend.HooksRunner(hooks_base_dir=self.tmpdir)

  def tearDown(self):
    self.torm.reverse()
    for path, kind in self.torm:
      if kind:
        os.rmdir(path)
      else:
        os.unlink(path)

  def _rname(self, fname):
    return "/".join(fname.split("/")[-2:])

  def testEmpty(self):
    """Test no hooks"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
78
79
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
                           (True, []))
Iustin Pop's avatar
Iustin Pop committed
80
81
82
83
84
85
86
87
88

  def testSkipNonExec(self):
    """Test skip non-exec file"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      fname = "%s/test" % self.ph_dirs[phase]
      f = open(fname, "w")
      f.close()
      self.torm.append((fname, False))
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
89
                           (True, [(self._rname(fname), HKR_SKIP, "")]))
Iustin Pop's avatar
Iustin Pop committed
90
91
92
93
94
95
96
97
98
99
100

  def testSkipInvalidName(self):
    """Test skip script with invalid name"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      fname = "%s/a.off" % self.ph_dirs[phase]
      f = open(fname, "w")
      f.write("#!/bin/sh\nexit 0\n")
      f.close()
      os.chmod(fname, 0700)
      self.torm.append((fname, False))
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
101
                           (True, [(self._rname(fname), HKR_SKIP, "")]))
Iustin Pop's avatar
Iustin Pop committed
102
103
104
105
106
107
108
109

  def testSkipDir(self):
    """Test skip directory"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      fname = "%s/testdir" % self.ph_dirs[phase]
      os.mkdir(fname)
      self.torm.append((fname, True))
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
110
                           (True, [(self._rname(fname), HKR_SKIP, "")]))
Iustin Pop's avatar
Iustin Pop committed
111
112
113
114
115
116
117
118
119
120
121

  def testSuccess(self):
    """Test success execution"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      fname = "%s/success" % self.ph_dirs[phase]
      f = open(fname, "w")
      f.write("#!/bin/sh\nexit 0\n")
      f.close()
      self.torm.append((fname, False))
      os.chmod(fname, 0700)
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
122
                           (True, [(self._rname(fname), HKR_SUCCESS, "")]))
Iustin Pop's avatar
Iustin Pop committed
123
124
125
126
127
128
129
130

  def testSymlink(self):
    """Test running a symlink"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      fname = "%s/success" % self.ph_dirs[phase]
      os.symlink("/bin/true", fname)
      self.torm.append((fname, False))
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
131
                           (True, [(self._rname(fname), HKR_SUCCESS, "")]))
Iustin Pop's avatar
Iustin Pop committed
132
133
134
135
136
137
138
139
140
141
142

  def testFail(self):
    """Test success execution"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      fname = "%s/success" % self.ph_dirs[phase]
      f = open(fname, "w")
      f.write("#!/bin/sh\nexit 1\n")
      f.close()
      self.torm.append((fname, False))
      os.chmod(fname, 0700)
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
143
                           (True, [(self._rname(fname), HKR_FAIL, "")]))
Iustin Pop's avatar
Iustin Pop committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

  def testCombined(self):
    """Test success, failure and skip all in one test"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      expect = []
      for fbase, ecode, rs in [("00succ", 0, HKR_SUCCESS),
                               ("10fail", 1, HKR_FAIL),
                               ("20inv.", 0, HKR_SKIP),
                               ]:
        fname = "%s/%s" % (self.ph_dirs[phase], fbase)
        f = open(fname, "w")
        f.write("#!/bin/sh\nexit %d\n" % ecode)
        f.close()
        self.torm.append((fname, False))
        os.chmod(fname, 0700)
        expect.append((self._rname(fname), rs, ""))
160
161
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
                           (True, expect))
Iustin Pop's avatar
Iustin Pop committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176

  def testOrdering(self):
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      expect = []
      for fbase in ["10s1",
                    "00s0",
                    "10sa",
                    "80sc",
                    "60sd",
                    ]:
        fname = "%s/%s" % (self.ph_dirs[phase], fbase)
        os.symlink("/bin/true", fname)
        self.torm.append((fname, False))
        expect.append((self._rname(fname), HKR_SUCCESS, ""))
      expect.sort()
177
178
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}),
                           (True, expect))
Iustin Pop's avatar
Iustin Pop committed
179
180
181
182
183
184
185
186
187

  def testEnv(self):
    """Test environment execution"""
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      fbase = "success"
      fname = "%s/%s" % (self.ph_dirs[phase], fbase)
      os.symlink("/usr/bin/env", fname)
      self.torm.append((fname, False))
      env_snt = {"PHASE": phase}
Iustin Pop's avatar
Iustin Pop committed
188
      env_exp = "PHASE=%s" % phase
Iustin Pop's avatar
Iustin Pop committed
189
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, env_snt),
190
191
                           (True, [(self._rname(fname), HKR_SUCCESS,
                                    env_exp)]))
Iustin Pop's avatar
Iustin Pop committed
192
193
194
195
196
197
198
199
200
201
202
203
204


class TestHooksMaster(unittest.TestCase):
  """Testing case for HooksMaster"""

  def _call_false(*args):
    """Fake call_hooks_runner function which returns False."""
    return False

  @staticmethod
  def _call_nodes_false(node_list, hpath, phase, env):
    """Fake call_hooks_runner function.

205
206
    @rtype: dict of node -> L{rpc.RpcResult} with an rpc error
    @return: rpc failure from all nodes
Iustin Pop's avatar
Iustin Pop committed
207
208

    """
209
210
    return dict([(node, rpc.RpcResult('error', failed=True,
                  node=node, call='FakeError')) for node in node_list])
Iustin Pop's avatar
Iustin Pop committed
211
212
213
214
215

  @staticmethod
  def _call_script_fail(node_list, hpath, phase, env):
    """Fake call_hooks_runner function.

216
217
    @rtype: dict of node -> L{rpc.RpcResult} with a failed script result
    @return: script execution failure from all nodes
Iustin Pop's avatar
Iustin Pop committed
218
219

    """
220
221
222
223
    rr = rpc.RpcResult
    return dict([(node, rr((True, [("utest", constants.HKR_FAIL, "err")]),
                           node=node, call='FakeScriptFail'))
                  for node in node_list])
Iustin Pop's avatar
Iustin Pop committed
224
225
226
227
228

  @staticmethod
  def _call_script_succeed(node_list, hpath, phase, env):
    """Fake call_hooks_runner function.

229
230
    @rtype: dict of node -> L{rpc.RpcResult} with a successful script result
    @return: script execution from all nodes
Iustin Pop's avatar
Iustin Pop committed
231
232

    """
233
234
235
236
    rr = rpc.RpcResult
    return dict([(node, rr(True, [("utest", constants.HKR_SUCCESS, "ok")],
                           node=node, call='FakeScriptOk'))
                 for node in node_list])
Iustin Pop's avatar
Iustin Pop committed
237

238
239
  def setUp(self):
    self.op = opcodes.OpCode()
Guido Trotter's avatar
Guido Trotter committed
240
    self.context = FakeContext()
Iustin Pop's avatar
Iustin Pop committed
241
242
    # WARNING: here we pass None as RpcRunner instance since we know
    # our usage via HooksMaster will not use lu.rpc
243
    self.lu = FakeLU(FakeProc(), self.op, self.context, None)
244

Iustin Pop's avatar
Iustin Pop committed
245
246
  def testTotalFalse(self):
    """Test complete rpc failure"""
247
    hm = mcpu.HooksMaster(self._call_false, FakeProc(), self.lu)
Iustin Pop's avatar
Iustin Pop committed
248
249
250
251
252
    self.failUnlessRaises(errors.HooksFailure,
                          hm.RunPhase, constants.HOOKS_PHASE_PRE)
    hm.RunPhase(constants.HOOKS_PHASE_POST)

  def testIndividualFalse(self):
253
    """Test individual node failure"""
254
    hm = mcpu.HooksMaster(self._call_nodes_false, FakeProc(), self.lu)
255
256
257
    hm.RunPhase(constants.HOOKS_PHASE_PRE)
    #self.failUnlessRaises(errors.HooksFailure,
    #                      hm.RunPhase, constants.HOOKS_PHASE_PRE)
Iustin Pop's avatar
Iustin Pop committed
258
259
260
261
    hm.RunPhase(constants.HOOKS_PHASE_POST)

  def testScriptFalse(self):
    """Test individual rpc failure"""
262
    hm = mcpu.HooksMaster(self._call_script_fail, FakeProc(), self.lu)
Iustin Pop's avatar
Iustin Pop committed
263
264
265
266
267
268
    self.failUnlessRaises(errors.HooksAbort,
                          hm.RunPhase, constants.HOOKS_PHASE_PRE)
    hm.RunPhase(constants.HOOKS_PHASE_POST)

  def testScriptSucceed(self):
    """Test individual rpc failure"""
269
    hm = mcpu.HooksMaster(self._call_script_succeed, FakeProc(), self.lu)
Iustin Pop's avatar
Iustin Pop committed
270
271
272
273
274
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      hm.RunPhase(phase)

if __name__ == '__main__':
  unittest.main()