ganeti.hooks_unittest.py 9.36 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
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}), [])
Iustin Pop's avatar
Iustin Pop committed
79
80
81
82
83
84
85
86
87

  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, {}),
88
                           [(self._rname(fname), HKR_SKIP, "")])
Iustin Pop's avatar
Iustin Pop committed
89
90
91
92
93
94
95
96
97
98
99

  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, {}),
100
                           [(self._rname(fname), HKR_SKIP, "")])
Iustin Pop's avatar
Iustin Pop committed
101
102
103
104
105
106
107
108

  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, {}),
109
                           [(self._rname(fname), HKR_SKIP, "")])
Iustin Pop's avatar
Iustin Pop committed
110
111
112
113
114
115
116
117
118
119
120

  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, {}),
121
                           [(self._rname(fname), HKR_SUCCESS, "")])
Iustin Pop's avatar
Iustin Pop committed
122
123
124
125
126
127
128
129

  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, {}),
130
                           [(self._rname(fname), HKR_SUCCESS, "")])
Iustin Pop's avatar
Iustin Pop committed
131
132
133
134
135
136
137
138
139
140
141

  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, {}),
142
                           [(self._rname(fname), HKR_FAIL, "")])
Iustin Pop's avatar
Iustin Pop committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158

  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, ""))
159
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}), expect)
Iustin Pop's avatar
Iustin Pop committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

  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()
175
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, {}), expect)
Iustin Pop's avatar
Iustin Pop committed
176
177
178
179
180
181
182
183
184

  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
185
      env_exp = "PHASE=%s" % phase
Iustin Pop's avatar
Iustin Pop committed
186
      self.failUnlessEqual(self.hr.RunHooks(self.hpath, phase, env_snt),
187
                           [(self._rname(fname), HKR_SUCCESS, env_exp)])
Iustin Pop's avatar
Iustin Pop committed
188
189
190
191
192
193
194
195
196
197
198
199
200


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.

201
202
    @rtype: dict of node -> L{rpc.RpcResult} with an rpc error
    @return: rpc failure from all nodes
Iustin Pop's avatar
Iustin Pop committed
203
204

    """
205
206
    return dict([(node, rpc.RpcResult('error', failed=True,
                  node=node, call='FakeError')) for node in node_list])
Iustin Pop's avatar
Iustin Pop committed
207
208
209
210
211

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

212
213
    @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
214
215

    """
216
217
218
219
    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
220
221
222
223
224

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

225
226
    @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
227
228

    """
229
230
231
232
    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
233

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

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

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

  def testScriptFalse(self):
    """Test individual rpc failure"""
258
    hm = mcpu.HooksMaster(self._call_script_fail, self.lu)
Iustin Pop's avatar
Iustin Pop committed
259
260
261
262
263
264
    self.failUnlessRaises(errors.HooksAbort,
                          hm.RunPhase, constants.HOOKS_PHASE_PRE)
    hm.RunPhase(constants.HOOKS_PHASE_POST)

  def testScriptSucceed(self):
    """Test individual rpc failure"""
265
    hm = mcpu.HooksMaster(self._call_script_succeed, self.lu)
Iustin Pop's avatar
Iustin Pop committed
266
267
268
269
270
    for phase in (constants.HOOKS_PHASE_PRE, constants.HOOKS_PHASE_POST):
      hm.RunPhase(phase)

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