summaryrefslogtreecommitdiffstats
path: root/src/account/test/TestAccountRaceConditions.py
blob: cd13d6179125f4f73ff87198743c6d59af517ef9 (plain)
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
38
39
40
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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
# -*- encoding: utf-8 -*-
# Copyright(C) 2012-2013 Red Hat, Inc.  All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or(at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors: Alois Mahdal <amahdal@redhat.com>

import lmi.test.util
import methods
from common import AccountBase, PasswdFile
from pywbem import CIMError

import threading


## ......................................................................... ##
## Helper methods
## ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ##

def perform_attempts(tcls, names, args):
    """
    Spawn and wait for one thread per username, passing name and args.

    tcls can be threading.Thread subclass or a callable that returns
    instance of such. Must accept two arguments: username and connection
    to the CIM.  It also must implement attribute "result" to communicate
    result to parent threads.

    args is an arbitrary dict that should contain at least 'ns' for LMI
    Namespace object (usually conn.root.cimv2) plus any other objects that
    particular subclass needs.

    Returns list of results.
    """
    # create, start threads and wait for them to finish
    threads = []
    for name in names:
        threads.append(tcls(name, args))
    [t.start() for t in threads]
    [t.join() for t in threads]
    return [t.result for t in threads]


## ......................................................................... ##
## Threading helper classes
## ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ##

class AccountActionAttempt(threading.Thread):
    """
    Base class to perform an action with account in a thread.
    """

    def __init__(self, username, args):
        threading.Thread.__init__(self)
        self.args = args
        self.username = username
        self.ns = self.args['ns']
        self.result = None

    def _chkargs(self, keys):
        """Check keys in args; raise sensible message"""
        for key in keys:
            if not key in self.args:
                raise ValueError("%s needs %s passed in args"
                                 % (self.__class__.__name__, key))


class CreationAttempt(AccountActionAttempt):
    """
    Try to create user, mute normal errors (error is OK)
    """

    def run(self):
        self._chkargs(['system_iname'])
        system_iname = self.args['system_iname']
        lams = self.ns.LMI_AccountManagementService.first_instance()
        try:
            lams.CreateAccount(Name=self.username, System=system_iname)
            self.result = self.username
        except CIMError:
            # OK, error reported to user
            self.result = False


class ModificationAttempt(AccountActionAttempt):
    """
    Try to modify user
    """

    def run(self):
        account = self.ns.LMI_Account.first_instance({"Name": self.username})
        account.LoginShell = methods.random_shell()
        account.push()


class DeletionAttempt(AccountActionAttempt):
    """
    Try to delete user
    """

    def run(self):
        account = self.ns.LMI_Account.first_instance({"Name": self.username})
        account.DeleteUser()


## ......................................................................... ##
## Actual test
## ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ##

class TestAccountRaceConditions(AccountBase):

    def setUp(self):
        self.user_count = 20        # = thread count
        self.prefix = "user"
        self.names = [lmi.test.util.random_string(strength=8,
                                                  prefix=self.prefix)
                      for i in xrange(self.user_count)]

        self.bs = lmi.test.util.BackupStorage()
        self.bs.add_file("/etc/passwd")
        self.bs.add_file("/etc/shadow")
        self.bs.add_file("/etc/group")
        self.bs.add_file("/etc/gshadow")
        self.args = {'ns': self.ns}

    def tearDown(self):
        self.bs.restore_all()

    def assertPasswdNotCorrupt(self):
        """
        Assert /etc/passwd is not corrupt
        """
        pf = PasswdFile()
        errors = pf.get_errors()
        msg = ("/etc/passwd corrupt: %s\n\nFull text follows:\n%s\n"
               % (errors, pf.fulltext))
        self.assertFalse(errors, msg)

    def assertUserCount(self, count=None):
        """
        Assert particular user count in /etc/passwd (filter on prefix)
        """
        if count is None:
            count = self.user_count
        pf = PasswdFile({'username_prefix': self.prefix})
        oc = count
        rc = len(pf.users)
        self.assertEqual(rc, oc,
                         "wrong user count: %s, expected %s" % (rc, oc))

    def assertUserNameSet(self, nameset=None):
        """
        Assert particular username set in /etc/passwd (filter on prefix)
        """
        if nameset is None:
            nameset = self.names
        pf = PasswdFile({'username_prefix': self.prefix})
        on = sorted(nameset)
        rn = sorted(pf.get_names())
        self.assertEqual(rn, on,
                         "wrong user set: %s, expected %s" % (rn, on))

    def test_create(self):
        """
        Account: Test creations from many threads.
        """
        self.args['system_iname'] = self.system_iname
        created_names = filter(
            lambda r: isinstance(r, basestring),
            perform_attempts(CreationAttempt, self.names, self.args)
        )
        self.assertUserNameSet(created_names)
        self.assertPasswdNotCorrupt()

    def test_modify(self):
        """
        Account: Test modifications from many threads.
        """
        [methods.create_account(n) for n in self.names]
        perform_attempts(ModificationAttempt, self.names, self.args)
        self.assertUserCount()
        self.assertPasswdNotCorrupt()

    def test_delete(self):
        """
        Account: Test deletions from many threads.
        """
        [methods.create_account(n) for n in self.names]
        perform_attempts(DeletionAttempt, self.names, self.args)
        self.assertUserCount(0)
        self.assertPasswdNotCorrupt()