summaryrefslogtreecommitdiffstats
path: root/azure/aria/aria-extension-cloudify/adapters/context_adapter.py
blob: 9e540aed8785b16e08f607b7f720c08bbe481c29 (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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#
# Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#

import os
import tempfile

from aria.orchestrator.context import operation


DEPLOYMENT = 'deployment'
NODE_INSTANCE = 'node-instance'
RELATIONSHIP_INSTANCE = 'relationship-instance'


class CloudifyContextAdapter(object):

    def __init__(self, ctx):
        self._ctx = ctx
        self._blueprint = BlueprintAdapter(ctx)
        self._deployment = DeploymentAdapter(ctx)
        self._operation = OperationAdapter(ctx)
        self._bootstrap_context = BootstrapAdapter(ctx)
        self._plugin = PluginAdapter(ctx)
        self._agent = CloudifyAgentAdapter()
        self._node = None
        self._node_instance = None
        self._source = None
        self._target = None
        if isinstance(ctx, operation.NodeOperationContext):
            self._node = NodeAdapter(ctx, ctx.node_template, ctx.node)
            self._instance = NodeInstanceAdapter(ctx, ctx.node, True)
        elif isinstance(ctx, operation.RelationshipOperationContext):
            self._source = RelationshipTargetAdapter(
                ctx,
                ctx.source_node_template,
                ctx.source_node,
                True
            )
            self._target = RelationshipTargetAdapter(
                ctx,
                ctx.target_node_template,
                ctx.target_node,
                True
            )

    def __getattr__(self, item):
        try:
            return getattr(self._ctx, item)
        except AttributeError:
            return super(CloudifyContextAdapter, self).__getattribute__(item)

    @property
    def blueprint(self):
        return self._blueprint

    @property
    def deployment(self):
        return self._deployment

    @property
    def operation(self):
        return self._operation

    @property
    def bootstrap_context(self):
        return self._bootstrap_context

    @property
    def plugin(self):
        return self._plugin

    @property
    def agent(self):
        return self._agent

    @property
    def type(self):
        if self._source:
            return RELATIONSHIP_INSTANCE
        elif self._instance:
            return NODE_INSTANCE
        else:
            return DEPLOYMENT

    @property
    def instance(self):
        self._verify_in_node_operation()
        return self._instance

    @property
    def node(self):
        self._verify_in_node_operation()
        return self._node

    @property
    def source(self):
        self._verify_in_relationship_operation()
        return self._source

    @property
    def target(self):
        self._verify_in_relationship_operation()
        return self._target

    @property
    def execution_id(self):
        return self._ctx.task.execution.id

    @property
    def workflow_id(self):
        return self._ctx.task.execution.workflow_name

    @property
    def rest_token(self):
        return None

    @property
    def task_id(self):
        return self._ctx.task.id

    @property
    def task_name(self):
        return self._ctx.task.function

    @property
    def task_target(self):
        return None

    @property
    def task_queue(self):
        return None

    @property
    def logger(self):
        

        def getChild( self, name ):
            loggertype = type(self)

            childlogger =  self._logger.getChild(name)
            finallogger = loggertype(childlogger, self._task_id)
            return finallogger
        
    
        loggertype = type(self._ctx.logger)
       
        childloggertype = type(self._ctx.logger.getChild("test"))
        if loggertype != childloggertype:
            loggertype.getChild = getChild
      
        return self._ctx.logger

    def send_event(self, event):
        self.logger.info(event)

    @property
    def provider_context(self):
        return {}

    def get_resource(self, resource_path):
        return self._ctx.get_resource(resource_path)

    def get_resource_and_render(self, resource_path, template_variables=None):
        return self._ctx.get_resource_and_render(resource_path, variables=template_variables)

    def download_resource(self, resource_path, target_path=None):
        target_path = self._get_target_path(target_path, resource_path)
        self._ctx.download_resource(
            destination=target_path,
            path=resource_path
        )
        return target_path

    def download_resource_and_render(self,
                                     resource_path,
                                     target_path=None,
                                     template_variables=None):
        target_path = self._get_target_path(target_path, resource_path)
        self._ctx.download_resource_and_render(
            destination=target_path,
            path=resource_path,
            variables=template_variables
        )
        return target_path

    @staticmethod
    def _get_target_path(target_path, resource_path):
        if target_path:
            return target_path
        fd, target_path = tempfile.mkstemp(suffix=os.path.basename(resource_path))
        os.close(fd)
        return target_path

    def _verify_in_node_operation(self):
        if self.type != NODE_INSTANCE:
            self._ctx.task.abort(
                'ctx.node/ctx.instance can only be used in a {0} context but '
                'used in a {1} context.'.format(NODE_INSTANCE, self.type)
            )

    def _verify_in_relationship_operation(self):
        if self.type != RELATIONSHIP_INSTANCE:
            self._ctx.task.abort(
                'ctx.source/ctx.target can only be used in a {0} context but '
                'used in a {1} context.'.format(RELATIONSHIP_INSTANCE,
                                                self.type)
            )


class BlueprintAdapter(object):

    def __init__(self, ctx):
        self._ctx = ctx

    @property
    def id(self):
        return self._ctx.service_template.id


class DeploymentAdapter(object):

    def __init__(self, ctx):
        self._ctx = ctx

    @property
    def id(self):
        return self._ctx.service.id


class NodeAdapter(object):

    def __init__(self, ctx, node_template, node):
        self._ctx = ctx
        self._node_template = node_template
        self._node = node

    @property
    def id(self):
        return self._node_template.id

    @property
    def name(self):
        return self._node_template.name

    @property
    def properties(self):
        # Cloudify Azure plugin will request the resource_config and merge it with new configurations.
        # This creates an problem when the resource_config is None. Fix this by replacing an empty
        # resource_config with an empth dict.
        if 'resource_config' in self._node.properties and self._node.properties.get('resource_config') == None:
            self._node.properties['resource_config']={}
        return self._node.properties

    @property
    def type(self):
        return self._node_template.type.name

    @property
    def type_hierarchy(self):
        # We needed to modify the type hierarchy to be a list of strings that include the word
        # 'cloudify' in each one of them instead of 'aria', since in the Cloudify AWS plugin, that
        # we currently wish to support, if we want to attach an ElasticIP to a node, this node's
        # type_hierarchy property must be a list of strings only, and it must contain either the
        # string 'cloudify.aws.nodes.Instance', or the string 'cloudify.aws.nodes.Interface'.
        # In any other case, we won't be able to attach an ElasticIP to a node using the Cloudify
        # AWS plugin.
        type_hierarchy_names = [type_.name for type_ in self._node_template.type.hierarchy
                                if type_.name is not None]
        return [type_name.replace('aria', 'cloudify') for type_name in type_hierarchy_names]


class NodeInstanceAdapter(object):

    def __init__(self, ctx, node, modifiable):
        self._ctx = ctx
        self._node = node
        self._modifiable = modifiable

    @property
    def id(self):
        return self._node.id

    @property
    def runtime_properties(self):
        return self._node.attributes

    @runtime_properties.setter
    def runtime_properties(self, value):
        self._node.attributes = value

    def update(self, on_conflict=None):
        self._ctx.model.node.update(self._node)

    def refresh(self, force=False):
        self._ctx.model.node.refresh(self._node)

    @property
    def host_ip(self):
        return self._node.host_address

    @property
    def relationships(self):
        return [RelationshipAdapter(self._ctx, relationship=relationship) for
                relationship in self._node.outbound_relationships]

    #def __getattr__(self, item):
    #    print "requsting "
    #    print self._node.attributes
    #    print dir(self._ctx)
    #    return getattr(self._ctx.instance, item)


class RelationshipAdapter(object):

    def __init__(self, ctx, relationship):
        self._ctx = ctx
        self._relationship = relationship
        node = relationship.target_node
        node_template = node.node_template
        self.target = RelationshipTargetAdapter(ctx, node_template, node, False)

    @property
    def type(self):
        return self._relationship.type.name

    #@property
    #def type_hierarchy(self):
    #    return self._relationship.type.hierarchy



    @property
    def type_hierarchy(self):
        # We needed to modify the type hierarchy to be a list of strings that include the word
        # 'cloudify' in each one of them instead of 'aria', since in the Cloudify AWS plugin, that
        # we currently wish to support, if we want to attach an ElasticIP to a node, this node's
        # type_hierarchy property must be a list of strings only, and it must contain either the
        # string 'cloudify.aws.nodes.Instance', or the string 'cloudify.aws.nodes.Interface'.
        # In any other case, we won't be able to attach an ElasticIP to a node using the Cloudify
        # AWS plugin.
        type_hierarchy_names = [type_.name for type_ in self._relationship.type.hierarchy
                                if type_.name is not None]
        return [type_name.replace('aria', 'cloudify') for type_name in type_hierarchy_names]











class RelationshipTargetAdapter(object):

    def __init__(self, ctx, node_template, node, modifiable):
        self._ctx = ctx
        self.node = NodeAdapter(ctx, node_template=node_template, node=node)
        self.instance = NodeInstanceAdapter(ctx, node=node, modifiable=modifiable)


class OperationAdapter(object):

    def __init__(self, ctx):
        self._ctx = ctx

    @property
    def name(self):
        # We needed to modify the operation's 'name' property in order to support the Cloudify AWS
        # plugin. It can't use ARIA's operation naming convention, as any operation we want to run
        # using the Cloudify AWS plugin must have its name in the format:
        # '<something>.<operation_name>'.
        aria_name = self._ctx.task.name
        return aria_name.split('@')[0].replace(':', '.')

    @property
    def retry_number(self):
        return self._ctx.task.attempts_count - 1

    @property
    def max_retries(self):
        task = self._ctx.task
        if task.max_attempts == task.INFINITE_RETRIES:
            return task.INFINITE_RETRIES
        else:
            return task.max_attempts - 1 if task.max_attempts > 0 else 0

    def retry(self, message=None, retry_after=None):
        self._ctx.task.retry(message, retry_after)


class BootstrapAdapter(object):

    def __init__(self, ctx):
        self._ctx = ctx
        self.cloudify_agent = _Stub()
        self.resources_prefix = ''

    def broker_config(self, *args, **kwargs):
        return {}


class CloudifyAgentAdapter(object):

    def init_script(self, *args, **kwargs):
        return None


class PluginAdapter(object):

    def __init__(self, ctx):
        self._ctx = ctx
        self._plugin = None

    @property
    def name(self):
        return self._ctx.task.plugin.name

    @property
    def package_name(self):
        return self._plugin_attr('package_name')

    @property
    def package_version(self):
        return self._plugin_attr('package_version')

    @property
    def prefix(self):
        # TODO
        return self._plugin_attr('prefix')

    @property
    def workdir(self):
        return self._ctx.plugin_workdir

    def _plugin_attr(self, attr):
        if not self._plugin:
            self._plugin = self._ctx.task.plugin
        if not self._plugin:
            return None
        return getattr(self._plugin, attr, None)



class _Stub(object):
    def __getattr__(self, _):
        return None