vFW and vDNS support added to azure-plugin
[multicloud/azure.git] / azure / aria / aria-extension-cloudify / src / aria / extensions / aria_extension_tosca / simple_v1_0 / modeling / functions.py
1 # Licensed to the Apache Software Foundation (ASF) under one or more
2 # contributor license agreements.  See the NOTICE file distributed with
3 # this work for additional information regarding copyright ownership.
4 # The ASF licenses this file to You under the Apache License, Version 2.0
5 # (the "License"); you may not use this file except in compliance with
6 # the License.  You may obtain a copy of the License at
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 from StringIO import StringIO # Note: cStringIO does not support Unicode
17 import re
18
19 from aria.utils.collections import FrozenList
20 from aria.utils.formatting import (as_raw, safe_repr)
21 from aria.utils.type import full_type_name
22 from aria.parser import implements_specification
23 from aria.parser.exceptions import InvalidValueError
24 from aria.parser.validation import Issue
25 from aria.modeling.exceptions import CannotEvaluateFunctionException
26 from aria.modeling.models import (Node, NodeTemplate, Relationship, RelationshipTemplate)
27 from aria.modeling.functions import (Function, Evaluation)
28
29
30 #
31 # Intrinsic
32 #
33
34 @implements_specification('4.3.1', 'tosca-simple-1.0')
35 class Concat(Function):
36     """
37     The ``concat`` function is used to concatenate two or more string values within a TOSCA
38     service template.
39     """
40
41     def __init__(self, context, presentation, argument):
42         self.locator = presentation._locator
43
44         if not isinstance(argument, list):
45             raise InvalidValueError(
46                 'function "concat" argument must be a list of string expressions: {0}'
47                 .format(safe_repr(argument)),
48                 locator=self.locator)
49
50         string_expressions = []
51         for index, an_argument in enumerate(argument):
52             string_expressions.append(parse_string_expression(context, presentation, 'concat',
53                                                               index, None, an_argument))
54         self.string_expressions = FrozenList(string_expressions)
55
56     @property
57     def as_raw(self):
58         string_expressions = []
59         for string_expression in self.string_expressions:
60             if hasattr(string_expression, 'as_raw'):
61                 string_expression = as_raw(string_expression)
62             string_expressions.append(string_expression)
63         return {'concat': string_expressions}
64
65     def __evaluate__(self, container_holder):
66         final = True
67         value = StringIO()
68         for e in self.string_expressions:
69             e, final = evaluate(e, final, container_holder)
70             if e is not None:
71                 value.write(unicode(e))
72         value = value.getvalue() or u''
73         return Evaluation(value, final)
74
75
76 @implements_specification('4.3.2', 'tosca-simple-1.0')
77 class Token(Function):
78     """
79     The ``token`` function is used within a TOSCA service template on a string to parse out
80     (tokenize) substrings separated by one or more token characters within a larger string.
81     """
82
83     def __init__(self, context, presentation, argument):
84         self.locator = presentation._locator
85
86         if (not isinstance(argument, list)) or (len(argument) != 3):
87             raise InvalidValueError('function "token" argument must be a list of 3 parameters: {0}'
88                                     .format(safe_repr(argument)),
89                                     locator=self.locator)
90
91         self.string_with_tokens = parse_string_expression(context, presentation, 'token', 0,
92                                                           'the string to tokenize', argument[0])
93         self.string_of_token_chars = parse_string_expression(context, presentation, 'token', 1,
94                                                              'the token separator characters',
95                                                              argument[1])
96         self.substring_index = parse_int(context, presentation, 'token', 2,
97                                          'the 0-based index of the token to return', argument[2])
98
99     @property
100     def as_raw(self):
101         string_with_tokens = self.string_with_tokens
102         if hasattr(string_with_tokens, 'as_raw'):
103             string_with_tokens = as_raw(string_with_tokens)
104         string_of_token_chars = self.string_of_token_chars
105         if hasattr(string_of_token_chars, 'as_raw'):
106             string_of_token_chars = as_raw(string_of_token_chars)
107         return {'token': [string_with_tokens, string_of_token_chars, self.substring_index]}
108
109     def __evaluate__(self, container_holder):
110         final = True
111         string_with_tokens, final = evaluate(self.string_with_tokens, final, container_holder)
112         string_of_token_chars, final = evaluate(self.string_of_token_chars, final, container_holder)
113
114         if string_of_token_chars:
115             regex = '[' + ''.join(re.escape(c) for c in string_of_token_chars) + ']'
116             split = re.split(regex, string_with_tokens)
117             if self.substring_index < len(split):
118                 return Evaluation(split[self.substring_index], final)
119
120         raise CannotEvaluateFunctionException()
121
122
123 #
124 # Property
125 #
126
127 @implements_specification('4.4.1', 'tosca-simple-1.0')
128 class GetInput(Function):
129     """
130     The ``get_input`` function is used to retrieve the values of properties declared within the
131     inputs section of a TOSCA Service Template.
132     """
133
134     def __init__(self, context, presentation, argument):
135         self.locator = presentation._locator
136
137         self.input_property_name = parse_string_expression(context, presentation, 'get_input',
138                                                            None, 'the input property name',
139                                                            argument)
140
141         if isinstance(self.input_property_name, basestring):
142             the_input = context.presentation.get_from_dict('service_template', 'topology_template',
143                                                            'inputs', self.input_property_name)
144             if the_input is None:
145                 raise InvalidValueError(
146                     'function "get_input" argument is not a valid input name: {0}'
147                     .format(safe_repr(argument)),
148                     locator=self.locator)
149
150     @property
151     def as_raw(self):
152         return {'get_input': as_raw(self.input_property_name)}
153
154     def __evaluate__(self, container_holder):
155         service = container_holder.service
156         if service is None:
157             raise CannotEvaluateFunctionException()
158
159         value = service.inputs.get(self.input_property_name)
160         if value is not None:
161             value = value.value
162             return Evaluation(value, False) # We never return final evaluations!
163
164         raise InvalidValueError(
165             'function "get_input" argument is not a valid input name: {0}'
166             .format(safe_repr(self.input_property_name)),
167             locator=self.locator)
168
169
170 @implements_specification('4.4.2', 'tosca-simple-1.0')
171 class GetProperty(Function):
172     """
173     The ``get_property`` function is used to retrieve property values between modelable entities
174     defined in the same service template.
175     """
176
177     def __init__(self, context, presentation, argument):
178         self.locator = presentation._locator
179
180         if (not isinstance(argument, list)) or (len(argument) < 2):
181             raise InvalidValueError(
182                 'function "get_property" argument must be a list of at least 2 string expressions: '
183                 '{0}'.format(safe_repr(argument)),
184                 locator=self.locator)
185
186         self.modelable_entity_name = parse_modelable_entity_name(context, presentation,
187                                                                  'get_property', 0, argument[0])
188         # The first of these will be tried as a req-or-cap name:
189         self.nested_property_name_or_index = argument[1:]
190
191     @property
192     def as_raw(self):
193         return {'get_property': [self.modelable_entity_name] + self.nested_property_name_or_index}
194
195     def __evaluate__(self, container_holder):
196         modelable_entities = get_modelable_entities(container_holder, 'get_property', self.locator,
197                                                     self.modelable_entity_name)
198         req_or_cap_name = self.nested_property_name_or_index[0]
199
200         for modelable_entity in modelable_entities:
201             properties = None
202
203             # First argument refers to a requirement template?
204             if hasattr(modelable_entity, 'requirement_templates') \
205                 and modelable_entity.requirement_templates \
206                 and (req_or_cap_name in [v.name for v in modelable_entity.requirement_templates]):
207                 for requirement in modelable_entity.requirement_templates:
208                     if requirement.name == req_or_cap_name:
209                         # TODO
210                         raise CannotEvaluateFunctionException()
211             # First argument refers to a capability?
212             elif hasattr(modelable_entity, 'capabilities') \
213                 and modelable_entity.capabilities \
214                 and (req_or_cap_name in modelable_entity.capabilities):
215                 properties = modelable_entity.capabilities[req_or_cap_name].properties
216                 nested_property_name_or_index = self.nested_property_name_or_index[1:]
217             # First argument refers to a capability template?
218             elif hasattr(modelable_entity, 'capability_templates') \
219                 and modelable_entity.capability_templates \
220                 and (req_or_cap_name in modelable_entity.capability_templates):
221                 properties = modelable_entity.capability_templates[req_or_cap_name].properties
222                 nested_property_name_or_index = self.nested_property_name_or_index[1:]
223             else:
224                 properties = modelable_entity.properties
225                 nested_property_name_or_index = self.nested_property_name_or_index
226
227             evaluation = get_modelable_entity_parameter(modelable_entity, properties,
228                                                         nested_property_name_or_index)
229             if evaluation is not None:
230                 return evaluation
231
232         raise InvalidValueError(
233             'function "get_property" could not find "{0}" in modelable entity "{1}"'
234             .format('.'.join(self.nested_property_name_or_index), self.modelable_entity_name),
235             locator=self.locator)
236
237
238 #
239 # Attribute
240 #
241
242 @implements_specification('4.5.1', 'tosca-simple-1.0')
243 class GetAttribute(Function):
244     """
245     The ``get_attribute`` function is used to retrieve the values of named attributes declared
246     by the referenced node or relationship template name.
247     """
248
249     def __init__(self, context, presentation, argument):
250         self.locator = presentation._locator
251
252         if (not isinstance(argument, list)) or (len(argument) < 2):
253             raise InvalidValueError(
254                 'function "get_attribute" argument must be a list of at least 2 string expressions:'
255                 ' {0}'.format(safe_repr(argument)),
256                 locator=self.locator)
257
258         self.modelable_entity_name = parse_modelable_entity_name(context, presentation,
259                                                                  'get_attribute', 0, argument[0])
260         # The first of these will be tried as a req-or-cap name:
261         self.nested_attribute_name_or_index = argument[1:]
262
263     @property
264     def as_raw(self):
265         return {'get_attribute': [self.modelable_entity_name] + self.nested_attribute_name_or_index}
266
267     def __evaluate__(self, container_holder):
268         modelable_entities = get_modelable_entities(container_holder, 'get_attribute', self.locator,
269                                                     self.modelable_entity_name)
270         for modelable_entity in modelable_entities:
271             attributes = modelable_entity.attributes
272             nested_attribute_name_or_index = self.nested_attribute_name_or_index
273             evaluation = get_modelable_entity_parameter(modelable_entity, attributes,
274                                                         nested_attribute_name_or_index)
275             if evaluation is not None:
276                 evaluation.final = False # We never return final evaluations!
277                 return evaluation
278
279         raise InvalidValueError(
280             'function "get_attribute" could not find "{0}" in modelable entity "{1}"'
281             .format('.'.join(self.nested_attribute_name_or_index), self.modelable_entity_name),
282             locator=self.locator)
283
284
285 #
286 # Operation
287 #
288
289 @implements_specification('4.6.1', 'tosca-simple-1.0') # pylint: disable=abstract-method
290 class GetOperationOutput(Function):
291     """
292     The ``get_operation_output`` function is used to retrieve the values of variables exposed /
293     exported from an interface operation.
294     """
295
296     def __init__(self, context, presentation, argument):
297         self.locator = presentation._locator
298
299         if (not isinstance(argument, list)) or (len(argument) != 4):
300             raise InvalidValueError(
301                 'function "get_operation_output" argument must be a list of 4 parameters: {0}'
302                 .format(safe_repr(argument)),
303                 locator=self.locator)
304
305         self.modelable_entity_name = parse_string_expression(context, presentation,
306                                                              'get_operation_output', 0,
307                                                              'modelable entity name', argument[0])
308         self.interface_name = parse_string_expression(context, presentation, 'get_operation_output',
309                                                       1, 'the interface name', argument[1])
310         self.operation_name = parse_string_expression(context, presentation, 'get_operation_output',
311                                                       2, 'the operation name', argument[2])
312         self.output_variable_name = parse_string_expression(context, presentation,
313                                                             'get_operation_output', 3,
314                                                             'the output name', argument[3])
315
316     @property
317     def as_raw(self):
318         interface_name = self.interface_name
319         if hasattr(interface_name, 'as_raw'):
320             interface_name = as_raw(interface_name)
321         operation_name = self.operation_name
322         if hasattr(operation_name, 'as_raw'):
323             operation_name = as_raw(operation_name)
324         output_variable_name = self.output_variable_name
325         if hasattr(output_variable_name, 'as_raw'):
326             output_variable_name = as_raw(output_variable_name)
327         return {'get_operation_output': [self.modelable_entity_name, interface_name, operation_name,
328                                          output_variable_name]}
329
330
331 #
332 # Navigation
333 #
334
335 @implements_specification('4.7.1', 'tosca-simple-1.0')
336 class GetNodesOfType(Function):
337     """
338     The ``get_nodes_of_type`` function can be used to retrieve a list of all known instances of
339     nodes of the declared Node Type.
340     """
341
342     def __init__(self, context, presentation, argument):
343         self.locator = presentation._locator
344
345         self.node_type_name = parse_string_expression(context, presentation, 'get_nodes_of_type',
346                                                       None, 'the node type name', argument)
347
348         if isinstance(self.node_type_name, basestring):
349             node_types = context.presentation.get('service_template', 'node_types')
350             if (node_types is None) or (self.node_type_name not in node_types):
351                 raise InvalidValueError(
352                     'function "get_nodes_of_type" argument is not a valid node type name: {0}'
353                     .format(safe_repr(argument)),
354                     locator=self.locator)
355
356     @property
357     def as_raw(self):
358         node_type_name = self.node_type_name
359         if hasattr(node_type_name, 'as_raw'):
360             node_type_name = as_raw(node_type_name)
361         return {'get_nodes_of_type': node_type_name}
362
363     def __evaluate__(self, container):
364         pass
365
366
367 #
368 # Artifact
369 #
370
371 @implements_specification('4.8.1', 'tosca-simple-1.0') # pylint: disable=abstract-method
372 class GetArtifact(Function):
373     """
374     The ``get_artifact`` function is used to retrieve artifact location between modelable
375     entities defined in the same service template.
376     """
377
378     def __init__(self, context, presentation, argument):
379         self.locator = presentation._locator
380
381         if (not isinstance(argument, list)) or (len(argument) < 2) or (len(argument) > 4):
382             raise InvalidValueError(
383                 'function "get_artifact" argument must be a list of 2 to 4 parameters: {0}'
384                 .format(safe_repr(argument)),
385                 locator=self.locator)
386
387         self.modelable_entity_name = parse_string_expression(context, presentation, 'get_artifact',
388                                                              0, 'modelable entity name',
389                                                              argument[0])
390         self.artifact_name = parse_string_expression(context, presentation, 'get_artifact', 1,
391                                                      'the artifact name', argument[1])
392         self.location = parse_string_expression(context, presentation, 'get_artifact', 2,
393                                                 'the location or "LOCAL_FILE"', argument[2])
394         self.remove = parse_bool(context, presentation, 'get_artifact', 3, 'the removal flag',
395                                  argument[3])
396
397     @property
398     def as_raw(self):
399         artifact_name = self.artifact_name
400         if hasattr(artifact_name, 'as_raw'):
401             artifact_name = as_raw(artifact_name)
402         location = self.location
403         if hasattr(location, 'as_raw'):
404             location = as_raw(location)
405         return {'get_artifacts': [self.modelable_entity_name, artifact_name, location, self.remove]}
406
407
408 #
409 # Utils
410 #
411
412 def get_function(context, presentation, value):
413     functions = context.presentation.presenter.functions
414     if isinstance(value, dict) and (len(value) == 1):
415         key = value.keys()[0]
416         if key in functions:
417             try:
418                 return True, functions[key](context, presentation, value[key])
419             except InvalidValueError as e:
420                 context.validation.report(issue=e.issue)
421                 return True, None
422     return False, None
423
424
425 def parse_string_expression(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument
426     is_function, func = get_function(context, presentation, value)
427     if is_function:
428         return func
429     else:
430         value = str(value)
431     return value
432
433
434 def parse_int(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument
435     if not isinstance(value, int):
436         try:
437             value = int(value)
438         except ValueError:
439             raise invalid_value(name, index, 'an integer', explanation, value,
440                                 presentation._locator)
441     return value
442
443
444 def parse_bool(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument
445     if not isinstance(value, bool):
446         raise invalid_value(name, index, 'a boolean', explanation, value, presentation._locator)
447     return value
448
449
450 def parse_modelable_entity_name(context, presentation, name, index, value):
451     value = parse_string_expression(context, presentation, name, index, 'the modelable entity name',
452                                     value)
453     if value == 'SELF':
454         the_self, _ = parse_self(presentation)
455         if the_self is None:
456             raise invalid_modelable_entity_name(name, index, value, presentation._locator,
457                                                 'a node template or a relationship template')
458     elif value == 'HOST':
459         _, self_variant = parse_self(presentation)
460         if self_variant != 'node_template':
461             raise invalid_modelable_entity_name(name, index, value, presentation._locator,
462                                                 'a node template')
463     elif (value == 'SOURCE') or (value == 'TARGET'):
464         _, self_variant = parse_self(presentation)
465         if self_variant != 'relationship_template':
466             raise invalid_modelable_entity_name(name, index, value, presentation._locator,
467                                                 'a relationship template')
468     elif isinstance(value, basestring):
469         node_templates = \
470             context.presentation.get('service_template', 'topology_template', 'node_templates') \
471             or {}
472         relationship_templates = \
473             context.presentation.get('service_template', 'topology_template',
474                                      'relationship_templates') \
475             or {}
476         if (value not in node_templates) and (value not in relationship_templates):
477             raise InvalidValueError(
478                 'function "{0}" parameter {1:d} is not a valid modelable entity name: {2}'
479                 .format(name, index + 1, safe_repr(value)),
480                 locator=presentation._locator, level=Issue.BETWEEN_TYPES)
481     return value
482
483
484 def parse_self(presentation):
485     from ..types import (NodeType, RelationshipType)
486     from ..templates import (
487         NodeTemplate as NodeTemplatePresentation,
488         RelationshipTemplate as RelationshipTemplatePresentation
489     )
490
491     if presentation is None:
492         return None, None
493     elif isinstance(presentation, NodeTemplatePresentation) or isinstance(presentation, NodeType):
494         return presentation, 'node_template'
495     elif isinstance(presentation, RelationshipTemplatePresentation) \
496         or isinstance(presentation, RelationshipType):
497         return presentation, 'relationship_template'
498     else:
499         return parse_self(presentation._container)
500
501
502 def evaluate(value, final, container_holder):
503     """
504     Calls ``__evaluate__`` and passes on ``final`` state.
505     """
506
507     if hasattr(value, '__evaluate__'):
508         value = value.__evaluate__(container_holder)
509         if not value.final:
510             final = False
511         return value.value, final
512     else:
513         return value, final
514
515
516 @implements_specification('4.1', 'tosca-simple-1.0')
517 def get_modelable_entities(container_holder, name, locator, modelable_entity_name):
518     """
519     The following keywords MAY be used in some TOSCA function in place of a TOSCA Node or
520     Relationship Template name.
521     """
522
523     if modelable_entity_name == 'SELF':
524         return get_self(container_holder, name, locator)
525     elif modelable_entity_name == 'HOST':
526         return get_hosts(container_holder, name, locator)
527     elif modelable_entity_name == 'SOURCE':
528         return get_source(container_holder, name, locator)
529     elif modelable_entity_name == 'TARGET':
530         return get_target(container_holder, name, locator)
531     elif isinstance(modelable_entity_name, basestring):
532         modelable_entities = []
533
534         service = container_holder.service
535         if service is not None:
536             for node in service.nodes.itervalues():
537                 if node.node_template.name == modelable_entity_name:
538                     modelable_entities.append(node)
539         else:
540             service_template = container_holder.service_template
541             if service_template is not None:
542                 for node_template in service_template.node_templates.itervalues():
543                     if node_template.name == modelable_entity_name:
544                         modelable_entities.append(node_template)
545
546         if not modelable_entities:
547             raise CannotEvaluateFunctionException()
548
549         return modelable_entities
550
551     raise InvalidValueError('function "{0}" could not find modelable entity "{1}"'
552                             .format(name, modelable_entity_name),
553                             locator=locator)
554
555
556 def get_self(container_holder, name, locator):
557     """
558     A TOSCA orchestrator will interpret this keyword as the Node or Relationship Template instance
559     that contains the function at the time the function is evaluated.
560     """
561
562     container = container_holder.container
563     if (not isinstance(container, Node)) and \
564         (not isinstance(container, NodeTemplate)) and \
565         (not isinstance(container, Relationship)) and \
566         (not isinstance(container, RelationshipTemplate)):
567         raise InvalidValueError('function "{0}" refers to "SELF" but it is not contained in '
568                                 'a node or a relationship: {1}'.format(name,
569                                                                        full_type_name(container)),
570                                 locator=locator)
571
572     return [container]
573
574
575 def get_hosts(container_holder, name, locator):
576     """
577     A TOSCA orchestrator will interpret this keyword to refer to the all nodes that "host" the node
578     using this reference (i.e., as identified by its HostedOn relationship).
579
580     Specifically, TOSCA orchestrators that encounter this keyword when evaluating the get_attribute
581     or ``get_property`` functions SHALL search each node along the "HostedOn" relationship chain
582     starting at the immediate node that hosts the node where the function was evaluated (and then
583     that node's host node, and so forth) until a match is found or the "HostedOn" relationship chain
584     ends.
585     """
586
587     container = container_holder.container
588     if (not isinstance(container, Node)) and (not isinstance(container, NodeTemplate)):
589         raise InvalidValueError('function "{0}" refers to "HOST" but it is not contained in '
590                                 'a node: {1}'.format(name, full_type_name(container)),
591                                 locator=locator)
592
593     if not isinstance(container, Node):
594         # NodeTemplate does not have "host"; we'll wait until instantiation
595         raise CannotEvaluateFunctionException()
596
597     host = container.host
598     if host is None:
599         # We might have a host later
600         raise CannotEvaluateFunctionException()
601
602     return [host]
603
604
605 def get_source(container_holder, name, locator):
606     """
607     A TOSCA orchestrator will interpret this keyword as the Node Template instance that is at the
608     source end of the relationship that contains the referencing function.
609     """
610
611     container = container_holder.container
612     if (not isinstance(container, Relationship)) and \
613         (not isinstance(container, RelationshipTemplate)):
614         raise InvalidValueError('function "{0}" refers to "SOURCE" but it is not contained in '
615                                 'a relationship: {1}'.format(name, full_type_name(container)),
616                                 locator=locator)
617
618     if not isinstance(container, RelationshipTemplate):
619         # RelationshipTemplate does not have "source_node"; we'll wait until instantiation
620         raise CannotEvaluateFunctionException()
621
622     return [container.source_node]
623
624
625 def get_target(container_holder, name, locator):
626     """
627     A TOSCA orchestrator will interpret this keyword as the Node Template instance that is at the
628     target end of the relationship that contains the referencing function.
629     """
630
631     container = container_holder.container
632     if (not isinstance(container, Relationship)) and \
633         (not isinstance(container, RelationshipTemplate)):
634         raise InvalidValueError('function "{0}" refers to "TARGET" but it is not contained in '
635                                 'a relationship: {1}'.format(name, full_type_name(container)),
636                                 locator=locator)
637
638     if not isinstance(container, RelationshipTemplate):
639         # RelationshipTemplate does not have "target_node"; we'll wait until instantiation
640         raise CannotEvaluateFunctionException()
641
642     return [container.target_node]
643
644
645 def get_modelable_entity_parameter(modelable_entity, parameters, nested_parameter_name_or_index):
646     if not parameters:
647         return Evaluation(None, True)
648
649     found = True
650     final = True
651     value = parameters
652
653     for name_or_index in nested_parameter_name_or_index:
654         if (isinstance(value, dict) and (name_or_index in value)) \
655             or ((isinstance(value, list) and (name_or_index < len(value)))):
656             value = value[name_or_index] # Parameter
657             # We are not using Parameter.value, but rather Parameter._value, because we want to make
658             # sure to get "final" (it is swallowed by Parameter.value)
659             value, final = evaluate(value._value, final, value)
660         else:
661             found = False
662             break
663
664     return Evaluation(value, final) if found else None
665
666
667 def invalid_modelable_entity_name(name, index, value, locator, contexts):
668     return InvalidValueError('function "{0}" parameter {1:d} can be "{2}" only in {3}'
669                              .format(name, index + 1, value, contexts),
670                              locator=locator, level=Issue.FIELD)
671
672
673 def invalid_value(name, index, the_type, explanation, value, locator):
674     return InvalidValueError(
675         'function "{0}" {1} is not {2}{3}: {4}'
676         .format(name,
677                 'parameter {0:d}'.format(index + 1) if index is not None else 'argument',
678                 the_type,
679                 ', {0}'.format(explanation) if explanation is not None else '',
680                 safe_repr(value)),
681         locator=locator, level=Issue.FIELD)