gurudesh/pytracebugs huggingface dataset:
# Buggy code
def beacons(opts, functions, context=None):
    """
    Load the beacon modules

    :param dict opts: The Salt options dictionary
    :param dict functions: A dictionary of minion modules, with module names as
                            keys and funcs as values.
    """
    return LazyLoader(
        _module_dirs(opts, "beacons", "beacons"),
        opts,
        tag="beacons",
        pack={"__context__": context, "__salt__": functions},
    )


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def beacons(opts, functions, context=None, proxy=None):
    """
    Load the beacon modules

    :param dict opts: The Salt options dictionary
    :param dict functions: A dictionary of minion modules, with module names as
                            keys and funcs as values.
    """
    return LazyLoader(
        _module_dirs(opts, "beacons", "beacons"),
        opts,
        tag="beacons",
        pack={"__context__": context, "__salt__": functions, "__proxy__": proxy or {}},
    )
# Buggy code
def executors(opts, functions=None, context=None):
    """
    Returns the executor modules
    """
    return LazyLoader(
        _module_dirs(opts, "executors", "executor"),
        opts,
        tag="executor",
        pack={"__salt__": functions, "__context__": context or {}},
    )


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def executors(opts, functions=None, context=None, proxy=None):
    """
    Returns the executor modules
    """
    return LazyLoader(
        _module_dirs(opts, "executors", "executor"),
        opts,
        tag="executor",
        pack={
            "__salt__": functions,
            "__context__": context or {},
            "__proxy__": proxy or {},
        },
    )
# Buggy code
def _load_states(self):
    """
    Read the state loader value and loadup the correct states subsystem
    """
    if self.states_loader == "thorium":
        self.states = salt.loader.thorium(
            self.opts, self.functions, {}
        )  # TODO: Add runners
    else:
        self.states = salt.loader.states(
            self.opts, self.functions, self.utils, self.serializers
        )


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def _load_states(self):
    """
    Read the state loader value and loadup the correct states subsystem
    """
    if self.states_loader == "thorium":
        self.states = salt.loader.thorium(
            self.opts, self.functions, {}
        )  # TODO: Add runners
    else:
        self.states = salt.loader.states(
            self.opts, self.functions, self.utils, self.serializers, proxy=self.proxy
        )
# Buggy code
def proxy(opts, functions=None, returners=None, whitelist=None):
    """
    Returns the proxy module for this salt-proxy-minion
    """
    ret = LazyLoader(
        _module_dirs(opts, "proxy"),
        opts,
        tag="proxy",
        pack={"__salt__": functions, "__ret__": returners},
    )

    ret.pack["__proxy__"] = ret

    return ret


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def proxy(opts, functions=None, returners=None, whitelist=None, utils=None):
    """
    Returns the proxy module for this salt-proxy-minion
    """
    ret = LazyLoader(
        _module_dirs(opts, "proxy"),
        opts,
        tag="proxy",
        pack={"__salt__": functions, "__ret__": returners, "__utils__": utils},
    )

    ret.pack["__proxy__"] = ret

    return ret
# Buggy code
def utils(opts, whitelist=None, context=None):
    """
    Returns the utility modules
    """
    return LazyLoader(
        _module_dirs(opts, "utils", ext_type_dirs="utils_dirs"),
        opts,
        tag="utils",
        whitelist=whitelist,
        pack={"__context__": context},
    )


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def utils(opts, whitelist=None, context=None, proxy=proxy):
    """
    Returns the utility modules
    """
    return LazyLoader(
        _module_dirs(opts, "utils", ext_type_dirs="utils_dirs"),
        opts,
        tag="utils",
        whitelist=whitelist,
        pack={"__context__": context, "__proxy__": proxy or {}},
    )
# Buggy code
def beacons(opts, functions, context=None):
    """
    Load the beacon modules

    :param dict opts: The Salt options dictionary
    :param dict functions: A dictionary of minion modules, with module names as
                            keys and funcs as values.
    """
    return LazyLoader(
        _module_dirs(opts, "beacons"),
        opts,
        tag="beacons",
        pack={"__context__": context, "__salt__": functions},
        virtual_funcs=["__validate__"],
    )


# Traceback (KeyError)
Invoking the same function in state files

$ salt cluster state.show_highstate
cluster:
- Rendering SLS 'base:esxcluster' failed: Jinja error: 'esxcluster.get_details'
Traceback (most recent call last):
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/templates.py", line 368, in render_jinja_tmpl
output = template.render(**decoded_context)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File ".../jinja2/2.7.3-py27/lib/Jinja2-2.7.3-py2.7.egg/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 29, in top-level template code
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 262, in __supports_proxies
return fn(*args, **clean_kwargs(**kwargs))
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 295, in _gets_service_instance_via_proxy
connection_details = _get_proxy_connection_details()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/vsphere.py", line 233, in _get_proxy_connection_details
details = __salt__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/modules/esxcluster.py", line 29, in get_details
return __proxy__['esxcluster.get_details']()
File "/var/tmp/bleotu/virtual/saltstack/install/common/lib/salt/utils/context.py", line 191, in __getitem__
return self._dict()[key]
KeyError: 'esxcluster.get_details'

; line 29

---
[...]
esxcluster.cluster_configured:
- {{ cluster_config }}
{%- endif %}

{%- if esxcluster_states_enabled.get('cluster_vsan_datastore') %}
{%- if pillar.get('vsan', {}).get('datastore_name') and     <======================
**salt['vsphere.get_cluster_vsan_data']()**.get('datastore_name') %}
cluster_vsan_datastore:
esxcluster.vsan_datastore_configured:
- datastore_name : {{ pillar['vsan']['datastore_name'] }}
{%- endif %}
[...]
---

# Fixed code
def beacons(opts, functions, context=None, proxy=None):
    """
    Load the beacon modules

    :param dict opts: The Salt options dictionary
    :param dict functions: A dictionary of minion modules, with module names as
                            keys and funcs as values.
    """
    return LazyLoader(
        _module_dirs(opts, "beacons"),
        opts,
        tag="beacons",
        virtual_funcs=["__validate__"],
        pack={"__context__": context, "__salt__": functions, "__proxy__": proxy or {}},
    )
# Buggy code
def beacon(config):
    """
    Scan for processes and fire events

    Example Config

    .. code-block:: yaml

        beacons:
          ps:
            salt-master: running
            mysql: stopped

    The config above sets up beacons to check that
    processes are running or stopped.
    """
    ret = []
    procs = []
    for proc in psutil.process_iter():
        _name = proc.name()
        if _name not in procs:
            procs.append(_name)

    for process in config:
        ret_dict = {}
        if config[process] == "running":
            if process not in procs:
                ret_dict[process] = "Stopped"
                ret.append(ret_dict)
        elif config[process] == "stopped":
            if process in procs:
                ret_dict[process] = "Running"
                ret.append(ret_dict)
        else:
            if process not in procs:
                ret_dict[process] = False
                ret.append(ret_dict)
    return ret


# Traceback (KeyError)
2016-12-07 10:33:33,391 [salt.minion      ][CRITICAL][22470] The beacon errored:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 2153, in handle_beacons
beacons = self.process_beacons(self.functions)
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 409, in process_beacons
return self.beacons.process(b_conf, self.opts['grains'])  # pylint: disable=no-member
File "/usr/lib/python2.7/dist-packages/salt/beacons/__init__.py", line 103, in process
raw = self.beacons[fun_str](b_config[mod])
File "/usr/lib/python2.7/dist-packages/salt/beacons/status.py", line 121, in beacon
data = __salt__['status.{0}'.format(func)]()
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1086, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/dist-packages/salt/utils/lazy.py", line 101, in __getitem__
raise KeyError(key)
KeyError: "status.{'time': ['all']}"

# Fixed code
def beacon(config):
    """
    Scan for processes and fire events

    Example Config

    .. code-block:: yaml

        beacons:
          ps:
            salt-master: running
            mysql: stopped

    The config above sets up beacons to check that
    processes are running or stopped.
    """
    ret = []
    procs = []
    for proc in psutil.process_iter():
        _name = proc.name()
        if _name not in procs:
            procs.append(_name)

    for entry in config:
        for process in entry:
            ret_dict = {}
            if entry[process] == "running":
                if process not in procs:
                    ret_dict[process] = "Stopped"
                    ret.append(ret_dict)
            elif entry[process] == "stopped":
                if process in procs:
                    ret_dict[process] = "Running"
                    ret.append(ret_dict)
            else:
                if process not in procs:
                    ret_dict[process] = False
                    ret.append(ret_dict)
    return ret
# Buggy code
def namespaced_function(function, global_dict, defaults=None, preserve_context=False):
    """
    Redefine (clone) a function under a different globals() namespace scope

        preserve_context:
            Allow to keep the context taken from orignal namespace,
            and extend it with globals() taken from
            new targetted namespace.
    """
    if defaults is None:
        defaults = function.__defaults__

    if preserve_context:
        _global_dict = function.__globals__.copy()
        _global_dict.update(global_dict)
        global_dict = _global_dict
    new_namespaced_function = types.FunctionType(
        function.__code__, global_dict, name=function.__name__, argdefs=defaults
    )
    new_namespaced_function.__dict__.update(function.__dict__)
    return new_namespaced_function


# Traceback (KeyError)
2016-12-07 10:33:33,391 [salt.minion      ][CRITICAL][22470] The beacon errored:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 2153, in handle_beacons
beacons = self.process_beacons(self.functions)
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 409, in process_beacons
return self.beacons.process(b_conf, self.opts['grains'])  # pylint: disable=no-member
File "/usr/lib/python2.7/dist-packages/salt/beacons/__init__.py", line 103, in process
raw = self.beacons[fun_str](b_config[mod])
File "/usr/lib/python2.7/dist-packages/salt/beacons/status.py", line 121, in beacon
data = __salt__['status.{0}'.format(func)]()
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1086, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/dist-packages/salt/utils/lazy.py", line 101, in __getitem__
raise KeyError(key)
KeyError: "status.{'time': ['all']}"

# Fixed code
def namespaced_function(function, global_dict, defaults=None, preserve_context=False):
    """
    Redefine (clone) a function under a different globals() namespace scope

        preserve_context:
            Allow to keep the context taken from orignal namespace,
            and extend it with globals() taken from
            new targetted namespace.
    """
    if defaults is None:
        defaults = function.__defaults__

    if preserve_context:
        _global_dict = function.__globals__.copy()
        _global_dict.update(global_dict)
        global_dict = _global_dict
    new_namespaced_function = types.FunctionType(
        function.__code__,
        global_dict,
        name=function.__name__,
        argdefs=defaults,
        closure=function.__closure__,
    )
    new_namespaced_function.__dict__.update(function.__dict__)
    return new_namespaced_function
# Buggy code
def uri_to_resource(resource_file):
    ### Returns the URI for a resource
    # The basic case is that the resource is on saltstack.com
    # It could be the case that the resource is cached.
    salt_uri = "https://repo.saltstack.com/windows/dependencies/" + resource_file
    if os.getenv("SALTREPO_LOCAL_CACHE") == None:
        # if environment variable not set, return the basic case
        return salt_uri
    if not os.path.isdir(os.getenv("SALTREPO_LOCAL_CACHE")):
        # if environment variable is not a directory, return the basic case
        return salt_uri
    cached_resource = os.path.join(os.getenv("SALTREPO_LOCAL_CACHE"), resource_file)
    cached_resource = cached_resource.replace("/", "\\")
    if not os.path.isfile(cached_resource):
        # if file does not exist, return the basic case
        return salt_uri
    if os.path.getsize(cached_resource) == 0:
        # if file has zero size, return the basic case
        return salt_uri
    return cached_resource


# Traceback (KeyError)
2016-12-07 10:33:33,391 [salt.minion      ][CRITICAL][22470] The beacon errored:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 2153, in handle_beacons
beacons = self.process_beacons(self.functions)
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 409, in process_beacons
return self.beacons.process(b_conf, self.opts['grains'])  # pylint: disable=no-member
File "/usr/lib/python2.7/dist-packages/salt/beacons/__init__.py", line 103, in process
raw = self.beacons[fun_str](b_config[mod])
File "/usr/lib/python2.7/dist-packages/salt/beacons/status.py", line 121, in beacon
data = __salt__['status.{0}'.format(func)]()
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1086, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/dist-packages/salt/utils/lazy.py", line 101, in __getitem__
raise KeyError(key)
KeyError: "status.{'time': ['all']}"

# Fixed code
def uri_to_resource(resource_file):
    # ## Returns the URI for a resource
    # The basic case is that the resource is on saltstack.com
    # It could be the case that the resource is cached.
    salt_uri = "https://repo.saltstack.com/windows/dependencies/" + resource_file
    if os.getenv("SALTREPO_LOCAL_CACHE") is None:
        # if environment variable not set, return the basic case
        return salt_uri
    if not os.path.isdir(os.getenv("SALTREPO_LOCAL_CACHE")):
        # if environment variable is not a directory, return the basic case
        return salt_uri
    cached_resource = os.path.join(os.getenv("SALTREPO_LOCAL_CACHE"), resource_file)
    cached_resource = cached_resource.replace("/", "\\")
    if not os.path.isfile(cached_resource):
        # if file does not exist, return the basic case
        return salt_uri
    if os.path.getsize(cached_resource) == 0:
        # if file has zero size, return the basic case
        return salt_uri
    return cached_resource
# Buggy code
def finalize_options(self):
    Sdist.finalize_options(self)
    if "SKIP_BOOTSTRAP_DOWNLOAD" in os.environ:
        log(
            "Please stop using 'SKIP_BOOTSTRAP_DOWNLOAD' and use "
            "'DOWNLOAD_BOOTSTRAP_SCRIPT' instead"
        )

    if "DOWNLOAD_BOOTSTRAP_SCRIPT" in os.environ:
        download_bootstrap_script = os.environ.get("DOWNLOAD_BOOTSTRAP_SCRIPT", "0")
        self.download_bootstrap_script = download_bootstrap_script == "1"


# Traceback (KeyError)
2016-12-07 10:33:33,391 [salt.minion      ][CRITICAL][22470] The beacon errored:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 2153, in handle_beacons
beacons = self.process_beacons(self.functions)
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 409, in process_beacons
return self.beacons.process(b_conf, self.opts['grains'])  # pylint: disable=no-member
File "/usr/lib/python2.7/dist-packages/salt/beacons/__init__.py", line 103, in process
raw = self.beacons[fun_str](b_config[mod])
File "/usr/lib/python2.7/dist-packages/salt/beacons/status.py", line 121, in beacon
data = __salt__['status.{0}'.format(func)]()
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1086, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/dist-packages/salt/utils/lazy.py", line 101, in __getitem__
raise KeyError(key)
KeyError: "status.{'time': ['all']}"

# Fixed code
def finalize_options(self):
    Sdist.finalize_options(self)
    if "SKIP_BOOTSTRAP_DOWNLOAD" in os.environ:
        log(
            "Please stop using 'SKIP_BOOTSTRAP_DOWNLOAD' and use "  # pylint: disable=not-callable
            "'DOWNLOAD_BOOTSTRAP_SCRIPT' instead"
        )

    if "DOWNLOAD_BOOTSTRAP_SCRIPT" in os.environ:
        download_bootstrap_script = os.environ.get("DOWNLOAD_BOOTSTRAP_SCRIPT", "0")
        self.download_bootstrap_script = download_bootstrap_script == "1"
# Buggy code
def queue_instances(instances):
    """
    Queue a set of instances to be provisioned later. Expects a list.

    Currently this only queries node data, and then places it in the cloud
    cache (if configured). If the salt-cloud-reactor is being used, these
    instances will be automatically provisioned using that.

    For more information about the salt-cloud-reactor, see:

    https://github.com/saltstack-formulas/salt-cloud-reactor
    """
    for instance_id in instances:
        node = _get_node(instance_id=instance_id)
        for name in node:
            if instance_id == node[name]["instanceId"]:
                __utils__["cloud.cache_node"](
                    node[name], __active_provider_name__, __opts__
                )


# Traceback (TypeError)
(py2-env) salt-test@tommynaut:~> salt-cloud -l debug -y -a show_instance foo1
...
[ERROR   ] There was an error actioning machines: 'NoneType' object has no attribute '__getitem__'
Traceback (most recent call last):
File "/home/salt-test/salt/salt/cloud/cli.py", line 252, in run
ret = mapper.do_action(names, kwargs)
File "/home/salt-test/salt/salt/cloud/__init__.py", line 1527, in do_action
vm_name, call='action'
File "/home/salt-test/salt/salt/cloud/clouds/ec2.py", line 3206, in show_instance
__opts__)
File "/home/salt-test/salt/salt/utils/cloud.py", line 2919, in cache_node
path = os.path.join(prov_dir, '{0}.p'.format(node['name']))
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def queue_instances(instances):
    """
    Queue a set of instances to be provisioned later. Expects a list.

    Currently this only queries node data, and then places it in the cloud
    cache (if configured). If the salt-cloud-reactor is being used, these
    instances will be automatically provisioned using that.

    For more information about the salt-cloud-reactor, see:

    https://github.com/saltstack-formulas/salt-cloud-reactor
    """
    for instance_id in instances:
        node = _get_node(instance_id=instance_id)
        __utils__["cloud.cache_node"](node, __active_provider_name__, __opts__)
# Buggy code
def show_instance(name=None, instance_id=None, call=None, kwargs=None):
    """
    Show the details from EC2 concerning an AMI.

    Can be called as an action (which requires a name):

    .. code-block:: bash

        salt-cloud -a show_instance myinstance

    ...or as a function (which requires either a name or instance_id):

    .. code-block:: bash

        salt-cloud -f show_instance my-ec2 name=myinstance
        salt-cloud -f show_instance my-ec2 instance_id=i-d34db33f
    """
    if not name and call == "action":
        raise SaltCloudSystemExit("The show_instance action requires a name.")

    if call == "function":
        name = kwargs.get("name", None)
        instance_id = kwargs.get("instance_id", None)

    if not name and not instance_id:
        raise SaltCloudSystemExit(
            "The show_instance function requires either a name or an instance_id"
        )

    node = _get_node(name=name, instance_id=instance_id)
    for name in node:
        __utils__["cloud.cache_node"](node[name], __active_provider_name__, __opts__)
    return node


# Traceback (TypeError)
(py2-env) salt-test@tommynaut:~> salt-cloud -l debug -y -a show_instance foo1
...
[ERROR   ] There was an error actioning machines: 'NoneType' object has no attribute '__getitem__'
Traceback (most recent call last):
File "/home/salt-test/salt/salt/cloud/cli.py", line 252, in run
ret = mapper.do_action(names, kwargs)
File "/home/salt-test/salt/salt/cloud/__init__.py", line 1527, in do_action
vm_name, call='action'
File "/home/salt-test/salt/salt/cloud/clouds/ec2.py", line 3206, in show_instance
__opts__)
File "/home/salt-test/salt/salt/utils/cloud.py", line 2919, in cache_node
path = os.path.join(prov_dir, '{0}.p'.format(node['name']))
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def show_instance(name=None, instance_id=None, call=None, kwargs=None):
    """
    Show the details from EC2 concerning an AMI.

    Can be called as an action (which requires a name):

    .. code-block:: bash

        salt-cloud -a show_instance myinstance

    ...or as a function (which requires either a name or instance_id):

    .. code-block:: bash

        salt-cloud -f show_instance my-ec2 name=myinstance
        salt-cloud -f show_instance my-ec2 instance_id=i-d34db33f
    """
    if not name and call == "action":
        raise SaltCloudSystemExit("The show_instance action requires a name.")

    if call == "function":
        name = kwargs.get("name", None)
        instance_id = kwargs.get("instance_id", None)

    if not name and not instance_id:
        raise SaltCloudSystemExit(
            "The show_instance function requires either a name or an instance_id"
        )

    node = _get_node(name=name, instance_id=instance_id)
    __utils__["cloud.cache_node"](node, __active_provider_name__, __opts__)
    return node
# Buggy code
def _check_vlan():
    tag = __salt__["openvswitch.port_get_tag"](name)
    interfaces = __salt__["network.interfaces"]()
    if not 0 <= id <= 4095:
        ret["result"] = False
        ret["comment"] = comment_vlan_invalid_id
    elif not internal and name not in interfaces:
        ret["result"] = False
        ret["comment"] = comment_vlan_invalid_name
    elif tag and name in port_list:
        try:
            if int(tag[0]) == id:
                ret["result"] = True
                ret["comment"] = comment_vlan_port_exists
        except (ValueError, KeyError):
            pass


# Traceback (TypeError)
----------
ID: ovs-tun-gre
Function: openvswitch_port.present
Name: ovs-tun-gre
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/var/tmp/.root_e78424_salt/py3/salt/state.py", line 1744, in call
**cdata['kwargs'])
File "/var/tmp/.root_e78424_salt/py3/salt/loader.py", line 1702, in wrapper
return f(*args, **kwargs)
File "/var/tmp/.root_e78424_salt/py3/salt/states/openvswitch_port.py", line 75, in present
comment_dstport = ' (dst_port' + str(dst_port) + ')' if 0 < dst_port <= 65535 else ''
TypeError: '<' not supported between instances of 'int' and 'NoneType'
Started: 18:26:22.079644
Duration: 29.143 ms
Changes:

# Fixed code
def _check_vlan():
    tag = __salt__["openvswitch.port_get_tag"](name)
    interfaces = __salt__["network.interfaces"]()
    if not 0 <= id <= 4095:
        ret["result"] = False
        ret["comment"] = comments["comment_vlan_invalid_id"]
    elif not internal and name not in interfaces:
        ret["result"] = False
        ret["comment"] = comments["comment_vlan_invalid_name"]
    elif tag and name in port_list:
        try:
            if int(tag[0]) == id:
                ret["result"] = True
                ret["comment"] = comments["comment_vlan_port_exists"]
        except (ValueError, KeyError):
            pass
# Buggy code
def _check_gre():
    interface_options = __salt__["openvswitch.interface_get_options"](name)
    interface_type = __salt__["openvswitch.interface_get_type"](name)
    if not 0 <= id <= 2**32:
        ret["result"] = False
        ret["comment"] = comment_gre_invalid_id
    elif not __salt__["dig.check_ip"](remote):
        ret["result"] = False
        ret["comment"] = comment_invalid_ip
    elif interface_options and interface_type and name in port_list:
        interface_attroptions = (
            '{key="' + str(id) + '", remote_ip="' + str(remote) + '"}'
        )
        try:
            if (
                interface_type[0] == "gre"
                and interface_options[0] == interface_attroptions
            ):
                ret["result"] = True
                ret["comment"] = comment_gre_interface_exists
        except KeyError:
            pass


# Traceback (TypeError)
----------
ID: ovs-tun-gre
Function: openvswitch_port.present
Name: ovs-tun-gre
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/var/tmp/.root_e78424_salt/py3/salt/state.py", line 1744, in call
**cdata['kwargs'])
File "/var/tmp/.root_e78424_salt/py3/salt/loader.py", line 1702, in wrapper
return f(*args, **kwargs)
File "/var/tmp/.root_e78424_salt/py3/salt/states/openvswitch_port.py", line 75, in present
comment_dstport = ' (dst_port' + str(dst_port) + ')' if 0 < dst_port <= 65535 else ''
TypeError: '<' not supported between instances of 'int' and 'NoneType'
Started: 18:26:22.079644
Duration: 29.143 ms
Changes:

# Fixed code
def _check_gre():
    interface_options = __salt__["openvswitch.interface_get_options"](name)
    interface_type = __salt__["openvswitch.interface_get_type"](name)
    if not 0 <= id <= 2**32:
        ret["result"] = False
        ret["comment"] = comments["comment_gre_invalid_id"]
    elif not __salt__["dig.check_ip"](remote):
        ret["result"] = False
        ret["comment"] = comments["comment_invalid_ip"]
    elif interface_options and interface_type and name in port_list:
        interface_attroptions = (
            '{key="' + str(id) + '", remote_ip="' + str(remote) + '"}'
        )
        try:
            if (
                interface_type[0] == "gre"
                and interface_options[0] == interface_attroptions
            ):
                ret["result"] = True
                ret["comment"] = comments["comment_gre_interface_exists"]
        except KeyError:
            pass
# Buggy code
def _check_vxlan():
    interface_options = __salt__["openvswitch.interface_get_options"](name)
    interface_type = __salt__["openvswitch.interface_get_type"](name)
    if not 0 <= id <= 2**64:
        ret["result"] = False
        ret["comment"] = comment_vxlan_invalid_id
    elif not __salt__["dig.check_ip"](remote):
        ret["result"] = False
        ret["comment"] = comment_invalid_ip
    elif interface_options and interface_type and name in port_list:
        opt_port = 'dst_port="' + str(dst_port) + '", ' if 0 < dst_port <= 65535 else ""
        interface_attroptions = (
            '{{{0}key="'.format(opt_port)
            + str(id)
            + '", remote_ip="'
            + str(remote)
            + '"}'
        )
        try:
            if (
                interface_type[0] == "vxlan"
                and interface_options[0] == interface_attroptions
            ):
                ret["result"] = True
                ret["comment"] = comment_vxlan_interface_exists
        except KeyError:
            pass


# Traceback (TypeError)
----------
ID: ovs-tun-gre
Function: openvswitch_port.present
Name: ovs-tun-gre
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/var/tmp/.root_e78424_salt/py3/salt/state.py", line 1744, in call
**cdata['kwargs'])
File "/var/tmp/.root_e78424_salt/py3/salt/loader.py", line 1702, in wrapper
return f(*args, **kwargs)
File "/var/tmp/.root_e78424_salt/py3/salt/states/openvswitch_port.py", line 75, in present
comment_dstport = ' (dst_port' + str(dst_port) + ')' if 0 < dst_port <= 65535 else ''
TypeError: '<' not supported between instances of 'int' and 'NoneType'
Started: 18:26:22.079644
Duration: 29.143 ms
Changes:

# Fixed code
def _check_vxlan():
    interface_options = __salt__["openvswitch.interface_get_options"](name)
    interface_type = __salt__["openvswitch.interface_get_type"](name)
    if not 0 <= id <= 2**64:
        ret["result"] = False
        ret["comment"] = comments["comment_vxlan_invalid_id"]
    elif not __salt__["dig.check_ip"](remote):
        ret["result"] = False
        ret["comment"] = comments["comment_invalid_ip"]
    elif interface_options and interface_type and name in port_list:
        opt_port = 'dst_port="' + str(dst_port) + '", ' if 0 < dst_port <= 65535 else ""
        interface_attroptions = (
            '{{{0}key="'.format(opt_port)
            + str(id)
            + '", remote_ip="'
            + str(remote)
            + '"}'
        )
        try:
            if (
                interface_type[0] == "vxlan"
                and interface_options[0] == interface_attroptions
            ):
                ret["result"] = True
                ret["comment"] = comments["comment_vxlan_interface_exists"]
        except KeyError:
            pass
# Buggy code
def get_pillar(
    opts,
    grains,
    minion_id,
    saltenv=None,
    ext=None,
    funcs=None,
    pillar=None,
    pillarenv=None,
    rend=None,
):
    """
    Return the correct pillar driver based on the file_client option
    """
    ptype = {"remote": RemotePillar, "local": Pillar}.get(opts["file_client"], Pillar)
    # If local pillar and we're caching, run through the cache system first
    log.debug("Determining pillar cache")
    if opts["pillar_cache"]:
        log.info("Compiling pillar from cache")
        log.debug("get_pillar using pillar cache with ext: {0}".format(ext))
        return PillarCache(
            opts,
            grains,
            minion_id,
            saltenv,
            ext=ext,
            functions=funcs,
            pillar=pillar,
            pillarenv=pillarenv,
        )
    return ptype(
        opts,
        grains,
        minion_id,
        saltenv,
        ext,
        functions=funcs,
        pillar=pillar,
        pillarenv=pillarenv,
        rend=rend,
    )


# Traceback (TypeError)
2017-01-06 14:37:22,558 [salt.pillar      ][CRITICAL][10803] Rendering SLS 'servers.qa' failed, render error:
Jinja error: unsupported operand type(s) for +: 'NoneType' and 'str'
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 379, in render_jinja_tmpl
    output = template.render(**decoded_context)
  File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 989, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 754, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<template>", line 8, in top-level template code
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

; line 8

---
[...]
postgres:
  host: {{ grains.get('role') + 'database.example.com' }}    <======================
[...]
---

# Fixed code
def get_pillar(
    opts,
    grains,
    minion_id,
    saltenv=None,
    ext=None,
    funcs=None,
    pillar=None,
    pillarenv=None,
):
    """
    Return the correct pillar driver based on the file_client option
    """
    ptype = {"remote": RemotePillar, "local": Pillar}.get(opts["file_client"], Pillar)
    # If local pillar and we're caching, run through the cache system first
    log.debug("Determining pillar cache")
    if opts["pillar_cache"]:
        log.info("Compiling pillar from cache")
        log.debug("get_pillar using pillar cache with ext: {0}".format(ext))
        return PillarCache(
            opts,
            grains,
            minion_id,
            saltenv,
            ext=ext,
            functions=funcs,
            pillar=pillar,
            pillarenv=pillarenv,
        )
    return ptype(
        opts,
        grains,
        minion_id,
        saltenv,
        ext,
        functions=funcs,
        pillar=pillar,
        pillarenv=pillarenv,
    )
# Buggy code
def __init__(
    self,
    opts,
    grains,
    minion_id,
    saltenv,
    ext=None,
    functions=None,
    pillar=None,
    pillarenv=None,
    *args,
    **kwargs,
):
    self.opts = opts
    self.opts["environment"] = saltenv
    self.ext = ext
    self.grains = grains
    self.minion_id = minion_id
    self.channel = salt.transport.Channel.factory(opts)
    if pillarenv is not None:
        self.opts["pillarenv"] = pillarenv
    elif self.opts.get("pillarenv_from_saltenv", False):
        self.opts["pillarenv"] = saltenv
    elif "pillarenv" not in self.opts:
        self.opts["pillarenv"] = None
    self.pillar_override = {}
    if pillar is not None:
        if isinstance(pillar, dict):
            self.pillar_override = pillar
        else:
            log.error("Pillar data must be a dictionary")


# Traceback (TypeError)
2017-01-06 14:37:22,558 [salt.pillar      ][CRITICAL][10803] Rendering SLS 'servers.qa' failed, render error:
Jinja error: unsupported operand type(s) for +: 'NoneType' and 'str'
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 379, in render_jinja_tmpl
    output = template.render(**decoded_context)
  File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 989, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 754, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<template>", line 8, in top-level template code
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

; line 8

---
[...]
postgres:
  host: {{ grains.get('role') + 'database.example.com' }}    <======================
[...]
---

# Fixed code
def __init__(
    self,
    opts,
    grains,
    minion_id,
    saltenv,
    ext=None,
    functions=None,
    pillar=None,
    pillarenv=None,
):
    self.opts = opts
    self.opts["environment"] = saltenv
    self.ext = ext
    self.grains = grains
    self.minion_id = minion_id
    self.channel = salt.transport.Channel.factory(opts)
    if pillarenv is not None:
        self.opts["pillarenv"] = pillarenv
    elif self.opts.get("pillarenv_from_saltenv", False):
        self.opts["pillarenv"] = saltenv
    elif "pillarenv" not in self.opts:
        self.opts["pillarenv"] = None
    self.pillar_override = {}
    if pillar is not None:
        if isinstance(pillar, dict):
            self.pillar_override = pillar
        else:
            log.error("Pillar data must be a dictionary")
# Buggy code
def _changes(name, admin):
    """
    Get necessary changes to given user account
    """

    existing_user = __salt__["influxdb.user_info"](name)
    changes = {}

    if existing_user["admin"] != admin:
        changes["admin"] = admin

    return changes


# Traceback (ConnectionError)
----------
ID: sensu_influxdb
Function: influxdb_user.present
Name: sensu
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1744, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1702, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/influxdb_user.py", line 72, in present
changes = _changes(name, admin)
File "/usr/lib/python2.7/dist-packages/salt/states/influxdb_user.py", line 24, in _changes
existing_user = __salt__['influxdb.user_info'](name)
File "/usr/lib/python2.7/dist-packages/salt/modules/influx.py", line 198, in user_info
matching_users = (user for user in list_users(**client_args)
File "/usr/lib/python2.7/dist-packages/salt/modules/influx.py", line 163, in list_users
return client.get_list_users()
File "/usr/lib/python2.7/dist-packages/influxdb/client.py", line 633, in get_list_users
return list(self.query("SHOW USERS").get_points())
File "/usr/lib/python2.7/dist-packages/influxdb/client.py", line 325, in query
expected_response_code=expected_response_code
File "/usr/lib/python2.7/dist-packages/influxdb/client.py", line 241, in request
raise e
ConnectionError: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?q=SHOW+USERS (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7f45d18b8350>: Failed to establish a new connection: [Errno 111] Connection refused',))
Started: 14:10:02.779676
Duration: 9098882.04 ms
Changes:
----------

# Fixed code
def _changes(name, admin, **client_args):
    """
    Get necessary changes to given user account
    """

    existing_user = __salt__["influxdb.user_info"](name, **client_args)
    changes = {}

    if existing_user["admin"] != admin:
        changes["admin"] = admin

    return changes