summaryrefslogtreecommitdiffstats
path: root/src/software/cli/software.py
blob: 9ae1172dc5b4441d3b647d1f76f3a4e3315090e3 (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
#!/usr/bin/env python
#
# 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: Michal Minar <miminar@redhat.com>
#

"""
Command line tool for simple software management with OpenLMI CIM software
providers.
"""

import argparse
from collections import defaultdict
import pywbem
import socket
import sys

from lmi.software import util
from lmi.software.core import SystemSoftwareCollection

CIM_ERROR2TEXT = defaultdict(lambda: "OTHER_ERROR", {
    1  : "FAILED",
    2  : "ACCESS_DENIED",
    3  : "INVALID_NAMESPACE",
    4  : "INVALID_PARAMETER",
    5  : "INVALID_CLASS",
    6  : "NOT_FOUND",
    7  : "NOT_SUPPORTED",
    8  : "CLASS_HAS_CHILDREN",
    9  : "CLASS_HAS_INSTANCES",
    10 : "INVALID_SUPERCLASS",
    11 : "ALREADY_EXISTS",
    12 : "NO_SUCH_PROPERTY",
    13 : "TYPE_MISMATCH",
    14 : "QUERY_LANGUAGE_NOT_SUPPORTED",
    15 : "INVALID_QUERY",
    16 : "METHOD_NOT_AVAILABLE",
    17 : "METHOD_NOT_FOUND"
})

class NotFound(Exception):
    """
    Exception raised, when desired package could not be found.
    """
    def __init__(self, package, details=None):
        msg = 'Package "%s" not installed!' % package
        if details is not None:
            msg += ' : '+details
        Exception.__init__(self, msg)

def get_host_name():
    """
    @return computer host name
    """
    if not hasattr(get_host_name, '_hostname'):
        get_host_name._hostname = socket.gethostname()  #pylint: disable=W0212
    return get_host_name._hostname                      #pylint: disable=W0212

def make_pkg_path(name, epoch, ver, rel, arch):
    """
    @return instance name for LMI_SoftwareIdentity
    """
    return pywbem.CIMInstanceName(
            classname="LMI_SoftwareIdentity",
            namespace=util.Configuration.get_instance().namespace,
            keybindings={
                "InstanceID" : util.make_nevra(
                    name, epoch, ver, rel, arch, "ALWAYS")})

def install(_conn, _nevra):
    """Install package by nevra."""
    raise NotImplementedError("Installation is not yet supported!")

def update(_conn, _package, _epoch=None, _version=None, _release=None):
    """Update to particular evr of package."""
    raise NotImplementedError("Update of package is not yet supported!")

def remove(_conn, _package):
    """Remove installed package by its name."""
    raise NotImplementedError("Removal is not yet supported!")

def verify(_conn, _package):
    """Verity installed package by its name."""
    raise NotImplementedError("Verification is not yet supported!")

def list_available(conn):
    """List nevra strings of available packages."""
    inames = conn.AssociatorNames(
            ObjectName=SystemSoftwareCollection.get_path(),
            ResultClass='LMI_SoftwareIdentity',
            AssocClass="LMI_MemberOfSoftwareCollection",
            Role="Collection",
            ResultRole="Member")
    for nevra in (i['InstanceID'] for i in inames):
        print nevra[len("LMI:LMI_SoftwareIdentity:"):]

def list_installed(_conn):
    """List nevra strings of installed packages."""
    raise NotImplementedError(
            "Listing of installed packages is not yet supported!")

def list_files(_conn, _package):
    """List files of installed package."""
    raise NotImplementedError("Listing of package files is not yet supported!")

def parse_args():
    """
    Parse command line arguments and handle related errors.
    @return Namespace object
    """
    parser = argparse.ArgumentParser(prog='software',
            description=("CLI tool for testing OpenLMI software providers."
                         " With this tool you are able to install, update,"
                         " remove and verify particular package."),
            conflict_handler="resolve")
    parser.add_argument('--url',
        help="Specify schema, hostname and port of broker in one argument."
        " For user and password, please use provided options.")
    parser.add_argument('-p', '--port', type=int, default=5989,
        help="Port of cimom broker. Default is %(default)d.")
    parser.add_argument('-h', '--hostname',
        default='localhost', help="Hostname of cimom broker.")
    parser.add_argument('-s', '--schema', choices=('http', 'https'),
        default='https', help="Schema part of url (default is %(default)s)")
    parser.add_argument('-u', '--user', default='',
        help="Under which user to authenticate.")
    parser.add_argument('--password', default='',
        help="User password.")
    parser.add_argument('-d', '--debug', action='store_true', default=False,
        help="Print debugging informations.")
    subpars = parser.add_subparsers(help="Action to make on OpenLMI providers.")

    parse_install = subpars.add_parser('install',
        help="Install specific available package.")
    parse_install.add_argument('nevra', help="Name, epoch, version, release"
        " and architecture of package to install given as:\n"
        "   name-epoch:version-release.arch")
    parse_install.set_defaults(command='install')

    parse_update = subpars.add_parser('update',
        help="Update a package to specific evra or to the newest available.")
    parse_update.add_argument('package',
        help="Name or nevra of installed package.")
    parse_update.add_argument('-e', '--epoch',
        type=int, help="Filter available packages for update by epoch.")
    parse_update.add_argument('-v', '--version',
        help="Filter available packages for update by version.")
    parse_update.add_argument('-r', '--release',
        help="Filter available packages for update by release.")
    parse_update.set_defaults(command='update')

    parse_remove = subpars.add_parser('remove',
        help="Remove installed package.")
    parse_remove.add_argument('package',
        help="Name or nevra of installed package.")
    parse_remove.set_defaults(command='remove')

    parse_verify = subpars.add_parser('verify',
        help="Verify installed package.")
    parse_verify.add_argument('package',
        help="Name or nevra of installed package to verify.")
    parse_verify.set_defaults(command='verify')

    parse_list = subpars.add_parser('list',
        help="List various information depending on next argument."
        " See \"%(prog)s list --help\".")
    parse_list.set_defaults(command='list')

    list_subpars = parse_list.add_subparsers(help="What should be listed.")
    parse_list_available = list_subpars.add_parser("available",
            help="List available packages.")
    parse_list_available.set_defaults(list_kind='available')
    parse_list_installed = list_subpars.add_parser("installed",
            help="List installed packages.")
    parse_list_installed.set_defaults(list_kind='installed')
    parse_list_files = list_subpars.add_parser("files",
            help="List files of installed package.")
    parse_list_files.set_defaults(list_kind='files')
    parse_list_files.add_argument('package',
        help="Name or nevra of installed package.")

    args = parser.parse_args()

    if args.url is None:
        args.url = '%s://%s:%d' % (args.schema, args.hostname, args.port)

    return args

def main(args):
    """
    Main functionality.
    @return return code of script
    """
    auth = (args.user, args.password)
    if args.debug:
        sys.stderr.write('url:\t%s\n'%args.url)
    conn = pywbem.WBEMConnection(args.url, auth)

    if args.command == 'list':
        func, attrs = \
            { 'available' : (list_available, tuple())
            , 'installed' : (list_installed, tuple())
            , 'files'     : (list_files, ('package'))
            }[args.list_kind]
    else:
        func, attrs = \
            { 'install' : (install, ('nevra',))
            , 'update'  : (update,  ('package', 'epoch', 'version', 'release'))
            , 'remove'  : (remove,  ('package',))
            , 'verify'  : (verify,  ('package',))
            }[args.command]
    try:
        func(conn, *(getattr(args, a) for a in attrs))
        return 0
    except pywbem.CIMError as exc:
        sys.stderr.write('Failed: %d (%s) - %s\n' % (
            exc.args[0], CIM_ERROR2TEXT[exc.args[0]],
            exc.args[1].replace('<br>', '\n')))
        return 1
    except NotFound as exc:
        sys.stderr.write(str(exc) + '\n')
        return 1

if __name__ == '__main__':
    ARGS = parse_args()
    sys.exit(main(ARGS))