pkgng 9.81 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2013, bleader
# Written by bleader <bleader@ratonland.org>
# Based on pkgin module written by Shaun Zinck <shaun.zinck at gmail.com>
# that was based on pacman module written by Afterburn <http://github.com/afterburn> 
#  that was based on apt module written by Matthew Williams <matthew@flowroute.com>
#
# This module 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 software 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 software.  If not, see <http://www.gnu.org/licenses/>.


DOCUMENTATION = '''
---
module: pkgng
short_description: Package manager for FreeBSD >= 9.0
description:
    - Manage binary packages for FreeBSD using 'pkgng' which
      is available in versions after 9.0.
version_added: "1.2"
options:
    name:
        description:
            - name of package to install/remove
        required: true
    state:
        description:
            - state of the package
        choices: [ 'present', 'absent' ]
        required: false
        default: present
    cached:
        description:
            - use local package base or try to fetch an updated one
        choices: [ 'yes', 'no' ]
        required: false
        default: no
49 50 51 52 53 54 55 56
    annotation:
        description:
            - a comma-separated list of keyvalue-pairs of the form
              <+/-/:><key>[=<value>]. A '+' denotes adding an annotation, a
              '-' denotes removing an annotation, and ':' denotes modifying an 
              annotation.
              If setting or modifying annotations, a value must be provided.
        required: false
57
        version_added: "1.6"
58 59
    pkgsite:
        description:
60 61 62 63 64
            - for pkgng versions before 1.1.4, specify packagesite to use
              for downloading packages, if not specified, use settings from
              /usr/local/etc/pkg.conf
              for newer pkgng versions, specify a the name of a repository
              configured in /usr/local/etc/pkg/repos
65 66 67 68
        required: false
author: bleader
notes:
    - When using pkgsite, be careful that already in cache packages won't be downloaded again.
69 70 71 72 73 74
'''

EXAMPLES = '''
# Install package foo
- pkgng: name=foo state=present

75 76 77
# Annotate package foo and bar
- pkgng: name=foo,bar annotation=+test1=baz,-test2,:test3=foobar

78 79
# Remove packages foo and bar 
- pkgng: name=foo,bar state=absent
80 81 82 83 84 85
'''


import json
import shlex
import os
86
import re
87 88
import sys

89
def query_package(module, pkgng_path, name):
90

91
    rc, out, err = module.run_command("%s info -g -e %s" % (pkgng_path, name))
92 93 94 95 96 97

    if rc == 0:
        return True

    return False

98
def pkgng_older_than(module, pkgng_path, compare_version):
99

100
    rc, out, err = module.run_command("%s -v" % pkgng_path)
101 102 103 104 105 106 107 108 109 110 111 112 113
    version = map(lambda x: int(x), re.split(r'[\._]', out))

    i = 0
    new_pkgng = True
    while compare_version[i] == version[i]:
        i += 1
        if i == min(len(compare_version), len(version)):
            break
    else:
        if compare_version[i] > version[i]:
            new_pkgng = False
    return not new_pkgng

114

115
def remove_packages(module, pkgng_path, packages):
116 117 118 119 120
    
    remove_c = 0
    # Using a for loop incase of error, we can report the package that failed
    for package in packages:
        # Query the package first, to see if we even need to remove
121
        if not query_package(module, pkgng_path, package):
122 123
            continue

abelbabel committed
124
        if not module.check_mode:
125
            rc, out, err = module.run_command("%s delete -y %s" % (pkgng_path, package))
126

127
        if not module.check_mode and query_package(module, pkgng_path, package):
128 129 130 131 132 133
            module.fail_json(msg="failed to remove %s: %s" % (package, out))
    
        remove_c += 1

    if remove_c > 0:

134
        return (True, "removed %s package(s)" % remove_c)
135

136
    return (False, "package(s) already absent")
137 138


139
def install_packages(module, pkgng_path, packages, cached, pkgsite):
140 141 142

    install_c = 0

143 144
    # as of pkg-1.1.4, PACKAGESITE is deprecated in favor of repository definitions
    # in /usr/local/etc/pkg/repos
145
    old_pkgng = pkgng_older_than(module, pkgng_path, [1, 1, 4])
146 147 148 149 150
    if pkgsite != "":
        if old_pkgng:
            pkgsite = "PACKAGESITE=%s" % (pkgsite)
        else:
            pkgsite = "-r %s" % (pkgsite)
151

152
    if not module.check_mode and not cached:
153
        if old_pkgng:
154
            rc, out, err = module.run_command("%s %s update" % (pkgsite, pkgng_path))
155
        else:
156
            rc, out, err = module.run_command("%s update" % (pkgng_path))
157 158 159 160
        if rc != 0:
            module.fail_json(msg="Could not update catalogue")

    for package in packages:
161
        if query_package(module, pkgng_path, package):
162 163
            continue

abelbabel committed
164
        if not module.check_mode:
165
            if old_pkgng:
166
                rc, out, err = module.run_command("%s %s install -g -U -y %s" % (pkgsite, pkgng_path, package))
167
            else:
168
                rc, out, err = module.run_command("%s install %s -g -U -y %s" % (pkgng_path, pkgsite, package))
169

170
        if not module.check_mode and not query_package(module, pkgng_path, package):
171
            module.fail_json(msg="failed to install %s: %s" % (package, out), stderr=err)
172 173 174 175

        install_c += 1
    
    if install_c > 0:
176
        return (True, "added %s package(s)" % (install_c))
177

178
    return (False, "package(s) already present")
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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
def annotation_query(module, pkgng_path, package, tag):
    rc, out, err = module.run_command("%s info -g -A %s" % (pkgng_path, package))
    match = re.search(r'^\s*(?P<tag>%s)\s*:\s*(?P<value>\w+)' % tag, out, flags=re.MULTILINE)
    if match:
        return match.group('value')
    return False


def annotation_add(module, pkgng_path, package, tag, value):
    _value = annotation_query(module, pkgng_path, package, tag)
    if not _value:
        # Annotation does not exist, add it.
        rc, out, err = module.run_command('%s annotate -y -A %s %s "%s"'
            % (pkgng_path, package, tag, value))
        if rc != 0:
            module.fail_json("could not annotate %s: %s"
                % (package, out), stderr=err)
        return True
    elif _value != value:
        # Annotation exists, but value differs
        module.fail_json(
            mgs="failed to annotate %s, because %s is already set to %s, but should be set to %s"
            % (package, tag, _value, value))
        return False
    else:
        # Annotation exists, nothing to do
        return False

def annotation_delete(module, pkgng_path, package, tag, value):
    _value = annotation_query(module, pkgng_path, package, tag)
    if _value:
        rc, out, err = module.run_command('%s annotate -y -D %s %s'
            % (pkgng_path, package, tag))
        if rc != 0:
            module.fail_json("could not delete annotation to %s: %s"
                % (package, out), stderr=err)
        return True
    return False

def annotation_modify(module, pkgng_path, package, tag, value):
    _value = annotation_query(module, pkgng_path, package, tag)
    if not value:
        # No such tag
        module.fail_json("could not change annotation to %s: tag %s does not exist"
            % (package, tag))
    elif _value == value:
        # No change in value
        return False
    else:
        rc,out,err = module.run_command('%s annotate -y -M %s %s "%s"'
            % (pkgng_path, package, tag, value))
        if rc != 0:
            module.fail_json("could not change annotation annotation to %s: %s"
                % (package, out), stderr=err)
        return True


def annotate_packages(module, pkgng_path, packages, annotation):
    annotate_c = 0
    annotations = map(lambda _annotation:
        re.match(r'(?P<operation>[\+-:])(?P<tag>\w+)(=(?P<value>\w+))?',
            _annotation).groupdict(),
        re.split(r',', annotation))

    operation = {
        '+': annotation_add,
        '-': annotation_delete,
        ':': annotation_modify
    }

    for package in packages:
        for _annotation in annotations:
            annotate_c += ( 1 if operation[_annotation['operation']](
                module, pkgng_path, package,
                _annotation['tag'], _annotation['value']) else 0 )

    if annotate_c > 0:
        return (True, "added %s annotations." % annotate_c)
    return (False, "changed no annotations")
259 260 261

def main():
    module = AnsibleModule(
abelbabel committed
262
            argument_spec       = dict(
263
                state           = dict(default="present", choices=["present","absent"], required=False),
abelbabel committed
264
                name            = dict(aliases=["pkg"], required=True),
265
                cached          = dict(default=False, type='bool'),
266
                annotation      = dict(default="", required=False),
abelbabel committed
267
                pkgsite         = dict(default="", required=False)),
abelbabel committed
268
            supports_check_mode = True)
269

270
    pkgng_path = module.get_bin_path('pkg', True)
271 272 273 274 275

    p = module.params

    pkgs = p["name"].split(",")

276 277 278
    changed = False
    msgs = []

279
    if p["state"] == "present":
280 281 282
        _changed, _msg = install_packages(module, pkgng_path, pkgs, p["cached"], p["pkgsite"])
        changed = changed or _changed
        msgs.append(_msg)
283 284

    elif p["state"] == "absent":
285 286 287 288 289 290 291 292 293 294 295 296
        _changed, _msg = remove_packages(module, pkgng_path, pkgs)
        changed = changed or _changed
        msgs.append(_msg)

    if p["annotation"]:
        _changed, _msg = annotate_packages(module, pkgng_path, pkgs, p["annotation"])
        changed = changed or _changed
        msgs.append(_msg)

    module.exit_json(changed=changed, msg=", ".join(msgs))


297

298
# import module snippets
299
from ansible.module_utils.basic import *
300 301
    
main()