mount 7.87 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#!/usr/bin/python

# (c) 2012, Red Hat, inc
# Written by Seth Vidal
# based on the mount modules from salt and puppet
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible.  If not, see <http://www.gnu.org/licenses/>.

22 23 24 25 26 27 28 29 30 31
# mount module - mount fs and define in fstab
# usage:
#
# mount name=mountpoint, src=device_to_be_mounted fstype=fstype 
#        opts=mount_opts, dump=0 passno=0 state=[present|absent|mounted|unmounted] 
#
#    absent == remove from fstab and unmounted
#    present == add to fstab, do not change mount state
#    mounted == add to fstab if not there and make sure it is mounted
#    unmounted == do not change fstab state, but unmount
32 33 34 35 36 37 38 39 40 41 42

def write_fstab(lines, dest):

    fs_w = open(dest, 'w')
    for l in lines:
        fs_w.write(l)

    fs_w.flush()
    fs_w.close()

def set_mount(**kwargs):
43 44
    """ set/change a mount point location in fstab """

45
    # kwargs: name, src, fstype, opts, dump, passno, state, fstab=/etc/fstab
46 47 48 49 50 51
    args = dict(
        opts   = 'defaults',
        dump   = '0',
        passno = '0',
        fstab  = '/etc/fstab'
    )
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
    args.update(kwargs)

    new_line = '%(src)s %(name)s %(fstype)s %(opts)s %(dump)s %(passno)s\n' 

    to_write = []
    exists = False
    changed = False
    for line in open(args['fstab'], 'r').readlines():
        if not line.strip():
             to_write.append(line)
             continue
        if line.strip().startswith('#'):
            to_write.append(line)
            continue
        if len(line.split()) != 6:
            # not sure what this is or why it is here
            # but it is not our fault so leave it be
            to_write.append(line)
            continue
        
        ld = {}
        ld['src'], ld['name'], ld['fstype'], ld['opts'], ld['dump'], ld['passno']  = line.split()

        if ld['name'] != args['name']:
            to_write.append(line)
            continue

        # it exists - now see if what we have is different
        exists = True
        for t in ('src', 'fstype','opts', 'dump', 'passno'):
            if ld[t] != args[t]:
                changed = True
                ld[t] = args[t]

        if changed:
             to_write.append(new_line % ld)
        else:
             to_write.append(line)
         
    if not exists:
        to_write.append(new_line % args)
        changed = True
    
    if changed:
        write_fstab(to_write, args['fstab'])

    return (args['name'], changed)
            

def unset_mount(**kwargs):
102 103
    """ remove a mount point from fstab """

104
    # kwargs: name, src, fstype, opts, dump, passno, state, fstab=/etc/fstab
105 106 107 108 109 110
    args = dict(
        opts   = 'default',
        dump   = '0',
        passno = '0',
        fstab  = '/etc/fstab'
    )
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
    args.update(kwargs)

    to_write = []
    changed = False
    for line in open(args['fstab'], 'r').readlines():
        if not line.strip():
             to_write.append(line)
             continue
        if line.strip().startswith('#'):
            to_write.append(line)
            continue
        if len(line.split()) != 6:
            # not sure what this is or why it is here
            # but it is not our fault so leave it be
            to_write.append(line)
            continue
        
        ld = {}
        ld['src'], ld['name'], ld['fstype'], ld['opts'], ld['dump'], ld['passno']  = line.split()

        if ld['name'] != args['name']:
            to_write.append(line)
            continue

        # if we got here we found a match - continue and mark changed
        changed = True

    if changed:
        write_fstab(to_write, args['fstab'])

    return (args['name'], changed)

     
def mount(**kwargs):
145 146
    """ mount up a path or remount if needed """

147 148 149 150 151 152 153 154 155 156 157
    name = kwargs['name']
    if os.path.ismount(name):
        cmd = ['/bin/mount', '-o', 'remount', name]
    else:
        cmd = ['/bin/mount', name ]

    call = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = call.communicate()
    if call.returncode == 0:
        return 0, ''
    else:
158
        return call.returncode, out+err
159 160

def umount(**kwargs):
161 162
    """ unmount a path """

163
    name = kwargs['name']
164 165 166 167 168 169 170
    cmd = ['/bin/umount', name]

    call = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = call.communicate()
    if call.returncode == 0:
        return 0, ''
    else:
171 172 173
        return call.returncode, out+err

def main():
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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    module = AnsibleModule(
        argument_spec = dict(
            state  = dict(required=True, choices=['present', 'absent', 'mounted', 'unmounted']),
            name   = dict(required=True),
            opts   = dict(default=None),
            passno = dict(default=None),
            dump   = dict(default=None),
            src    = dict(required=True),
            fstype = dict(required=True),
            fstab  = dict(default=None)
        )
    )
    
    changed = False
    rc = 0
    args = {
        'name': module.params['name'],
        'src': module.params['src'],
        'fstype': module.params['fstype']
    }
    if module.params['passno'] is not None:
        args['passno'] = module.params['passno']
    if module.params['opts'] is not None:
        args['opts'] = module.params['opts']
    if module.params['dump'] is not None:
        args['dump'] = module.params['dump']
    if module.params['fstab'] is not None:
        args['fstab'] = module.params['fstab']
    
    # absent == remove from fstab and unmounted
    # unmounted == do not change fstab state, but unmount
    # present == add to fstab, do not change mount state
    # mounted == add to fstab if not there and make sure it is mounted, if it has changed in fstab then remount it
    
    state = module.params['state']
    name  = module.params['name']
    if state == 'absent':
        name, changed = unset_mount(**args)
        if changed:
            if os.path.ismount(name):
                res,msg  = umount(**args)
                if res:
                    fail_json(msg="Error unmounting %s: %s" % (name, msg))
    
            if os.path.exists(name):
                try:
                    os.rmdir(name)
                except (OSError, IOError), e:
                    fail_json(msg="Error rmdir %s: %s" % (name, str(e)))
    
        module.exit_json(changed=changed, **args)
    
    if state == 'unmounted':
228 229 230 231
        if os.path.ismount(name):
            res,msg  = umount(**args)
            if res:
                fail_json(msg="Error unmounting %s: %s" % (name, msg))
232
            changed = True
233
    
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        module.exit_json(changed=changed, **args)
    
    if state in ['mounted', 'present']:
        name, changed = set_mount(**args)
        if state == 'mounted':
            if not os.path.exists(name):
                try:
                    os.makedirs(name)
                except (OSError, IOError), e:
                    fail_json(msg="Error making dir %s: %s" % (name, str(e)))
    
            res = 0
            if os.path.ismount(name):
                if changed:
                    res,msg = mount(**args)
            else:
                changed = True
251
                res,msg = mount(**args)
252 253 254 255 256 257 258 259 260 261 262 263 264
    
            if res:
                fail_json(msg="Error mounting %s: %s" % (name, msg))
    
    
        module.exit_json(changed=changed, **args)
    
    module.fail_json(msg='Unexpected position reached')
    sys.exit(0)
    
# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()