summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/packaging/os/svr4pkg.py
blob: 5dc28160df23e27ec476dc769bde2877057fffa2 (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
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
259
260
261
262
263
264
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2012, Boyd Adamson <boyd () boydadamson.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}


DOCUMENTATION = '''
---
module: svr4pkg
short_description: Manage Solaris SVR4 packages
description:
    - Manages SVR4 packages on Solaris 10 and 11.
    - These were the native packages on Solaris <= 10 and are available
      as a legacy feature in Solaris 11.
    - Note that this is a very basic packaging system. It will not enforce
      dependencies on install or remove.
version_added: "0.9"
author: "Boyd Adamson (@brontitall)"
options:
  name:
    description:
      - Package name, e.g. C(SUNWcsr)
    required: true

  state:
    description:
      - Whether to install (C(present)), or remove (C(absent)) a package.
      - If the package is to be installed, then I(src) is required.
      - The SVR4 package system doesn't provide an upgrade operation. You need to uninstall the old, then install the new package.
    required: true
    choices: ["present", "absent"]

  src:
    description:
      - Specifies the location to install the package from. Required when C(state=present).
      - "Can be any path acceptable to the C(pkgadd) command's C(-d) option. e.g.: C(somefile.pkg), C(/dir/with/pkgs), C(http:/server/mypkgs.pkg)."
      - If using a file or directory, they must already be accessible by the host. See the M(copy) module for a way to get them there.
  proxy:
    description:
      - HTTP[s] proxy to be used if C(src) is a URL.
  response_file:
    description:
      - Specifies the location of a response file to be used if package expects input on install. (added in Ansible 1.4)
    required: false
  zone:
    description:
      - Whether to install the package only in the current zone, or install it into all zones.
      - The installation into all zones works only if you are working with the global zone.
    required: false
    default: "all"
    choices: ["current", "all"]
    version_added: "1.6"
  category:
    description:
      - Install/Remove category instead of a single package.
    required: false
    type: bool
    version_added: "1.6"
'''

EXAMPLES = '''
# Install a package from an already copied file
- svr4pkg:
    name: CSWcommon
    src: /tmp/cswpkgs.pkg
    state: present

# Install a package directly from an http site
- svr4pkg:
    name: CSWpkgutil
    src: 'http://get.opencsw.org/now'
    state: present
    zone: current

# Install a package with a response file
- svr4pkg:
    name: CSWggrep
    src: /tmp/third-party.pkg
    response_file: /tmp/ggrep.response
    state: present

# Ensure that a package is not installed.
- svr4pkg:
    name: SUNWgnome-sound-recorder
    state: absent

# Ensure that a category is not installed.
- svr4pkg:
    name: FIREFOX
    state: absent
    category: true
'''


import os
import tempfile

from ansible.module_utils.basic import AnsibleModule


def package_installed(module, name, category):
    cmd = [module.get_bin_path('pkginfo', True)]
    cmd.append('-q')
    if category:
        cmd.append('-c')
    cmd.append(name)
    rc, out, err = module.run_command(' '.join(cmd))
    if rc == 0:
        return True
    else:
        return False


def create_admin_file():
    (desc, filename) = tempfile.mkstemp(prefix='ansible_svr4pkg', text=True)
    fullauto = '''
mail=
instance=unique
partial=nocheck
runlevel=quit
idepend=nocheck
rdepend=nocheck
space=quit
setuid=nocheck
conflict=nocheck
action=nocheck
networktimeout=60
networkretries=3
authentication=quit
keystore=/var/sadm/security
proxy=
basedir=default
'''
    os.write(desc, fullauto)
    os.close(desc)
    return filename


def run_command(module, cmd):
    progname = cmd[0]
    cmd[0] = module.get_bin_path(progname, True)
    return module.run_command(cmd)


def package_install(module, name, src, proxy, response_file, zone, category):
    adminfile = create_admin_file()
    cmd = ['pkgadd', '-n']
    if zone == 'current':
        cmd += ['-G']
    cmd += ['-a', adminfile, '-d', src]
    if proxy is not None:
        cmd += ['-x', proxy]
    if response_file is not None:
        cmd += ['-r', response_file]
    if category:
        cmd += ['-Y']
    cmd.append(name)
    (rc, out, err) = run_command(module, cmd)
    os.unlink(adminfile)
    return (rc, out, err)


def package_uninstall(module, name, src, category):
    adminfile = create_admin_file()
    if category:
        cmd = ['pkgrm', '-na', adminfile, '-Y', name]
    else:
        cmd = ['pkgrm', '-na', adminfile, name]
    (rc, out, err) = run_command(module, cmd)
    os.unlink(adminfile)
    return (rc, out, err)


def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            state=dict(required=True, choices=['present', 'absent']),
            src=dict(default=None),
            proxy=dict(default=None),
            response_file=dict(default=None),
            zone=dict(required=False, default='all', choices=['current', 'all']),
            category=dict(default=False, type='bool')
        ),
        supports_check_mode=True
    )
    state = module.params['state']
    name = module.params['name']
    src = module.params['src']
    proxy = module.params['proxy']
    response_file = module.params['response_file']
    zone = module.params['zone']
    category = module.params['category']
    rc = None
    out = ''
    err = ''
    result = {}
    result['name'] = name
    result['state'] = state

    if state == 'present':
        if src is None:
            module.fail_json(name=name,
                             msg="src is required when state=present")
        if not package_installed(module, name, category):
            if module.check_mode:
                module.exit_json(changed=True)
            (rc, out, err) = package_install(module, name, src, proxy, response_file, zone, category)
            # Stdout is normally empty but for some packages can be
            # very long and is not often useful
            if len(out) > 75:
                out = out[:75] + '...'

    elif state == 'absent':
        if package_installed(module, name, category):
            if module.check_mode:
                module.exit_json(changed=True)
            (rc, out, err) = package_uninstall(module, name, src, category)
            out = out[:75]

    # Returncodes as per pkgadd(1m)
    #    0 Successful completion
    #    1 Fatal error.
    #    2 Warning.
    #    3 Interruption.
    #    4 Administration.
    #    5 Administration. Interaction  is  required.  Do  not  use pkgadd -n.
    #   10 Reboot after installation of all packages.
    #   20 Reboot after installation of this package.
    #   99 (observed) pkgadd: ERROR: could not process datastream from </tmp/pkgutil.pkg>
    if rc in (0, 2, 3, 10, 20):
        result['changed'] = True
    # no install nor uninstall, or failed
    else:
        result['changed'] = False

    # rc will be none when the package already was installed and no action took place
    # Only return failed=False when the returncode is known to be good as there may be more
    # undocumented failure return codes
    if rc not in (None, 0, 2, 10, 20):
        result['failed'] = True
    else:
        result['failed'] = False

    if out:
        result['stdout'] = out
    if err:
        result['stderr'] = err

    module.exit_json(**result)


if __name__ == '__main__':
    main()