summaryrefslogtreecommitdiffstats
path: root/roles/lib_openshift/src/class/oc_obj.py
blob: 68f7818e40a86bff01ed37cfeff16d848168b5a3 (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
# pylint: skip-file
# flake8: noqa

# pylint: disable=too-many-instance-attributes
class OCObject(OpenShiftCLI):
    ''' Class to wrap the oc command line tools '''

    # pylint allows 5. we need 6
    # pylint: disable=too-many-arguments
    def __init__(self,
                 kind,
                 namespace,
                 name=None,
                 selector=None,
                 kubeconfig='/etc/origin/master/admin.kubeconfig',
                 verbose=False,
                 all_namespaces=False):
        ''' Constructor for OpenshiftOC '''
        super(OCObject, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose,
                                       all_namespaces=all_namespaces)
        self.kind = kind
        self.name = name
        self.selector = selector

    def get(self):
        '''return a kind by name '''
        results = self._get(self.kind, name=self.name, selector=self.selector)
        if (results['returncode'] != 0 and 'stderr' in results and
                '\"{}\" not found'.format(self.name) in results['stderr']):
            results['returncode'] = 0

        return results

    def delete(self):
        '''delete the object'''
        results = self._delete(self.kind, name=self.name, selector=self.selector)
        if (results['returncode'] != 0 and 'stderr' in results and
                '\"{}\" not found'.format(self.name) in results['stderr']):
            results['returncode'] = 0

        return results

    def create(self, files=None, content=None):
        '''
           Create a config

           NOTE: This creates the first file OR the first conent.
           TODO: Handle all files and content passed in
        '''
        if files:
            return self._create(files[0])

        # pylint: disable=no-member
        # The purpose of this change is twofold:
        # - we need a check to only use the ruamel specific dumper if ruamel is loaded
        # - the dumper or the flow style change is needed so openshift is able to parse
        # the resulting yaml, at least until gopkg.in/yaml.v2 is updated
        if hasattr(yaml, 'RoundTripDumper'):
            content['data'] = yaml.dump(content['data'], Dumper=yaml.RoundTripDumper)
        else:
            content['data'] = yaml.safe_dump(content['data'], default_flow_style=False)

        content_file = Utils.create_tmp_files_from_contents(content)[0]

        return self._create(content_file['path'])

    # pylint: disable=too-many-function-args
    def update(self, files=None, content=None, force=False):
        '''update a current openshift object

           This receives a list of file names or content
           and takes the first and calls replace.

           TODO: take an entire list
        '''
        if files:
            return self._replace(files[0], force)

        if content and 'data' in content:
            content = content['data']

        return self.update_content(content, force)

    def update_content(self, content, force=False):
        '''update an object through using the content param'''
        return self._replace_content(self.kind, self.name, content, force=force)

    def needs_update(self, files=None, content=None, content_type='yaml'):
        ''' check to see if we need to update '''
        objects = self.get()
        if objects['returncode'] != 0:
            return objects

        data = None
        if files:
            data = Utils.get_resource_file(files[0], content_type)
        elif content and 'data' in content:
            data = content['data']
        else:
            data = content

            # if equal then no need.  So not equal is True
        return not Utils.check_def_equal(data, objects['results'][0], skip_keys=None, debug=False)

    # pylint: disable=too-many-return-statements,too-many-branches
    @staticmethod
    def run_ansible(params, check_mode=False):
        '''perform the ansible idempotent code'''

        ocobj = OCObject(params['kind'],
                         params['namespace'],
                         params['name'],
                         params['selector'],
                         kubeconfig=params['kubeconfig'],
                         verbose=params['debug'],
                         all_namespaces=params['all_namespaces'])

        state = params['state']

        api_rval = ocobj.get()

        #####
        # Get
        #####
        if state == 'list':
            return {'changed': False, 'results': api_rval, 'state': state}

        ########
        # Delete
        ########
        if state == 'absent':
            # verify its not in our results
            if (params['name'] is not None or params['selector'] is not None) and \
               (len(api_rval['results']) == 0 or \
               ('items' in api_rval['results'][0] and len(api_rval['results'][0]['items']) == 0)):
                return {'changed': False, 'state': state}

            if check_mode:
                return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete'}

            api_rval = ocobj.delete()

            if api_rval['returncode'] != 0:
                return {'failed': True, 'msg': api_rval}

            return {'changed': True, 'results': api_rval, 'state': state}

        # create/update: Must define a name beyond this point
        if not params['name']:
            return {'failed': True, 'msg': 'Please specify a name when state is present.'}

        if state == 'present':
            ########
            # Create
            ########
            if not Utils.exists(api_rval['results'], params['name']):

                if check_mode:
                    return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create'}

                # Create it here
                api_rval = ocobj.create(params['files'], params['content'])
                if api_rval['returncode'] != 0:
                    return {'failed': True, 'msg': api_rval}

                # return the created object
                api_rval = ocobj.get()

                if api_rval['returncode'] != 0:
                    return {'failed': True, 'msg': api_rval}

                # Remove files
                if params['files'] and params['delete_after']:
                    Utils.cleanup(params['files'])

                return {'changed': True, 'results': api_rval, 'state': state}

            ########
            # Update
            ########
            # if a file path is passed, use it.
            update = ocobj.needs_update(params['files'], params['content'])
            if not isinstance(update, bool):
                return {'failed': True, 'msg': update}

            # No changes
            if not update:
                if params['files'] and params['delete_after']:
                    Utils.cleanup(params['files'])

                return {'changed': False, 'results': api_rval['results'][0], 'state': state}

            if check_mode:
                return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}

            api_rval = ocobj.update(params['files'],
                                    params['content'],
                                    params['force'])


            if api_rval['returncode'] != 0:
                return {'failed': True, 'msg': api_rval}

            # return the created object
            api_rval = ocobj.get()

            if api_rval['returncode'] != 0:
                return {'failed': True, 'msg': api_rval}

            return {'changed': True, 'results': api_rval, 'state': state}