http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/argparse.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/argparse.py b/apache-ariatosca-0.1.1/aria/utils/argparse.py deleted file mode 100644 index a05a841..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/argparse.py +++ /dev/null @@ -1,118 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Enhancements to Python's ``argparse`` module. -""" - -from __future__ import absolute_import # so we can import standard 'argparse' - -from argparse import ArgumentParser as BaseArgumentParser - - -class ArgumentParser(BaseArgumentParser): - """ - Enhanced argument parser. - - Applied patch to fix `this issue <https://bugs.python.org/issue22433>`__. - """ - - def add_flag_argument(self, name, help_true=None, help_false=None, default=False): - """ - Adds a flag argument as two arguments: ``--my-flag`` and ``--no-my-flag``. - """ - - dest = name.replace('-', '_') - - if default: - if help_true is not None: - help_true += ' (default)' - else: - help_true = '(default)' - else: - if help_false is not None: - help_false += ' (default)' - else: - help_false = '(default)' - - group = self.add_mutually_exclusive_group() - group.add_argument('--%s' % name, action='store_true', help=help_true) - group.add_argument('--no-%s' % name, dest=dest, action='store_false', help=help_false) - - self.set_defaults(**{dest: default}) - - def _parse_optional(self, arg_string): - - if self._is_positional(arg_string): - return None - - # if the option string is present in the parser, return the action - if arg_string in self._option_string_actions: - action = self._option_string_actions[arg_string] - return action, arg_string, None - - # if the option string before the "=" is present, return the action - if '=' in arg_string: - option_string, explicit_arg = arg_string.split('=', 1) - if option_string in self._option_string_actions: - action = self._option_string_actions[option_string] - return action, option_string, explicit_arg - - # search through all possible prefixes of the option string - # and all actions in the parser for possible interpretations - option_tuples = self._get_option_tuples(arg_string) - - # if multiple actions match, the option string was ambiguous - if len(option_tuples) > 1: - options = ', '.join( - [option_string for action, option_string, explicit_arg in option_tuples]) - tup = arg_string, options - self.error('ambiguous option: %s could match %s' % tup) - - # if exactly one action matched, this segmentation is good, - # so return the parsed action - elif len(option_tuples) == 1: - option_tuple = option_tuples - return option_tuple - - # if it was not found as an option, but it looks like a negative - # number, it was meant to be positional - # unless there are negative-number-like options - if self._negative_number_matcher.match(arg_string): - if not self._has_negative_number_optionals: - return None - - # it was meant to be an optional but there is no such option - # in this parser (though it might be a valid option in a subparser) - return None, arg_string, None - - def _is_positional(self, arg_string): - # if it's an empty string, it was meant to be a positional - if not arg_string: - return True - - # if it doesn't start with a prefix, it was meant to be positional - if not arg_string[0] in self.prefix_chars: - return True - - # if it's just a single character, it was meant to be positional - if len(arg_string) == 1: - return True - - # if it contains a space, it was meant to be a positional - if ' ' in arg_string and arg_string[0] not in self.prefix_chars: - return True - - return False
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/caching.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/caching.py b/apache-ariatosca-0.1.1/aria/utils/caching.py deleted file mode 100644 index 5f8cd88..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/caching.py +++ /dev/null @@ -1,137 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Caching utilities. -""" - -from __future__ import absolute_import # so we can import standard 'collections' and 'threading' - -from threading import Lock -from functools import partial - -from .collections import OrderedDict - - -class cachedmethod(object): # pylint: disable=invalid-name - """ - Decorator for caching method return values. - - The implementation is thread-safe. - - Supports ``cache_info`` to be compatible with Python 3's ``functools.lru_cache``. Note that the - statistics are combined for all instances of the class. - - Won't use the cache if not called when bound to an object, allowing you to override the cache. - - Adapted from `this solution - <http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/>`__. - """ - - ENABLED = True - - def __init__(self, func): - self.__doc__ = func.__doc__ - self.func = func - self.hits = 0 - self.misses = 0 - self.lock = Lock() - - def cache_info(self): - with self.lock: - return (self.hits, self.misses, None, self.misses) - - def reset_cache_info(self): - with self.lock: - self.hits = 0 - self.misses = 0 - - def __get__(self, instance, owner): - if instance is None: - # Don't use cache if not bound to an object - # Note: This is also a way for callers to override the cache - return self.func - return partial(self, instance) - - def __call__(self, *args, **kwargs): - if not self.ENABLED: - return self.func(*args, **kwargs) - - instance = args[0] - if not hasattr(instance, '_method_cache'): - instance._method_cache = {} - method_cache = instance._method_cache - - key = (self.func, args[1:], frozenset(kwargs.items())) - - try: - with self.lock: - return_value = method_cache[key] - self.hits += 1 - except KeyError: - return_value = self.func(*args, **kwargs) - with self.lock: - method_cache[key] = return_value - self.misses += 1 - # Another thread may override our cache entry here, so we need to read - # it again to make sure all threads use the same return value - return_value = method_cache.get(key, return_value) - - return return_value - - -class HasCachedMethods(object): - """ - Provides convenience methods for working with :class:`cachedmethod`. - """ - - def __init__(self, method_cache=None): - self._method_cache = method_cache or {} - - @property - def _method_cache_info(self): - """ - The cache infos of all cached methods. - - :rtype: dict of str, 4-tuple - """ - - cached_info = OrderedDict() - for k, v in self.__class__.__dict__.iteritems(): - if isinstance(v, property): - # The property getter might be cached - v = v.fget - if hasattr(v, 'cache_info'): - cached_info[k] = v.cache_info() - return cached_info - - def _reset_method_cache(self): - """ - Resets the caches of all cached methods. - """ - - if hasattr(self, '_method_cache'): - self._method_cache = {} - - # Note: Another thread may already be storing entries in the cache here. - # But it's not a big deal! It only means that our cache_info isn't - # guaranteed to be accurate. - - for entry in self.__class__.__dict__.itervalues(): - if isinstance(entry, property): - # The property getter might be cached - entry = entry.fget - if hasattr(entry, 'reset_cache_info'): - entry.reset_cache_info() http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/collections.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/collections.py b/apache-ariatosca-0.1.1/aria/utils/collections.py deleted file mode 100644 index ccc37a1..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/collections.py +++ /dev/null @@ -1,303 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Additional collection classes and collection utilities. -""" - -from __future__ import absolute_import # so we can import standard 'collections' - -from copy import deepcopy -try: - from collections import OrderedDict -except ImportError: - from ordereddict import OrderedDict - - -def cls_name(cls): - module = str(cls.__module__) - name = str(cls.__name__) - return name if module == '__builtin__' else '%s.%s' % (module, name) - - -class FrozenList(list): - """ - An immutable list. - - After initialization it will raise :class:`~exceptions.TypeError` exceptions if modification is - attempted. - - Note that objects stored in the list may not be immutable. - """ - def __init__(self, *args, **kwargs): - self.locked = False - super(FrozenList, self).__init__(*args, **kwargs) - self.locked = True - - def __setitem__(self, index, value): - if self.locked: - raise TypeError('frozen list') - return super(FrozenList, self).__setitem__(index, value) - - def __delitem__(self, index): - if self.locked: - raise TypeError('frozen list') - return super(FrozenList, self).__delitem__(index) - - def __iadd__(self, values): - if self.locked: - raise TypeError('frozen list') - return super(FrozenList, self).__iadd__(values) - - def __deepcopy__(self, memo): - res = [deepcopy(v, memo) for v in self] - return FrozenList(res) - - def append(self, value): - if self.locked: - raise TypeError('frozen list') - return super(FrozenList, self).append(value) - - def extend(self, values): - if self.locked: - raise TypeError('frozen list') - return super(FrozenList, self).append(values) - - def insert(self, index, value): - if self.locked: - raise TypeError('frozen list') - return super(FrozenList, self).insert(index, value) - -EMPTY_READ_ONLY_LIST = FrozenList() - - -class FrozenDict(OrderedDict): - """ - An immutable ordered dict. - - After initialization it will raise :class:`~exceptions.TypeError` exceptions if modification is - attempted. - - Note that objects stored in the dict may not be immutable. - """ - - def __init__(self, *args, **kwargs): - self.locked = False - super(FrozenDict, self).__init__(*args, **kwargs) - self.locked = True - - def __setitem__(self, key, value, **_): - if self.locked: - raise TypeError('frozen dict') - return super(FrozenDict, self).__setitem__(key, value) - - def __delitem__(self, key, **_): - if self.locked: - raise TypeError('frozen dict') - return super(FrozenDict, self).__delitem__(key) - - def __deepcopy__(self, memo): - res = [(deepcopy(k, memo), deepcopy(v, memo)) for k, v in self.iteritems()] - return FrozenDict(res) - -EMPTY_READ_ONLY_DICT = FrozenDict() - - -class StrictList(list): - """ - A list that raises :class:`~exceptions.TypeError` exceptions when objects of the wrong type are - inserted. - """ - - def __init__(self, - items=None, - value_class=None, - wrapper_function=None, - unwrapper_function=None): - super(StrictList, self).__init__() - if isinstance(items, StrictList): - self.value_class = items.value_class - self.wrapper_function = items.wrapper_function - self.unwrapper_function = items.unwrapper_function - self.value_class = value_class - self.wrapper_function = wrapper_function - self.unwrapper_function = unwrapper_function - if items: - for item in items: - self.append(item) - - def _wrap(self, value): - if (self.value_class is not None) and (not isinstance(value, self.value_class)): - raise TypeError('value must be a "%s": %s' % (cls_name(self.value_class), repr(value))) - if self.wrapper_function is not None: - value = self.wrapper_function(value) - return value - - def _unwrap(self, value): - if self.unwrapper_function is not None: - value = self.unwrapper_function(value) - return value - - def __getitem__(self, index): - value = super(StrictList, self).__getitem__(index) - value = self._unwrap(value) - return value - - def __setitem__(self, index, value): - value = self._wrap(value) - return super(StrictList, self).__setitem__(index, value) - - def __iadd__(self, values): - values = [self._wrap(v) for v in values] - return super(StrictList, self).__iadd__(values) - - def append(self, value): - value = self._wrap(value) - return super(StrictList, self).append(value) - - def extend(self, values): - values = [self._wrap(v) for v in values] - return super(StrictList, self).extend(values) - - def insert(self, index, value): - value = self._wrap(value) - return super(StrictList, self).insert(index, value) - - -class StrictDict(OrderedDict): - """ - An ordered dict that raises :class:`~exceptions.TypeError` exceptions when keys or values of the - wrong type are used. - """ - - def __init__(self, - items=None, - key_class=None, - value_class=None, - wrapper_function=None, - unwrapper_function=None): - super(StrictDict, self).__init__() - if isinstance(items, StrictDict): - self.key_class = items.key_class - self.value_class = items.value_class - self.wrapper_function = items.wrapper_function - self.unwrapper_function = items.unwrapper_function - self.key_class = key_class - self.value_class = value_class - self.wrapper_function = wrapper_function - self.unwrapper_function = unwrapper_function - if items: - for k, v in items: - self[k] = v - - def __getitem__(self, key): - if (self.key_class is not None) and (not isinstance(key, self.key_class)): - raise TypeError('key must be a "%s": %s' % (cls_name(self.key_class), repr(key))) - value = super(StrictDict, self).__getitem__(key) - if self.unwrapper_function is not None: - value = self.unwrapper_function(value) - return value - - def __setitem__(self, key, value, **_): - if (self.key_class is not None) and (not isinstance(key, self.key_class)): - raise TypeError('key must be a "%s": %s' % (cls_name(self.key_class), repr(key))) - if (self.value_class is not None) and (not isinstance(value, self.value_class)): - raise TypeError('value must be a "%s": %s' % (cls_name(self.value_class), repr(value))) - if self.wrapper_function is not None: - value = self.wrapper_function(value) - return super(StrictDict, self).__setitem__(key, value) - - -def merge(dict_a, dict_b, path=None, strict=False): - """ - Merges dicts, recursively. - """ - - # TODO: a.add_yaml_merge(b), see https://bitbucket.org/ruamel/yaml/src/ - # TODO: 86622a1408e0f171a12e140d53c4ffac4b6caaa3/comments.py?fileviewer=file-view-default - - path = path or [] - for key, value_b in dict_b.iteritems(): - if key in dict_a: - value_a = dict_a[key] - if isinstance(value_a, dict) and isinstance(value_b, dict): - merge(value_a, value_b, path + [str(key)], strict) - elif value_a != value_b: - if strict: - raise ValueError('dict merge conflict at %s' % '.'.join(path + [str(key)])) - else: - dict_a[key] = value_b - else: - dict_a[key] = value_b - return dict_a - - -def is_removable(_container, _key, v): - return (v is None) or ((isinstance(v, dict) or isinstance(v, list)) and (len(v) == 0)) - - -def prune(value, is_removable_function=is_removable): - """ - Deletes ``None`` and empty lists and dicts, recursively. - """ - - if isinstance(value, list): - for i, v in enumerate(value): - if is_removable_function(value, i, v): - del value[i] - else: - prune(v, is_removable_function) - elif isinstance(value, dict): - for k, v in value.items(): - if is_removable_function(value, k, v): - del value[k] - else: - prune(v, is_removable_function) - - return value - - -# TODO: Move following two methods to some place parser specific - -def deepcopy_with_locators(value): - """ - Like :func:`~copy.deepcopy`, but also copies over locators. - """ - - res = deepcopy(value) - copy_locators(res, value) - return res - - -def copy_locators(target, source): - """ - Copies over ``_locator`` for all elements, recursively. - - Assumes that target and source have exactly the same list/dict structure. - """ - - locator = getattr(source, '_locator', None) - if locator is not None: - try: - setattr(target, '_locator', locator) - except AttributeError: - pass - - if isinstance(target, list) and isinstance(source, list): - for i, _ in enumerate(target): - copy_locators(target[i], source[i]) - elif isinstance(target, dict) and isinstance(source, dict): - for k, v in target.iteritems(): - copy_locators(v, source[k]) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/console.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/console.py b/apache-ariatosca-0.1.1/aria/utils/console.py deleted file mode 100644 index 642cbb1..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/console.py +++ /dev/null @@ -1,68 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Abstraction API above terminal color libraries. -""" - -from clint.textui.core import STDOUT -from clint.textui import puts as _puts -from clint.textui.colored import ColoredString as _ColoredString -from clint.textui import indent # pylint: disable=unused-import - -from .formatting import safe_str - - -class ColoredString(_ColoredString): - def __init__(self, color, str_, always_color=False, bold=False): - super(ColoredString, self).__init__(color, safe_str(str_), always_color, bold) - - -def puts(string='', newline=True, stream=STDOUT): - _puts(safe_str(string), newline, stream) - - -class Colored(object): - @staticmethod - def black(string, always=False, bold=False): - return ColoredString('BLACK', string, always_color=always, bold=bold) - - @staticmethod - def red(string, always=False, bold=False): - return ColoredString('RED', string, always_color=always, bold=bold) - - @staticmethod - def green(string, always=False, bold=False): - return ColoredString('GREEN', string, always_color=always, bold=bold) - - @staticmethod - def yellow(string, always=False, bold=False): - return ColoredString('YELLOW', string, always_color=always, bold=bold) - - @staticmethod - def blue(string, always=False, bold=False): - return ColoredString('BLUE', string, always_color=always, bold=bold) - - @staticmethod - def magenta(string, always=False, bold=False): - return ColoredString('MAGENTA', string, always_color=always, bold=bold) - - @staticmethod - def cyan(string, always=False, bold=False): - return ColoredString('CYAN', string, always_color=always, bold=bold) - - @staticmethod - def white(string, always=False, bold=False): - return ColoredString('WHITE', string, always_color=always, bold=bold) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/exceptions.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/exceptions.py b/apache-ariatosca-0.1.1/aria/utils/exceptions.py deleted file mode 100644 index 5bb0e6d..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/exceptions.py +++ /dev/null @@ -1,120 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Utilities for extracting and formatting Python exceptions. -""" - -import sys -import linecache -import StringIO -import traceback as tb - -import jsonpickle - -from .console import (puts, indent, Colored) - - -ENTRY_FORMAT = 'File "{filename}", line {lineno}, in {name}' - - -def print_exception(e, full=True, cause=False, traceback=None): - """ - Prints the exception with nice colors and such. - """ - def format_heading(e): - return '{0}{1}: {2}'.format( - Colored.red('Caused by ') if cause else '', - Colored.red(e.__class__.__name__, bold=True), - Colored.red(e)) - - puts(format_heading(e)) - if full: - if cause: - if traceback: - print_traceback(traceback, True) - else: - print_traceback() - if hasattr(e, 'cause') and e.cause: - traceback = e.cause_traceback if hasattr(e, 'cause_traceback') else None - print_exception(e.cause, full=full, cause=True, traceback=traceback) - - -def print_traceback(traceback=None, print_last_stack=False): - """ - Prints the traceback with nice colors and such. - """ - - if traceback is None: - _, _, traceback = sys.exc_info() - while traceback is not None: - frame = traceback.tb_frame - code = frame.f_code - filename = code.co_filename - lineno = traceback.tb_lineno - name = code.co_name - with indent(2): - puts(ENTRY_FORMAT.format(filename=Colored.blue(filename), - lineno=Colored.cyan(lineno), - name=Colored.cyan(name))) - linecache.checkcache(filename) - line = linecache.getline(filename, lineno, frame.f_globals) - if line: - with indent(2): - puts(line.strip()) - traceback = traceback.tb_next - if print_last_stack and (traceback is None): - # Print stack of *last* traceback - _print_stack(frame) - - -def _print_stack(frame): - entries = tb.extract_stack(frame) - if not entries: - return - puts(Colored.red('Call stack:')) - with indent(2): - for filename, lineno, name, line in entries: - puts(ENTRY_FORMAT.format(filename=Colored.blue(filename), - lineno=Colored.cyan(lineno), - name=Colored.cyan(name))) - with indent(2): - puts(line) - - -def get_exception_as_string(exc_type, exc_val, traceback): - s_traceback = StringIO.StringIO() - tb.print_exception( - etype=exc_type, - value=exc_val, - tb=traceback, - file=s_traceback) - return s_traceback.getvalue() - - -class _WrappedException(Exception): - - def __init__(self, exception_type, exception_str): - super(_WrappedException, self).__init__(exception_type, exception_str) - self.exception_type = exception_type - self.exception_str = exception_str - - -def wrap_if_needed(exception): - try: - jsonpickle.loads(jsonpickle.dumps(exception)) - return exception - except BaseException: - return _WrappedException(type(exception).__name__, str(exception)) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/file.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/file.py b/apache-ariatosca-0.1.1/aria/utils/file.py deleted file mode 100644 index 75f2859..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/file.py +++ /dev/null @@ -1,46 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -File utilities. -""" - -import errno -import os -import shutil - - -def makedirs(path): - """ - Enhancement of :func:`os.makedirs` that doesn't fail if the directory already exists. - """ - if os.path.isdir(path): - return - try: - os.makedirs(path) - except IOError as e: - if e.errno != errno.EEXIST: - raise - -def remove_if_exists(path): - try: - if os.path.isfile(path): - os.remove(path) - if os.path.isdir(path): - shutil.rmtree(path) - - except OSError as e: - if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory - raise # re-raise exception if a different error occurred http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/formatting.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/formatting.py b/apache-ariatosca-0.1.1/aria/utils/formatting.py deleted file mode 100644 index fa34b7d..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/formatting.py +++ /dev/null @@ -1,235 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -String formatting and string-based format utilities. -""" - -import json -from types import MethodType - -from ruamel import yaml # @UnresolvedImport - -from .collections import FrozenList, FrozenDict, StrictList, StrictDict, OrderedDict - - -PLURALIZE_EXCEPTIONS = {} - - -# Add our types to ruamel.yaml (for round trips) -yaml.representer.RoundTripRepresenter.add_representer( - FrozenList, yaml.representer.RoundTripRepresenter.represent_list) -yaml.representer.RoundTripRepresenter.add_representer( - FrozenDict, yaml.representer.RoundTripRepresenter.represent_dict) -yaml.representer.RoundTripRepresenter.add_representer( - StrictList, yaml.representer.RoundTripRepresenter.represent_list) -yaml.representer.RoundTripRepresenter.add_representer( - StrictDict, yaml.representer.RoundTripRepresenter.represent_dict) - -# Without this, ruamel.yaml will output "!!omap" types, which is -# technically correct but unnecessarily verbose for our uses -yaml.representer.RoundTripRepresenter.add_representer( - OrderedDict, yaml.representer.RoundTripRepresenter.represent_dict) - - -class JsonAsRawEncoder(json.JSONEncoder): - """ - A :class:`JSONEncoder` that will use the ``as_raw`` property of objects if available. - """ - def raw_encoder_default(self, obj): - try: - return iter(obj) - except TypeError: - if hasattr(obj, 'as_raw'): - return as_raw(obj) - return str(obj) - return super(JsonAsRawEncoder, self).default(obj) - - def __init__(self, *args, **kwargs): - kwargs['default'] = self.raw_encoder_default - super(JsonAsRawEncoder, self).__init__(*args, **kwargs) - - -class YamlAsRawDumper(yaml.dumper.RoundTripDumper): # pylint: disable=too-many-ancestors - """ - A :class:`RoundTripDumper` that will use the ``as_raw`` property of objects if available. - """ - - def represent_data(self, data): - if hasattr(data, 'as_raw'): - data = as_raw(data) - return super(YamlAsRawDumper, self).represent_data(data) - - -def decode_list(data): - decoded_list = [] - for item in data: - if isinstance(item, unicode): - item = item.encode('utf-8') - elif isinstance(item, list): - item = decode_list(item) - elif isinstance(item, dict): - item = decode_dict(item) - decoded_list.append(item) - return decoded_list - - -def decode_dict(data): - decoded_dict = {} - for key, value in data.iteritems(): - if isinstance(key, unicode): - key = key.encode('utf-8') - if isinstance(value, unicode): - value = value.encode('utf-8') - elif isinstance(value, list): - value = decode_list(value) - elif isinstance(value, dict): - value = decode_dict(value) - decoded_dict[key] = value - return decoded_dict - - -def safe_str(value): - """ - Like :class:`str` coercion, but makes sure that Unicode strings are properly encoded, and will - never return ``None``. - """ - - try: - return str(value) - except UnicodeEncodeError: - return unicode(value).encode('utf8') - - -def safe_repr(value): - """ - Like :func:`repr`, but calls :func:`as_raw` and :func:`as_agnostic` first. - """ - - return repr(as_agnostic(as_raw(value))) - - -def string_list_as_string(strings): - """ - Nice representation of a list of strings. - """ - - if not strings: - return 'none' - return ', '.join('"{0}"'.format(safe_str(v)) for v in strings) - - -def pluralize(noun): - plural = PLURALIZE_EXCEPTIONS.get(noun) - if plural is not None: - return plural - elif noun.endswith('s'): - return '{0}es'.format(noun) - elif noun.endswith('y'): - return '{0}ies'.format(noun[:-1]) - else: - return '{0}s'.format(noun) - - -def as_raw(value): - """ - Converts values using their ``as_raw`` property, if it exists, recursively. - """ - - if hasattr(value, 'as_raw'): - value = value.as_raw - if isinstance(value, MethodType): - # Old-style Python classes don't support properties - value = value() - elif isinstance(value, list): - value = list(value) - for i, v in enumerate(value): - value[i] = as_raw(v) - elif isinstance(value, dict): - value = dict(value) - for k, v in value.iteritems(): - value[k] = as_raw(v) - return value - - -def as_raw_list(value): - """ - Assuming value is a list, converts its values using :func:`as_raw`. - """ - - if value is None: - return [] - if isinstance(value, dict): - value = value.itervalues() - return [as_raw(v) for v in value] - - -def as_raw_dict(value): - """ - Assuming value is a dict, converts its values using :func:`as_raw`. The keys are left as is. - """ - - if value is None: - return OrderedDict() - return OrderedDict(( - (k, as_raw(v)) for k, v in value.iteritems())) - - -def as_agnostic(value): - """ - Converts subclasses of list and dict to standard lists and dicts, and Unicode strings to - non-Unicode if possible, recursively. - - Useful for creating human-readable output of structures. - """ - - if isinstance(value, unicode): - try: - value = str(value) - except UnicodeEncodeError: - pass - elif isinstance(value, list): - value = list(value) - elif isinstance(value, dict): - value = dict(value) - - if isinstance(value, list): - for i, _ in enumerate(value): - value[i] = as_agnostic(value[i]) - elif isinstance(value, dict): - for k, v in value.iteritems(): - value[k] = as_agnostic(v) - - return value - - -def json_dumps(value, indent=2): - """ - JSON dumps that supports Unicode and the ``as_raw`` property of objects if available. - """ - - return json.dumps(value, indent=indent, ensure_ascii=False, cls=JsonAsRawEncoder) - - -def yaml_dumps(value, indent=2): - """ - YAML dumps that supports Unicode and the ``as_raw`` property of objects if available. - """ - - return yaml.dump(value, indent=indent, allow_unicode=True, Dumper=YamlAsRawDumper) - - -def yaml_loads(value): - return yaml.load(value, Loader=yaml.SafeLoader) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/http.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/http.py b/apache-ariatosca-0.1.1/aria/utils/http.py deleted file mode 100644 index c8357e9..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/http.py +++ /dev/null @@ -1,66 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -HTTP utilities. -""" - -import os -import tempfile - -import requests - - -def download_file(url, destination=None, logger=None, progress_handler=None): - """ - Download file. - - :param url: URL from which to download - :type url: basestring - :param destination: path where the file should be saved or ``None`` to auto-generate - :type destination: basestring - :returns: path where the file was saved - :rtype: basestring - :raises exceptions.IOError: - :raises requests.exceptions.RequestException: - """ - chunk_size = 1024 - - if not destination: - file_descriptor, destination = tempfile.mkstemp() - os.close(file_descriptor) - if logger: - logger.info('Downloading {0} to {1}...'.format(url, destination)) - - response = requests.get(url, stream=True) - final_url = response.url - if final_url != url and logger: - logger.debug('Redirected to {0}'.format(final_url)) - - read_bytes = 0 - total_size = int(response.headers['Content-Length']) \ - if 'Content-Length' in response.headers else None - try: - with open(destination, 'wb') as destination_file: - for chunk in response.iter_content(chunk_size): - destination_file.write(chunk) - if total_size and progress_handler: - # Only showing progress bar if we have the total content length - read_bytes += chunk_size - progress_handler(read_bytes, total_size) - finally: - response.close() - - return destination http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/imports.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/imports.py b/apache-ariatosca-0.1.1/aria/utils/imports.py deleted file mode 100644 index 14ad09e..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/imports.py +++ /dev/null @@ -1,96 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Utilities for dynamically loading Python code. -""" - -import pkgutil -import importlib - - -def import_fullname(name, paths=None): - """ - Imports a variable or class based on a full name, optionally searching for it in the paths. - """ - paths = paths or [] - if name is None: - return None - - def do_import(name): - if name and ('.' in name): - module_name, name = name.rsplit('.', 1) - return getattr(__import__(module_name, fromlist=[name], level=0), name) - else: - raise ImportError('import not found: %s' % name) - - try: - return do_import(name) - except ImportError: - for path in paths: - try: - return do_import('%s.%s' % (path, name)) - except Exception as e: - raise ImportError('cannot import %s, because %s' % (name, e)) - - raise ImportError('import not found: %s' % name) - - -def import_modules(name): - """ - Imports a module and all its sub-modules, recursively. Relies on modules defining a ``MODULES`` - attribute listing their sub-module names. - """ - - module = __import__(name, fromlist=['MODULES'], level=0) - if hasattr(module, 'MODULES'): - for module_ in module.MODULES: - import_modules('%s.%s' % (name, module_)) - - -# TODO merge with import_fullname -def load_attribute(attribute_path): - """ - Dynamically load an attribute based on the path to it. E.g. - ``some_package.some_module.some_attribute``, will load ``some_attribute`` from the - ``some_package.some_module`` module. - """ - module_name, attribute_name = attribute_path.rsplit('.', 1) - try: - module = importlib.import_module(module_name) - return getattr(module, attribute_name) - except ImportError: - # TODO: handle - raise - except AttributeError: - # TODO: handle - raise - - -def iter_modules(): - # apparently pkgutil had some issues in python 2.6. Accessing any root level directories - # failed. and it got the entire process of importing fail. Since we only need any - # aria_extension related loading, in the meantime we could try to import only those - # (and assume they are not located at the root level. - # [In python 2.7 it does actually ignore any OSError]. - yielded = {} - for importer in pkgutil.iter_importers(): - try: - for module_name, ispkg in pkgutil.iter_importer_modules(importer): - if module_name not in yielded: - yielded[module_name] = True - yield importer, module_name, ispkg - except OSError: - pass http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/openclose.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/openclose.py b/apache-ariatosca-0.1.1/aria/utils/openclose.py deleted file mode 100644 index 722885c..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/openclose.py +++ /dev/null @@ -1,36 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Utilities for working with open/close patterns. -""" - -class OpenClose(object): - """ - Wraps an object that has ``open()`` and ``close()`` methods to support the ``with`` keyword. - """ - - def __init__(self, wrapped): - self.wrapped = wrapped - - def __enter__(self): - if hasattr(self.wrapped, 'open'): - self.wrapped.open() - return self.wrapped - - def __exit__(self, the_type, value, traceback): - if hasattr(self.wrapped, 'close'): - self.wrapped.close() - return False http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/plugin.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/plugin.py b/apache-ariatosca-0.1.1/aria/utils/plugin.py deleted file mode 100644 index 4fb6a8e..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/plugin.py +++ /dev/null @@ -1,24 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Plugin utilities. -""" - -import wagon - - -def create(source, destination_dir): - return wagon.create(source=source, archive_destination_dir=destination_dir) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/process.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/process.py b/apache-ariatosca-0.1.1/aria/utils/process.py deleted file mode 100644 index ec4a72d..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/process.py +++ /dev/null @@ -1,51 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Process utilities. -""" - -import os - - -def append_to_path(*args, **kwargs): - """ - Appends one or more paths to the system path of an environment. - The environment will be that of the current process unless another is passed using the - 'env' keyword argument. - :param args: paths to append - :param kwargs: 'env' may be used to pass a custom environment to use - """ - _append_to_path('PATH', *args, **kwargs) - - -def append_to_pythonpath(*args, **kwargs): - """ - Appends one or more paths to the python path of an environment. - The environment will be that of the current process unless another is passed using the - 'env' keyword argument. - :param args: paths to append - :param kwargs: 'env' may be used to pass a custom environment to use - """ - _append_to_path('PYTHONPATH', *args, **kwargs) - - -def _append_to_path(path, *args, **kwargs): - env = kwargs.get('env') or os.environ - env[path] = '{0}{1}{2}'.format( - os.pathsep.join(args), - os.pathsep, - env.get(path, '') - ) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/specification.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/specification.py b/apache-ariatosca-0.1.1/aria/utils/specification.py deleted file mode 100644 index 8c51134..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/specification.py +++ /dev/null @@ -1,57 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Utilities for cross-referencing code with specification documents. -""" - -from .collections import OrderedDict - - -DSL_SPECIFICATIONS = {} - - -def implements_specification(section, spec): - """ - Decorator for specification implementations. - - Used for documentation and standards compliance. - """ - - from .type import full_type_name - - def decorator(obj): - specification = DSL_SPECIFICATIONS.get(spec) - - if specification is None: - specification = {} - DSL_SPECIFICATIONS[spec] = specification - - if section in specification: - raise Exception('you cannot specify the same @implements_specification twice, consider' - ' adding \'-1\', \'-2\', etc.: {0}, {1}'.format(spec, section)) - - specification[section] = OrderedDict(( - ('code', full_type_name(obj)), - ('doc', obj.__doc__))) - - try: - setattr(obj, '_dsl_specifications', {section: section, spec: spec}) - except BaseException: - pass - - return obj - - return decorator http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/threading.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/threading.py b/apache-ariatosca-0.1.1/aria/utils/threading.py deleted file mode 100644 index f5ca302..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/threading.py +++ /dev/null @@ -1,286 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Threading utilities. -""" - -from __future__ import absolute_import # so we can import standard 'threading' - -import sys -import itertools -import multiprocessing -from threading import (Thread, Lock) -from Queue import (Queue, Full, Empty) - -from .exceptions import print_exception - -class ExecutorException(Exception): - pass - - -class DaemonThread(Thread): - def __init__(self, *args, **kwargs): - super(DaemonThread, self).__init__(*args, **kwargs) - self.daemon = True - - def run(self): - """ - We're overriding ``Thread.run`` in order to avoid annoying (but harmless) error messages - during shutdown. The problem is that CPython nullifies the global state _before_ shutting - down daemon threads, so that exceptions might happen, and then ``Thread.__bootstrap_inner`` - prints them out. - - Our solution is to swallow these exceptions here. - - The side effect is that uncaught exceptions in our own thread code will _not_ be printed out - as usual, so it's our responsibility to catch them in our code. - """ - - try: - super(DaemonThread, self).run() - except SystemExit as e: - # This exception should be bubbled up - raise e - except BaseException: - # Exceptions might occur in daemon threads during interpreter shutdown - pass - - -# https://gist.github.com/tliron/81dd915166b0bfc64be08b4f8e22c835 -class FixedThreadPoolExecutor(object): - """ - Executes tasks in a fixed thread pool. - - Makes sure to gather all returned results and thrown exceptions in one place, in order of task - submission. - - Example:: - - def sum(arg1, arg2): - return arg1 + arg2 - - executor = FixedThreadPoolExecutor(10) - try: - for value in range(100): - executor.submit(sum, value, value) - executor.drain() - except: - executor.close() - executor.raise_first() - print executor.returns - - You can also use it with the Python ``with`` keyword, in which case you don't need to call - ``close`` explicitly:: - - with FixedThreadPoolExecutor(10) as executor: - for value in range(100): - executor.submit(sum, value, value) - executor.drain() - executor.raise_first() - print executor.returns - """ - - _CYANIDE = object() # Special task marker used to kill worker threads. - - def __init__(self, - size=None, - timeout=None, - print_exceptions=False): - """ - :param size: number of threads in the pool; if ``None`` will use an optimal number for the - platform - :param timeout: timeout in seconds for all blocking operations (``None`` means no timeout) - :param print_exceptions: set to ``True`` in order to print exceptions from tasks - """ - if not size: - try: - size = multiprocessing.cpu_count() * 2 + 1 - except NotImplementedError: - size = 3 - - self.size = size - self.timeout = timeout - self.print_exceptions = print_exceptions - - self._tasks = Queue() - self._returns = {} - self._exceptions = {} - self._id_creator = itertools.count() - self._lock = Lock() # for console output - - self._workers = [] - for index in range(size): - worker = DaemonThread( - name='%s%d' % (self.__class__.__name__, index), - target=self._thread_worker) - worker.start() - self._workers.append(worker) - - def submit(self, func, *args, **kwargs): - """ - Submit a task for execution. - - The task will be called ASAP on the next available worker thread in the pool. - - :raises ExecutorException: if cannot be submitted - """ - - try: - self._tasks.put((self._id_creator.next(), func, args, kwargs), timeout=self.timeout) - except Full: - raise ExecutorException('cannot submit task: queue is full') - - def close(self): - """ - Blocks until all current tasks finish execution and all worker threads are dead. - - You cannot submit tasks anymore after calling this. - - This is called automatically upon exit if you are using the ``with`` keyword. - """ - - self.drain() - while self.is_alive: - try: - self._tasks.put(self._CYANIDE, timeout=self.timeout) - except Full: - raise ExecutorException('cannot close executor: a thread seems to be hanging') - self._workers = None - - def drain(self): - """ - Blocks until all current tasks finish execution, but leaves the worker threads alive. - """ - - self._tasks.join() # oddly, the API does not support a timeout parameter - - @property - def is_alive(self): - """ - True if any of the worker threads are alive. - """ - - for worker in self._workers: - if worker.is_alive(): - return True - return False - - @property - def returns(self): - """ - The returned values from all tasks, in order of submission. - """ - - return [self._returns[k] for k in sorted(self._returns)] - - @property - def exceptions(self): - """ - The raised exceptions from all tasks, in order of submission. - """ - - return [self._exceptions[k] for k in sorted(self._exceptions)] - - def raise_first(self): - """ - If exceptions were thrown by any task, then the first one will be raised. - - This is rather arbitrary: proper handling would involve iterating all the exceptions. - However, if you want to use the "raise" mechanism, you are limited to raising only one of - them. - """ - - exceptions = self.exceptions - if exceptions: - raise exceptions[0] - - def _thread_worker(self): - while True: - if not self._execute_next_task(): - break - - def _execute_next_task(self): - try: - task = self._tasks.get(timeout=self.timeout) - except Empty: - # Happens if timeout is reached - return True - if task == self._CYANIDE: - # Time to die :( - return False - self._execute_task(*task) - return True - - def _execute_task(self, task_id, func, args, kwargs): - try: - result = func(*args, **kwargs) - self._returns[task_id] = result - except Exception as e: - self._exceptions[task_id] = e - if self.print_exceptions: - with self._lock: - print_exception(e) - self._tasks.task_done() - - def __enter__(self): - return self - - def __exit__(self, the_type, value, traceback): - self.close() - return False - - -class LockedList(list): - """ - A list that supports the ``with`` keyword with a built-in lock. - - Though Python lists are thread-safe in that they will not raise exceptions during concurrent - access, they do not guarantee atomicity. This class will let you gain atomicity when needed. - """ - - def __init__(self, *args, **kwargs): - super(LockedList, self).__init__(*args, **kwargs) - self.lock = Lock() - - def __enter__(self): - return self.lock.__enter__() - - def __exit__(self, the_type, value, traceback): - return self.lock.__exit__(the_type, value, traceback) - - -class ExceptionThread(Thread): - """ - A thread from which top level exceptions can be retrieved or re-raised. - """ - def __init__(self, *args, **kwargs): - Thread.__init__(self, *args, **kwargs) - self.exception = None - self.daemon = True - - def run(self): - try: - super(ExceptionThread, self).run() - except BaseException: - self.exception = sys.exc_info() - - def is_error(self): - return self.exception is not None - - def raise_error_if_exists(self): - if self.is_error(): - type_, value, trace = self.exception - raise type_, value, trace http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/type.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/type.py b/apache-ariatosca-0.1.1/aria/utils/type.py deleted file mode 100644 index fe88a62..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/type.py +++ /dev/null @@ -1,156 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Type utilities. -""" - -import datetime - -from .specification import implements_specification - - -BASE_TYPES_TO_CANONICAL_NAMES = { - # TOSCA aliases: - None.__class__: 'null', - basestring: 'string', - int: 'integer', - float: 'float', - bool: 'boolean', - list: 'list', - tuple: 'list', - dict: 'map', - datetime.datetime: 'timestamp' -} - -NAMES_TO_CANONICAL_TYPES = { - # Python: - 'none': None.__class__, - 'basestring': unicode, - 'str': unicode, - 'unicode': unicode, - 'int': int, - 'float': float, # also a TOSCA alias - 'bool': bool, - 'list': list, # also a TOSCA alias - 'tuple': list, - 'dict': dict, - 'datetime': datetime.datetime, - - # YAML 1.2: - 'tag:yaml.org,2002:null': None.__class__, - 'tag:yaml.org,2002:str': unicode, - 'tag:yaml.org,2002:integer': int, - 'tag:yaml.org,2002:float': float, - 'tag:yaml.org,2002:bool': bool, - - # TOSCA aliases: - 'null': None.__class__, - 'string': unicode, - 'integer': int, - 'boolean': bool, - - # TOSCA custom types: - 'map': dict, - 'timestamp': datetime.datetime -} - - -def full_type_name(value): - """ - The full class name of a type or instance. - """ - - if not isinstance(value, type): - value = value.__class__ - module = str(value.__module__) - name = str(value.__name__) - return name if module == '__builtin__' else '{0}.{1}'.format(module, name) - - -@implements_specification('3.2.1-1', 'tosca-simple-1.0') -def canonical_type_name(value): - """ - Returns the canonical TOSCA type name of a primitive value, or ``None`` if unknown. - - For a list of TOSCA type names, see the `TOSCA Simple Profile v1.0 - cos01 specification <http://docs.oasis-open.org/tosca/TOSCA-Simple-Profile-YAML/v1.0/cos01 - /TOSCA-Simple-Profile-YAML-v1.0-cos01.html#_Toc373867862>`__ - """ - - for the_type, name in BASE_TYPES_TO_CANONICAL_NAMES.iteritems(): - if isinstance(value, the_type): - return name - return None - - -@implements_specification('3.2.1-2', 'tosca-simple-1.0') -def canonical_type(type_name): - """ - Return the canonical type for any Python, YAML, or TOSCA type name or alias, or ``None`` if - unsupported. - - :param type_name: Type name (case insensitive) - """ - - return NAMES_TO_CANONICAL_TYPES.get(type_name.lower()) - - -def validate_value_type(value, type_name): - """ - Validate that a value is of a specific type. Supports Python, YAML, and TOSCA type names and - aliases. - - :param type_name: type name (case insensitive) - :raises ~exceptions.ValueError: on type mismatch - """ - - the_type = canonical_type(type_name) - if the_type is None: - raise RuntimeError('Unsupported type name: {0}'.format(type_name)) - - # The following Python types do not inherit from the canonical type, but are considered valid - if (the_type is unicode) and isinstance(value, str): - return - if (the_type is list) and isinstance(value, tuple): - return - - if not isinstance(value, the_type): - raise ValueError('Value {0} is not of type {1}'.format(value, type_name)) - - -def convert_value_to_type(str_value, python_type_name): - """ - Converts a value to a specific Python primitive type. - - :param python_type_name: Python primitive type name (case insensitive) - :raises ~exceptions.ValueError: for unsupported types or conversion failure - """ - - python_type_name = python_type_name.lower() - try: - if python_type_name in ('str', 'unicode'): - return str_value.decode('utf-8') - elif python_type_name == 'int': - return int(str_value) - elif python_type_name == 'bool': - return bool(str_value) - elif python_type_name == 'float': - return float(str_value) - else: - raise ValueError('Unsupported Python type name: {0}'.format(python_type_name)) - except ValueError: - raise ValueError('Failed to to convert {0} to {1}'.format(str_value, - python_type_name)) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/uris.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/uris.py b/apache-ariatosca-0.1.1/aria/utils/uris.py deleted file mode 100644 index 49881f2..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/uris.py +++ /dev/null @@ -1,48 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -URI utilities. -""" - -import os -import urlparse - - -_IS_WINDOWS = (os.name == 'nt') - - -def as_file(uri): - """ - If the URI is a file (either the ``file`` scheme or no scheme), then returns the normalized - path. Otherwise, returns ``None``. - """ - - if _IS_WINDOWS: - # We need this extra check in Windows before urlparse because paths might have a drive - # prefix, e.g. "C:" which will be considered a scheme for urlparse below - path = uri.replace('/', '\\') - if os.path.exists(path): - return os.path.normpath(path) - - url = urlparse.urlparse(uri) - scheme = url.scheme - if (not scheme) or (scheme == 'file'): - path = url.path - if _IS_WINDOWS: - path = path.replace('/', '\\') - return os.path.normpath(path) - - return None http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/uuid.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/uuid.py b/apache-ariatosca-0.1.1/aria/utils/uuid.py deleted file mode 100644 index d6c9ced..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/uuid.py +++ /dev/null @@ -1,70 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -UUID generation utilities. -""" - -from __future__ import absolute_import # so we can import standard 'uuid' - -from random import randrange -from uuid import uuid4 - -from shortuuid import ShortUUID - - -# Alphanumeric without visually ambiguous characters; default length is 22 -UUID_BASE57 = ShortUUID() - -# Lower-case alphanumeric; default length is 25 -UUID_LOWERCASE_ALPHANUMERIC = ShortUUID(alphabet='abcdefghijklmnopqrstuvwxyz0123456789') - - -def generate_uuid(length=None, variant='base57'): - """ - A random string with varying degrees of guarantee of universal uniqueness. - - :param variant: - * ``base57`` (the default) uses a mix of upper and lowercase alphanumerics ensuring no visually - ambiguous characters; default length 22 - * ``alphanumeric`` uses lowercase alphanumeric; default length 25 - * ``uuid`` uses lowercase hexadecimal in the classic UUID format, including dashes; length is - always 36 - * ``hex`` uses lowercase hexadecimal characters but has no guarantee of uniqueness; default - length of 5 - """ - - if variant == 'base57': - the_id = UUID_BASE57.uuid() - if length is not None: - the_id = the_id[:length] - - elif variant == 'alphanumeric': - the_id = UUID_LOWERCASE_ALPHANUMERIC.uuid() - if length is not None: - the_id = the_id[:length] - - elif variant == 'uuid': - the_id = str(uuid4()) - - elif variant == 'hex': - length = length or 5 - # See: http://stackoverflow.com/a/2782859 - the_id = ('%0' + str(length) + 'x') % randrange(16 ** length) - - else: - raise ValueError('unsupported UUID variant: {0}'.format(variant)) - - return the_id http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/validation.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/validation.py b/apache-ariatosca-0.1.1/aria/utils/validation.py deleted file mode 100644 index 06989a7..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/validation.py +++ /dev/null @@ -1,97 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Validation utilities. -""" - -from .formatting import string_list_as_string - - -class ValidatorMixin(object): - """ - A mix0in that should be added to classes that require validating user input. - """ - - _ARGUMENT_TYPE_MESSAGE = '{name} argument must be {type} based, got {arg!r}' - _ARGUMENT_CHOICE_MESSAGE = '{name} argument must be in {choices}, got {arg!r}' - - @classmethod - def validate_in_choice(cls, name, argument, choices): - """ - Validate ``argument`` is in ``choices`` - """ - if argument not in choices: - raise TypeError(cls._ARGUMENT_CHOICE_MESSAGE.format( - name=name, choices=choices, arg=argument)) - - @classmethod - def validate_type(cls, argument_name, argument, expected_type): - """ - Validate ``argument`` is a subclass of ``expected_type`` - """ - if not issubclass(argument, expected_type): - raise TypeError(cls._ARGUMENT_TYPE_MESSAGE.format( - name=argument_name, type=expected_type, arg=argument)) - - @classmethod - def validate_instance(cls, argument_name, argument, expected_type): - """ - Validate ``argument`` is a instance of ``expected_type`` - """ - if not isinstance(argument, expected_type): - raise TypeError(cls._ARGUMENT_TYPE_MESSAGE.format( - name=argument_name, type=expected_type, arg=argument)) - - @classmethod - def validate_callable(cls, argument_name, argument): - """ - Validate ``argument`` is callable - """ - if not callable(argument): - raise TypeError(cls._ARGUMENT_TYPE_MESSAGE.format( - name=argument_name, type='callable', arg=argument)) - - -def validate_function_arguments(func, func_kwargs): - """ - Validates all required arguments are supplied to ``func`` and that no additional arguments are - supplied. - """ - - _kwargs_flags = 8 - - has_kwargs = func.func_code.co_flags & _kwargs_flags != 0 - args_count = func.func_code.co_argcount - - # all args without the ones with default values - args = func.func_code.co_varnames[:args_count] - non_default_args = args[:len(args) - len(func.func_defaults)] if func.func_defaults else args - - # Check if any args without default values is missing in the func_kwargs - for arg in non_default_args: - if arg not in func_kwargs: - raise ValueError( - 'The argument "{arg}" is not provided and does not have a default value for ' - 'function "{func.__name__}"'.format(arg=arg, func=func)) - - # check if there are any extra kwargs - extra_kwargs = [arg for arg in func_kwargs.keys() if arg not in args] - - # assert that the function has kwargs - if extra_kwargs and not has_kwargs: - raise ValueError("The following extra kwargs were supplied: {extra_kwargs}".format( - extra_kwargs=string_list_as_string(extra_kwargs) - )) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/utils/versions.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/utils/versions.py b/apache-ariatosca-0.1.1/aria/utils/versions.py deleted file mode 100644 index 521004c..0000000 --- a/apache-ariatosca-0.1.1/aria/utils/versions.py +++ /dev/null @@ -1,163 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -""" -Verion string utilities. -""" - -import re - - -_INF = float('inf') - -_NULL = (), _INF - -_DIGITS_RE = re.compile(r'^\d+$') - -_PREFIXES = { - 'dev': 0.0001, - 'alpha': 0.001, - 'beta': 0.01, - 'rc': 0.1 -} - - -class VersionString(unicode): - """ - Version string that can be compared, sorted, made unique in a set, and used as a unique dict - key. - - The primary part of the string is one or more dot-separated natural numbers. Trailing zeroes - are treated as redundant, e.g. "1.0.0" == "1.0" == "1". - - An optional qualifier can be added after a "-". The qualifier can be a natural number or a - specially treated prefixed natural number, e.g. "1.1-beta1" > "1.1-alpha2". The case of the - prefix is ignored. - - Numeric qualifiers will always be greater than prefixed integer qualifiers, e.g. "1.1-1" > - "1.1-beta1". - - Versions without a qualifier will always be greater than their equivalents with a qualifier, - e.g. e.g. "1.1" > "1.1-1". - - Any value that does not conform to this format will be treated as a zero version, which would - be lesser than any non-zero version. - - For efficient list sorts use the ``key`` property, e.g.:: - - sorted(versions, key=lambda x: x.key) - """ - - NULL = None # initialized below - - def __init__(self, value=None): - if value is not None: - super(VersionString, self).__init__(value) - self.key = parse_version_string(self) - - def __eq__(self, version): - if not isinstance(version, VersionString): - version = VersionString(version) - return self.key == version.key - - def __lt__(self, version): - if not isinstance(version, VersionString): - version = VersionString(version) - return self.key < version.key - - def __hash__(self): - return self.key.__hash__() - - -def parse_version_string(version): # pylint: disable=too-many-branches - """ - Parses a version string. - - :param version: version string - :returns: primary tuple and qualifier float - :rtype: ((:obj:`int`), :obj:`float`) - """ - - if version is None: - return _NULL - version = unicode(version) - - # Split to primary and qualifier on '-' - split = version.split('-', 1) - if len(split) == 2: - primary, qualifier = split - else: - primary = split[0] - qualifier = None - - # Parse primary - split = primary.split('.') - primary = [] - for element in split: - if _DIGITS_RE.match(element) is None: - # Invalid version string - return _NULL - try: - element = int(element) - except ValueError: - # Invalid version string - return _NULL - primary.append(element) - - # Remove redundant zeros - for element in reversed(primary): - if element == 0: - primary.pop() - else: - break - primary = tuple(primary) - - # Parse qualifier - if qualifier is not None: - if _DIGITS_RE.match(qualifier) is not None: - # Integer qualifier - try: - qualifier = float(int(qualifier)) - except ValueError: - # Invalid version string - return _NULL - else: - # Prefixed integer qualifier - value = None - qualifier = qualifier.lower() - for prefix, factor in _PREFIXES.iteritems(): - if qualifier.startswith(prefix): - value = qualifier[len(prefix):] - if _DIGITS_RE.match(value) is None: - # Invalid version string - return _NULL - try: - value = float(int(value)) * factor - except ValueError: - # Invalid version string - return _NULL - break - if value is None: - # Invalid version string - return _NULL - qualifier = value - else: - # Version strings with no qualifiers are higher - qualifier = _INF - - return primary, qualifier - - -VersionString.NULL = VersionString() http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/examples/hello-world/helloworld.yaml ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/examples/hello-world/helloworld.yaml b/apache-ariatosca-0.1.1/examples/hello-world/helloworld.yaml deleted file mode 100644 index d3369b7..0000000 --- a/apache-ariatosca-0.1.1/examples/hello-world/helloworld.yaml +++ /dev/null @@ -1,38 +0,0 @@ -tosca_definitions_version: tosca_simple_yaml_1_0 - -node_types: - - WebServer: - derived_from: tosca.nodes.Root - capabilities: - host: - type: tosca.capabilities.Container - - WebApp: - derived_from: tosca.nodes.WebApplication - properties: - port: - type: integer - -topology_template: - - node_templates: - web_server: - type: WebServer - - web_app: - type: WebApp - properties: - port: 9090 - requirements: - - host: web_server - interfaces: - Standard: - configure: scripts/configure.sh - start: scripts/start.sh - stop: scripts/stop.sh - - outputs: - port: - type: integer - value: { get_property: [ web_app, port ] } http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/examples/hello-world/images/aria-logo.png ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/examples/hello-world/images/aria-logo.png b/apache-ariatosca-0.1.1/examples/hello-world/images/aria-logo.png deleted file mode 100644 index 3505844..0000000 Binary files a/apache-ariatosca-0.1.1/examples/hello-world/images/aria-logo.png and /dev/null differ http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/examples/hello-world/index.html ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/examples/hello-world/index.html b/apache-ariatosca-0.1.1/examples/hello-world/index.html deleted file mode 100644 index 8d21c3a..0000000 --- a/apache-ariatosca-0.1.1/examples/hello-world/index.html +++ /dev/null @@ -1,14 +0,0 @@ -<html> - <header> - <title>ARIA Hello World</title> - </header> -<body> - <h1>Hello, World!</h1> - <p> - blueprint_id = {{ ctx.service_template.name }}<br/> - deployment_id = {{ ctx.service.name }}<br/> - node_id = {{ ctx.node.name }} - </p> - <img src="aria-logo.png"> -</body> -</html> \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/examples/hello-world/scripts/configure.sh ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/examples/hello-world/scripts/configure.sh b/apache-ariatosca-0.1.1/examples/hello-world/scripts/configure.sh deleted file mode 100755 index 9ac26d5..0000000 --- a/apache-ariatosca-0.1.1/examples/hello-world/scripts/configure.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -set -e - -TEMP_DIR="/tmp" -PYTHON_FILE_SERVER_ROOT=${TEMP_DIR}/python-simple-http-webserver -if [ -d ${PYTHON_FILE_SERVER_ROOT} ]; then - echo "Removing file server root folder ${PYTHON_FILE_SERVER_ROOT}" - rm -rf ${PYTHON_FILE_SERVER_ROOT} -fi -ctx logger info "Creating HTTP server root directory at ${PYTHON_FILE_SERVER_ROOT}" - -mkdir -p ${PYTHON_FILE_SERVER_ROOT} - -cd ${PYTHON_FILE_SERVER_ROOT} - -index_path="index.html" -image_path="images/aria-logo.png" - -ctx logger info "Downloading blueprint resources..." -ctx download-resource-and-render ${PYTHON_FILE_SERVER_ROOT}/index.html ${index_path} -ctx download-resource ${PYTHON_FILE_SERVER_ROOT}/aria-logo.png ${image_path} - http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/examples/hello-world/scripts/start.sh ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/examples/hello-world/scripts/start.sh b/apache-ariatosca-0.1.1/examples/hello-world/scripts/start.sh deleted file mode 100755 index 010af2c..0000000 --- a/apache-ariatosca-0.1.1/examples/hello-world/scripts/start.sh +++ /dev/null @@ -1,66 +0,0 @@ -#!/bin/bash -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You 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. - -set -e - -TEMP_DIR="/tmp" -PYTHON_FILE_SERVER_ROOT=${TEMP_DIR}/python-simple-http-webserver -PID_FILE="server.pid" - -ctx logger info "Starting HTTP server from ${PYTHON_FILE_SERVER_ROOT}" - -port=$(ctx node properties port) - -cd ${PYTHON_FILE_SERVER_ROOT} -ctx logger info "Starting SimpleHTTPServer" -nohup python -m SimpleHTTPServer ${port} > /dev/null 2>&1 & -echo $! > ${PID_FILE} - -ctx logger info "Waiting for server to launch on port ${port}" -url="http://localhost:${port}" - -server_is_up() { - if which wget >/dev/null; then - if wget $url >/dev/null; then - return 0 - fi - elif which curl >/dev/null; then - if curl $url >/dev/null; then - return 0 - fi - else - ctx logger error "Both curl, wget were not found in path" - exit 1 - fi - return 1 -} - -STARTED=false -for i in $(seq 1 15) -do - if server_is_up; then - ctx logger info "Server is up." - STARTED=true - break - else - ctx logger info "Server not up. waiting 1 second." - sleep 1 - fi -done -if [ ${STARTED} = false ]; then - ctx logger error "Failed starting web server in 15 seconds." - exit 1 -fi
