gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __virtual__():
    """
    Only work on proxy
    """
    if salt.utils.is_proxy():
        return __virtualname__
    return (
        False,
        "The rest_package execution module failed to load: only available on proxy minions.",
    )


# Traceback (KeyError)
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1210, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/ssh_package.py", line 31, in list_pkgs
return __proxy__['ssh_sample.package_list']()
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1010, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'ssh_sample.package_list'

# Fixed code
def __virtual__():
    """
    Only work on systems that are a proxy minion
    """
    try:
        if salt.utils.is_proxy() and __opts__["proxy"]["proxytype"] == "rest_sample":
            return __virtualname__
    except KeyError:
        return (
            False,
            "The rest_package execution module failed to load.  Check the proxy key in pillar.",
        )

    return (
        False,
        "The rest_package execution module failed to load: only works on a rest_sample proxy minion.",
    )
# Buggy code
def __virtual__():
    """
    Only work on systems that are a proxy minion
    """
    if __grains__["os"] == "proxy":
        return __virtualname__
    return (
        False,
        "The rest_service execution module failed to load: only available on proxy minions.",
    )


# Traceback (KeyError)
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1210, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/ssh_package.py", line 31, in list_pkgs
return __proxy__['ssh_sample.package_list']()
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1010, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'ssh_sample.package_list'

# Fixed code
def __virtual__():
    """
    Only work on systems that are a proxy minion
    """
    try:
        if salt.utils.is_proxy() and __opts__["proxy"]["proxytype"] == "rest_sample":
            return __virtualname__
    except KeyError:
        return (
            False,
            "The rest_service execution module failed to load.  Check the proxy key in pillar.",
        )

    return (
        False,
        "The rest_service execution module failed to load: only works on a rest_sample proxy minion.",
    )
# Buggy code
def __virtual__():
    """
    Only work on proxy
    """
    if salt.utils.is_proxy():
        return __virtualname__
    return (
        False,
        "THe ssh_service execution module failed to load: only works on a proxy minion.",
    )


# Traceback (KeyError)
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1210, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/ssh_package.py", line 31, in list_pkgs
return __proxy__['ssh_sample.package_list']()
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1010, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'ssh_sample.package_list'

# Fixed code
def __virtual__():
    """
    Only work on proxy
    """
    try:
        if salt.utils.is_proxy() and __opts__["proxy"]["proxytype"] == "ssh_sample":
            return __virtualname__
    except KeyError:
        return (
            False,
            "The ssh_package execution module failed to load.  Check the proxy key in pillar.",
        )

    return (
        False,
        "The ssh_package execution module failed to load: only works on an ssh_sample proxy minion.",
    )
# Buggy code
def __virtual__():
    """
    Only work on systems that are a proxy minion
    """
    if __grains__["os"] == "proxy":
        return __virtualname__
    return (
        False,
        "ssh_service module cannot be loaded: only available on proxy minions.",
    )


# Traceback (KeyError)
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1210, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/ssh_package.py", line 31, in list_pkgs
return __proxy__['ssh_sample.package_list']()
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1010, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'ssh_sample.package_list'

# Fixed code
def __virtual__():
    """
    Only work on systems that are a proxy minion
    """
    try:
        if salt.utils.is_proxy() and __opts__["proxy"]["proxytype"] == "ssh_sample":
            return __virtualname__
    except KeyError:
        return (
            False,
            "The ssh_service execution module failed to load.  Check the proxy key in pillar.",
        )

    return (
        False,
        "The ssh_service execution module failed to load: only works on an ssh_sample proxy minion.",
    )
# Buggy code
def init(opts):
    """
    Required.
    Can be used to initialize the server connection.
    """
    try:
        DETAILS["server"] = SSHConnection(
            host=__opts__["proxy"]["host"],
            username=__opts__["proxy"]["username"],
            password=__opts__["proxy"]["password"],
        )
        out, err = DETAILS["server"].sendline("help")
        log.debug(out)

    except TerminalException as e:
        log.error(e)
        return False


# Traceback (KeyError)
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1210, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/ssh_package.py", line 31, in list_pkgs
return __proxy__['ssh_sample.package_list']()
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1010, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'ssh_sample.package_list'

# Fixed code
def init(opts):
    """
    Required.
    Can be used to initialize the server connection.
    """
    try:
        DETAILS["server"] = SSHConnection(
            host=__opts__["proxy"]["host"],
            username=__opts__["proxy"]["username"],
            password=__opts__["proxy"]["password"],
        )
        out, err = DETAILS["server"].sendline("help")

    except TerminalException as e:
        log.error(e)
        return False
# Buggy code
def package_install(name, **kwargs):
    """
    Install a "package" on the REST server
    """
    cmd = DETAILS["url"] + "package/install/" + name
    if "version" in kwargs:
        cmd += "/" + kwargs["version"]
    else:
        cmd += "/1.0"
    r = salt.utils.http.query(cmd, decode_type="json", decode=True)
    return r["dict"]


# Traceback (KeyError)
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1210, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/ssh_package.py", line 31, in list_pkgs
return __proxy__['ssh_sample.package_list']()
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1010, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'ssh_sample.package_list'

# Fixed code
def package_install(name, **kwargs):
    """
    Install a "package" on the REST server
    """
    cmd = DETAILS["url"] + "package/install/" + name
    if kwargs.get("version", False):
        cmd += "/" + kwargs["version"]
    else:
        cmd += "/1.0"
    r = salt.utils.http.query(cmd, decode_type="json", decode=True)
    return r["dict"]
# Buggy code
def package_list():
    """
    List "packages" by executing a command via ssh
    This function is called in response to the salt command

    ..code-block::bash
        salt target_minion pkg.list_pkgs

    """
    # Send the command to execute
    out, err = DETAILS["server"].sendline("pkg_list")

    # "scrape" the output and return the right fields as a dict
    return parse(out)


# Traceback (KeyError)
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1210, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/ssh_package.py", line 31, in list_pkgs
return __proxy__['ssh_sample.package_list']()
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1010, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'ssh_sample.package_list'

# Fixed code
def package_list():
    """
    List "packages" by executing a command via ssh
    This function is called in response to the salt command

    ..code-block::bash
        salt target_minion pkg.list_pkgs

    """
    # Send the command to execute
    out, err = DETAILS["server"].sendline("pkg_list\n")

    # "scrape" the output and return the right fields as a dict
    return parse(out)
# Buggy code
def package_install(name, **kwargs):
    """
    Install a "package" on the ssh server
    """
    cmd = "pkg_install " + name
    if "version" in kwargs:
        cmd += " " + kwargs["version"]

    # Send the command to execute
    out, err = DETAILS["server"].sendline(cmd)

    # "scrape" the output and return the right fields as a dict
    return parse(out)


# Traceback (KeyError)
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1210, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/ssh_package.py", line 31, in list_pkgs
return __proxy__['ssh_sample.package_list']()
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1010, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'ssh_sample.package_list'

# Fixed code
def package_install(name, **kwargs):
    """
    Install a "package" on the ssh server
    """
    cmd = "pkg_install " + name
    if kwargs.get("version", False):
        cmd += " " + kwargs["version"]

    # Send the command to execute
    out, err = DETAILS["server"].sendline(cmd)

    # "scrape" the output and return the right fields as a dict
    return parse(out)
# Buggy code
def _finger_fail(self, finger, master_key):
    log.critical(
        "The specified fingerprint in the master configuration "
        "file:\n{0}\nDoes not match the authenticating master's "
        "key:\n{1}\nVerify that the configured fingerprint "
        "matches the fingerprint of the correct master and that "
        "this minion is not subject to a man-in-the-middle attack.".format(
            finger, salt.utils.pem_finger(master_key)
        )
    )
    sys.exit(42)


# Traceback (ValueError)
/var/log/salt/minion:

2015-11-03 00:04:24,744 [salt.scripts                             ][ERROR   ][2411] Minion failed to start:
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/scripts.py", line 81, in minion_process
minion.start()
File "/usr/lib/python2.6/site-packages/salt/cli/daemons.py", line 275, in start
self.minion.tune_in()
File "/usr/lib/python2.6/site-packages/salt/minion.py", line 1628, in tune_in
io_loop=self.io_loop,
File "/usr/lib/python2.6/site-packages/salt/utils/event.py", line 731, in __init__
id_hash = hash_type(salt.utils.to_bytes(self.opts.get('id', ''))).hexdigest()[:10]
ValueError: error:060800A3:digital envelope routines:EVP_DigestInit_ex:disabled for fips

# Fixed code
def _finger_fail(self, finger, master_key):
    log.critical(
        "The specified fingerprint in the master configuration "
        "file:\n{0}\nDoes not match the authenticating master's "
        "key:\n{1}\nVerify that the configured fingerprint "
        "matches the fingerprint of the correct master and that "
        "this minion is not subject to a man-in-the-middle attack.".format(
            finger, salt.utils.pem_finger(master_key, sum_type=self.opts["hash_type"])
        )
    )
    sys.exit(42)
# Buggy code
def finger(self, match):
    """
    Return the fingerprint for a specified key
    """
    matches = self.name_match(match, True)
    ret = {}
    for status, keys in six.iteritems(matches):
        ret[status] = {}
        for key in keys:
            if status == "local":
                path = os.path.join(self.opts["pki_dir"], key)
            else:
                path = os.path.join(self.opts["pki_dir"], status, key)
            ret[status][key] = salt.utils.pem_finger(path)
    return ret


# Traceback (ValueError)
/var/log/salt/minion:

2015-11-03 00:04:24,744 [salt.scripts                             ][ERROR   ][2411] Minion failed to start:
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/scripts.py", line 81, in minion_process
minion.start()
File "/usr/lib/python2.6/site-packages/salt/cli/daemons.py", line 275, in start
self.minion.tune_in()
File "/usr/lib/python2.6/site-packages/salt/minion.py", line 1628, in tune_in
io_loop=self.io_loop,
File "/usr/lib/python2.6/site-packages/salt/utils/event.py", line 731, in __init__
id_hash = hash_type(salt.utils.to_bytes(self.opts.get('id', ''))).hexdigest()[:10]
ValueError: error:060800A3:digital envelope routines:EVP_DigestInit_ex:disabled for fips

# Fixed code
def finger(self, match):
    """
    Return the fingerprint for a specified key
    """
    matches = self.name_match(match, True)
    ret = {}
    for status, keys in six.iteritems(matches):
        ret[status] = {}
        for key in keys:
            if status == "local":
                path = os.path.join(self.opts["pki_dir"], key)
            else:
                path = os.path.join(self.opts["pki_dir"], status, key)
            ret[status][key] = salt.utils.pem_finger(
                path, sum_type=self.opts["hash_type"]
            )
    return ret
# Buggy code
def finger_all(self):
    """
    Return fingerprins for all keys
    """
    ret = {}
    for status, keys in six.iteritems(self.list_keys()):
        ret[status] = {}
        for key in keys:
            if status == "local":
                path = os.path.join(self.opts["pki_dir"], key)
            else:
                path = os.path.join(self.opts["pki_dir"], status, key)
            ret[status][key] = salt.utils.pem_finger(path)
    return ret


# Traceback (ValueError)
/var/log/salt/minion:

2015-11-03 00:04:24,744 [salt.scripts                             ][ERROR   ][2411] Minion failed to start:
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/scripts.py", line 81, in minion_process
minion.start()
File "/usr/lib/python2.6/site-packages/salt/cli/daemons.py", line 275, in start
self.minion.tune_in()
File "/usr/lib/python2.6/site-packages/salt/minion.py", line 1628, in tune_in
io_loop=self.io_loop,
File "/usr/lib/python2.6/site-packages/salt/utils/event.py", line 731, in __init__
id_hash = hash_type(salt.utils.to_bytes(self.opts.get('id', ''))).hexdigest()[:10]
ValueError: error:060800A3:digital envelope routines:EVP_DigestInit_ex:disabled for fips

# Fixed code
def finger_all(self):
    """
    Return fingerprins for all keys
    """
    ret = {}
    for status, keys in six.iteritems(self.list_keys()):
        ret[status] = {}
        for key in keys:
            if status == "local":
                path = os.path.join(self.opts["pki_dir"], key)
            else:
                path = os.path.join(self.opts["pki_dir"], status, key)
            ret[status][key] = salt.utils.pem_finger(
                path, sum_type=self.opts["hash_type"]
            )
    return ret
# Buggy code
def finger():
    """
    Return the minion's public key fingerprint

    CLI Example:

    .. code-block:: bash

        salt '*' key.finger
    """
    return salt.utils.pem_finger(os.path.join(__opts__["pki_dir"], "minion.pub"))


# Traceback (ValueError)
/var/log/salt/minion:

2015-11-03 00:04:24,744 [salt.scripts                             ][ERROR   ][2411] Minion failed to start:
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/scripts.py", line 81, in minion_process
minion.start()
File "/usr/lib/python2.6/site-packages/salt/cli/daemons.py", line 275, in start
self.minion.tune_in()
File "/usr/lib/python2.6/site-packages/salt/minion.py", line 1628, in tune_in
io_loop=self.io_loop,
File "/usr/lib/python2.6/site-packages/salt/utils/event.py", line 731, in __init__
id_hash = hash_type(salt.utils.to_bytes(self.opts.get('id', ''))).hexdigest()[:10]
ValueError: error:060800A3:digital envelope routines:EVP_DigestInit_ex:disabled for fips

# Fixed code
def finger():
    """
    Return the minion's public key fingerprint

    CLI Example:

    .. code-block:: bash

        salt '*' key.finger
    """
    return salt.utils.pem_finger(
        os.path.join(__opts__["pki_dir"], "minion.pub"), sum_type=__opts__["hash_type"]
    )
# Buggy code
def finger_master():
    """
    Return the fingerprint of the master's public key on the minion.

    CLI Example:

    .. code-block:: bash

        salt '*' key.finger_master
    """
    return salt.utils.pem_finger(os.path.join(__opts__["pki_dir"], "minion_master.pub"))


# Traceback (ValueError)
/var/log/salt/minion:

2015-11-03 00:04:24,744 [salt.scripts                             ][ERROR   ][2411] Minion failed to start:
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/scripts.py", line 81, in minion_process
minion.start()
File "/usr/lib/python2.6/site-packages/salt/cli/daemons.py", line 275, in start
self.minion.tune_in()
File "/usr/lib/python2.6/site-packages/salt/minion.py", line 1628, in tune_in
io_loop=self.io_loop,
File "/usr/lib/python2.6/site-packages/salt/utils/event.py", line 731, in __init__
id_hash = hash_type(salt.utils.to_bytes(self.opts.get('id', ''))).hexdigest()[:10]
ValueError: error:060800A3:digital envelope routines:EVP_DigestInit_ex:disabled for fips

# Fixed code
def finger_master():
    """
    Return the fingerprint of the master's public key on the minion.

    CLI Example:

    .. code-block:: bash

        salt '*' key.finger_master
    """
    return salt.utils.pem_finger(
        os.path.join(__opts__["pki_dir"], "minion_master.pub"),
        sum_type=__opts__["hash_type"],
    )
# Buggy code
def __init__(opts, pack=None):
    if HAS_BOTO:
        __utils__["boto.assign_funcs"](
            __name__, "cfn", module="cloudformation", pack=pack
        )


# Traceback (NameError)
----------
ID: register_to_route53
Function: boto_route53.present
Name: prd_artdb01.arterra.local
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/state.py", line 1682, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1582, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/boto_route53.py", line 157, in present
private_zone)
File "/usr/lib/python2.6/site-packages/salt/modules/boto_route53.py", line 241, in get_record
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
File "/usr/lib/python2.6/site-packages/salt/utils/boto.py", line 178, in get_connection
keyid, profile)
File "/usr/lib/python2.6/site-packages/salt/utils/boto.py", line 98, in _get_profile
if not key and __salt__['config.option'](service + '.key'):
NameError: global name '__salt__' is not defined
Started: 12:42:55.588665
Duration: 1.487 ms
Changes:

# Fixed code
def __init__(opts):
    if HAS_BOTO:
        __utils__["boto.assign_funcs"](
            __name__, "cfn", module="cloudformation", pack=__salt__
        )
# Buggy code
def __init__(opts, pack=None):
    salt.utils.compat.pack_dunder(__name__)
    if HAS_BOTO:
        __utils__["boto.assign_funcs"](__name__, "kms", pack=__salt__)


# Traceback (NameError)
----------
ID: register_to_route53
Function: boto_route53.present
Name: prd_artdb01.arterra.local
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/state.py", line 1682, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1582, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/boto_route53.py", line 157, in present
private_zone)
File "/usr/lib/python2.6/site-packages/salt/modules/boto_route53.py", line 241, in get_record
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
File "/usr/lib/python2.6/site-packages/salt/utils/boto.py", line 178, in get_connection
keyid, profile)
File "/usr/lib/python2.6/site-packages/salt/utils/boto.py", line 98, in _get_profile
if not key and __salt__['config.option'](service + '.key'):
NameError: global name '__salt__' is not defined
Started: 12:42:55.588665
Duration: 1.487 ms
Changes:

# Fixed code
def __init__(opts):
    salt.utils.compat.pack_dunder(__name__)
    if HAS_BOTO:
        __utils__["boto.assign_funcs"](__name__, "kms", pack=__salt__)
# Buggy code
def __init__(opts, pack=None):
    salt.utils.compat.pack_dunder(__name__)
    if HAS_BOTO:
        __utils__["boto.assign_funcs"](__name__, "route53", pack=pack)


# Traceback (NameError)
----------
ID: register_to_route53
Function: boto_route53.present
Name: prd_artdb01.arterra.local
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/state.py", line 1682, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1582, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/boto_route53.py", line 157, in present
private_zone)
File "/usr/lib/python2.6/site-packages/salt/modules/boto_route53.py", line 241, in get_record
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
File "/usr/lib/python2.6/site-packages/salt/utils/boto.py", line 178, in get_connection
keyid, profile)
File "/usr/lib/python2.6/site-packages/salt/utils/boto.py", line 98, in _get_profile
if not key and __salt__['config.option'](service + '.key'):
NameError: global name '__salt__' is not defined
Started: 12:42:55.588665
Duration: 1.487 ms
Changes:

# Fixed code
def __init__(opts):
    salt.utils.compat.pack_dunder(__name__)
    if HAS_BOTO:
        __utils__["boto.assign_funcs"](__name__, "route53", pack=__salt__)
# Buggy code
def __init__(opts, pack=None):
    salt.utils.compat.pack_dunder(__name__)
    if HAS_BOTO:
        __utils__["boto.assign_funcs"](__name__, "vpc", pack=pack)


# Traceback (NameError)
----------
ID: register_to_route53
Function: boto_route53.present
Name: prd_artdb01.arterra.local
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/state.py", line 1682, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1582, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/boto_route53.py", line 157, in present
private_zone)
File "/usr/lib/python2.6/site-packages/salt/modules/boto_route53.py", line 241, in get_record
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
File "/usr/lib/python2.6/site-packages/salt/utils/boto.py", line 178, in get_connection
keyid, profile)
File "/usr/lib/python2.6/site-packages/salt/utils/boto.py", line 98, in _get_profile
if not key and __salt__['config.option'](service + '.key'):
NameError: global name '__salt__' is not defined
Started: 12:42:55.588665
Duration: 1.487 ms
Changes:

# Fixed code
def __init__(opts):
    salt.utils.compat.pack_dunder(__name__)
    if HAS_BOTO:
        __utils__["boto.assign_funcs"](__name__, "vpc", pack=__salt__)
# Buggy code
def volume_absent(name, driver=None):
    """
    Ensure that a volume is absent.

    .. versionadded:: 2015.8.4

    name
        Name of the volume

    Usage Examples:

    .. code-block:: yaml

        volume_foo:
          dockerng.volume_absent

    """
    ret = {"name": name, "changes": {}, "result": False, "comment": ""}

    volumes = [
        v for v in __salt__["dockerng.volumes"]()["Volumes"] if v["Name"] == name
    ]
    if not volumes:
        ret["result"] = True
        ret["comment"] = "Volume '{0}' already absent".format(name)
        return ret

    try:
        ret["changes"]["removed"] = __salt__["dockerng.remove_volume"](name)
        ret["result"] = True
    except Exception as exc:
        ret["comment"] = "Failed to remove volume '{0}': {1}".format(name, exc)
    return ret


# Traceback (TypeError)
----------
ID: jenkins-volume
Function: dockerng.volume_present
Name: jenkins
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 1682, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1583, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/dockerng.py", line 2153, in volume_present
volumes = [v for v in __salt__['dockerng.volumes']()['Volumes'] if v['Name'] == name]
TypeError: 'NoneType' object is not iterable
Started: 03:33:11.542971
Duration: 4.582 ms
Changes:
----------
ID: jenkins
Function: dockerng.running
Result: False
Comment: One or more requisite failed: jenkins.jenkins-volume
Started:
Duration:
Changes:

# Fixed code
def volume_absent(name, driver=None):
    """
    Ensure that a volume is absent.

    .. versionadded:: 2015.8.4

    name
        Name of the volume

    Usage Examples:

    .. code-block:: yaml

        volume_foo:
          dockerng.volume_absent

    """
    ret = {"name": name, "changes": {}, "result": False, "comment": ""}

    volume = _find_volume(name)
    if not volume:
        ret["result"] = True
        ret["comment"] = "Volume '{0}' already absent".format(name)
        return ret

    try:
        ret["changes"]["removed"] = __salt__["dockerng.remove_volume"](name)
        ret["result"] = True
    except Exception as exc:
        ret["comment"] = "Failed to remove volume '{0}': {1}".format(name, exc)
    return ret
# Buggy code
def info_installed(*names):
    """
    Return the information of the named package(s), installed on the system.

    CLI example:

    .. code-block:: bash

        salt '*' pkg.info_installed <package1>
        salt '*' pkg.info_installed <package1> <package2> <package3> ...
    """
    ret = dict()
    for pkg_name, pkg_nfo in __salt__["lowpkg.info"](*names).items():
        t_nfo = dict()
        # Translate dpkg-specific keys to a common structure
        for key, value in pkg_nfo.items():
            if key == "package":
                t_nfo["name"] = value
            elif key == "origin":
                t_nfo["vendor"] = value
            elif key == "section":
                t_nfo["group"] = value
            elif key == "maintainer":
                t_nfo["packager"] = value
            elif key == "homepage":
                t_nfo["url"] = value
            else:
                t_nfo[key] = value

        ret[pkg_name] = t_nfo

    return ret


# Traceback (KeyError)
root@localhost:~/salt# salt '*' pkg.info_installed bash-completion
ubuntu:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 1039, in _thread_return
return_data = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/aptpkg.py", line 2245, in info_installed
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names).items():
File "/usr/lib/python2.7/dist-packages/salt/modules/dpkg.py", line 383, in info
for pkg_ext_k, pkg_ext_v in dselect_pkg_avail.get(pkg['package'], {}).items():
KeyError: 'package'

# Fixed code
def info_installed(*names):
    """
    Return the information of the named package(s) installed on the system.

    .. versionadded:: 2015.8.1

    names
        The names of the packages for which to return information.

    CLI example:

    .. code-block:: bash

        salt '*' pkg.info_installed <package1>
        salt '*' pkg.info_installed <package1> <package2> <package3> ...
    """
    ret = dict()
    for pkg_name, pkg_nfo in __salt__["lowpkg.info"](*names).items():
        t_nfo = dict()
        # Translate dpkg-specific keys to a common structure
        for key, value in pkg_nfo.items():
            if key == "package":
                t_nfo["name"] = value
            elif key == "origin":
                t_nfo["vendor"] = value
            elif key == "section":
                t_nfo["group"] = value
            elif key == "maintainer":
                t_nfo["packager"] = value
            elif key == "homepage":
                t_nfo["url"] = value
            else:
                t_nfo[key] = value

        ret[pkg_name] = t_nfo

    return ret
# Buggy code
def _etree_to_dict(t):
    if len(t.getchildren()) > 0:
        d = {}
        for child in t.getchildren():
            d[child.tag] = _etree_to_dict(child)
    else:
        d = t.text
    return d


# Traceback (TypeError)
2016-02-05 10:07:01,763 [salt.state       ][INFO    ][25335] Running state [10.129.2.33] at time 10:07:01.762913
2016-02-05 10:07:01,763 [salt.state       ][INFO    ][25335] Executing state glusterfs.peered for 10.129.2.33 <-- This is the primary glusterfs host
2016-02-05 10:07:01,764 [salt.loaded.int.module.cmdmod][INFO    ][25335] Executing command 'gluster --xml --mode=script' in directory '/root'
2016-02-05 10:07:01,871 [salt.loaded.int.module.cmdmod][INFO    ][25335] Executing command 'gluster --xml --mode=script' in directory '/root'
2016-02-05 10:07:01,964 [salt.loaded.int.module.cmdmod][INFO    ][25335] Executing command 'gluster --xml --mode=script' in directory '/root'
2016-02-05 10:07:02,057 [salt.state       ][ERROR   ][25335] An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1624, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1491, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/glusterfs.py", line 83, in peered
elif 'on localhost not needed' in ret['comment']:
TypeError: argument of type 'bool' is not iterable

# Fixed code
def _etree_to_dict(t):
    list_t = list(t)
    if len(list_t) > 0:
        d = {}
        for child in list_t:
            d[child.tag] = _etree_to_dict(child)
    else:
        d = t.text
    return d
# Buggy code
def list_peers():
    """
    Return a list of gluster peers

    CLI Example:

    .. code-block:: bash

        salt '*' glusterfs.list_peers

    GLUSTER direct CLI example (to show what salt is sending to gluster):

        $ gluster peer status

    GLUSTER CLI 3.4.4 return example (so we know what we are parsing):

        Number of Peers: 2

        Hostname: ftp2
        Port: 24007
        Uuid: cbcb256b-e66e-4ec7-a718-21082d396c24
        State: Peer in Cluster (Connected)

        Hostname: ftp3
        Uuid: 5ea10457-6cb2-427b-a770-7897509625e9
        State: Peer in Cluster (Connected)


    """
    root = _gluster_xml("peer status")
    result = [x.find("hostname").text for x in _iter(root, "peer")]
    if len(result) == 0:
        return None
    else:
        return result


# Traceback (TypeError)
2016-02-05 10:07:01,763 [salt.state       ][INFO    ][25335] Running state [10.129.2.33] at time 10:07:01.762913
2016-02-05 10:07:01,763 [salt.state       ][INFO    ][25335] Executing state glusterfs.peered for 10.129.2.33 <-- This is the primary glusterfs host
2016-02-05 10:07:01,764 [salt.loaded.int.module.cmdmod][INFO    ][25335] Executing command 'gluster --xml --mode=script' in directory '/root'
2016-02-05 10:07:01,871 [salt.loaded.int.module.cmdmod][INFO    ][25335] Executing command 'gluster --xml --mode=script' in directory '/root'
2016-02-05 10:07:01,964 [salt.loaded.int.module.cmdmod][INFO    ][25335] Executing command 'gluster --xml --mode=script' in directory '/root'
2016-02-05 10:07:02,057 [salt.state       ][ERROR   ][25335] An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1624, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1491, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/glusterfs.py", line 83, in peered
elif 'on localhost not needed' in ret['comment']:
TypeError: argument of type 'bool' is not iterable

# Fixed code
def list_peers():
    """
    Return a list of gluster peers

    CLI Example:

    .. code-block:: bash

        salt '*' glusterfs.list_peers

    GLUSTER direct CLI example (to show what salt is sending to gluster):

        $ gluster peer status

    GLUSTER CLI 3.4.4 return example (so we know what we are parsing):

        Number of Peers: 2

        Hostname: ftp2
        Port: 24007
        Uuid: cbcb256b-e66e-4ec7-a718-21082d396c24
        State: Peer in Cluster (Connected)

        Hostname: ftp3
        Uuid: 5ea10457-6cb2-427b-a770-7897509625e9
        State: Peer in Cluster (Connected)


    """
    root = _gluster_xml("peer status")
    result = {}
    for et_peer in _iter(root, "peer"):
        result.update(
            {
                et_peer.find("hostname").text: [
                    x.text for x in _iter(et_peer.find("hostnames"), "hostname")
                ]
            }
        )
    if len(result) == 0:
        return None
    else:
        return result
# Buggy code
def get_distribution_id(vm_):
    r"""
    Returns the distribution ID for a VM

    vm\_
        The VM to get the distribution ID for
    """
    distributions = _query("avail", "distributions")["DATA"]
    vm_image_name = config.get_cloud_config_value("image", vm_, __opts__)

    distro_id = ""

    for distro in distributions:
        if vm_image_name == distro["LABEL"]:
            distro_id = distro["DISTRIBUTIONID"]
            return distro_id

    if not distro_id:
        raise SaltCloudNotFound(
            "The DistributionID for the {0} profile could not be found.\n"
            "The {1} instance could not be provisioned.".format(
                vm_image_name, vm_["name"]
            )
        )


# Traceback (KeyError)
[ERROR   ] Failed to create VM prd-core-cache4. Configuration value 'DiskID' needs to be set
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1249, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/linode.py", line 444, in create
root_disk_id = create_disk_from_distro(vm_, node_id)['DiskID']
KeyError: 'DiskID'

# Fixed code
def get_distribution_id(vm_):
    r"""
    Returns the distribution ID for a VM

    vm\_
        The VM to get the distribution ID for
    """
    distributions = _query("avail", "distributions")["DATA"]
    vm_image_name = config.get_cloud_config_value("image", vm_, __opts__)

    distro_id = ""

    for distro in distributions:
        if vm_image_name == distro["LABEL"]:
            distro_id = distro["DISTRIBUTIONID"]
            return distro_id

    if not distro_id:
        raise SaltCloudNotFound(
            "The DistributionID for the '{0}' profile could not be found.\n"
            "The '{1}' instance could not be provisioned.".format(
                vm_image_name, vm_["name"]
            )
        )
# Buggy code
def file_list(self, saltenv="base", prefix="", env=None):
    """
    List the files on the master
    """
    if env is not None:
        salt.utils.warn_until(
            "Boron",
            "Passing a salt environment should be done using 'saltenv' "
            "not 'env'. This functionality will be removed in Salt "
            "Boron.",
        )
        # Backwards compatibility
        saltenv = env

    load = {"saltenv": saltenv, "prefix": prefix, "cmd": "_file_list"}

    return self.channel.send(load)


# Traceback (UnicodeDecodeError)
salt '<minion_id>' saltutil.sync_modules
<minion_id>:
The minion function caused an exception: Traceback (most recent call last):
File "C:\salt\bin\lib\site-packages\salt\minion.py", line 1039, in _thread_return
return_data = func(*args, **kwargs)
File "C:\salt\bin\lib\site-packages\salt\modules\saltutil.py", line 331, in sync_modules
ret = _sync('modules', saltenv)
File "C:\salt\bin\lib\site-packages\salt\modules\saltutil.py", line 112, in _sync
source, sub_env, include_pat=r'E@\.(pyx?|so|zip)$'
File "C:\salt\bin\lib\site-packages\salt\modules\cp.py", line 444, in cache_dir
path, saltenv, include_empty, include_pat, exclude_pat
File "C:\salt\bin\lib\site-packages\salt\fileclient.py", line 233, in cache_dir
if fn_.strip() and fn_.startswith(path):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 85: ordinal not in range(128)

# Fixed code
def file_list(self, saltenv="base", prefix="", env=None):
    """
    List the files on the master
    """
    if env is not None:
        salt.utils.warn_until(
            "Boron",
            "Passing a salt environment should be done using 'saltenv' "
            "not 'env'. This functionality will be removed in Salt "
            "Boron.",
        )
        # Backwards compatibility
        saltenv = env

    load = {"saltenv": saltenv, "prefix": prefix, "cmd": "_file_list"}

    return [sdecode(fn_) for fn_ in self.channel.send(load)]
# Buggy code
def daemonize_if_required(self):
    if self.options.daemon:
        if self._setup_mp_logging_listener_ is True:
            # Stop the logging queue listener for the current process
            # We'll restart it once forked
            log.shutdown_multiprocessing_logging_listener()

        # Late import so logging works correctly
        salt.utils.daemonize()

    # Setup the multiprocessing log queue listener if enabled
    self._setup_mp_logging_listener()


# Traceback (AssertionError)
mp@silver ~/devel/salt % sudo salt-master -d                                                                                                            (git)-[25ef141...|bisect]
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib/python2.7/multiprocessing/util.py", line 325, in _exit_function
p.join()
File "/usr/lib/python2.7/multiprocessing/process.py", line 143, in join
assert self._parent_pid == os.getpid(), 'can only join a child process'
AssertionError: can only join a child process
Error in sys.exitfunc:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib/python2.7/multiprocessing/util.py", line 325, in _exit_function
p.join()
File "/usr/lib/python2.7/multiprocessing/process.py", line 143, in join
assert self._parent_pid == os.getpid(), 'can only join a child process'
AssertionError: can only join a child process
^CError in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/lib/python2.7/multiprocessing/util.py", line 325, in _exit_function
p.join()
File "/usr/lib/python2.7/multiprocessing/process.py", line 145, in join
res = self._popen.wait(timeout)
File "/usr/lib/python2.7/multiprocessing/forking.py", line 154, in wait
return self.poll(0)
File "/usr/lib/python2.7/multiprocessing/forking.py", line 135, in poll
pid, sts = os.waitpid(self.pid, flag)
KeyboardInterrupt
Error in sys.exitfunc:

# Fixed code
def daemonize_if_required(self):
    if self.options.daemon:
        if self._setup_mp_logging_listener_ is True:
            # Stop the logging queue listener for the current process
            # We'll restart it once forked
            log.shutdown_multiprocessing_logging_listener(daemonizing=True)

        # Late import so logging works correctly
        salt.utils.daemonize()

    # Setup the multiprocessing log queue listener if enabled
    self._setup_mp_logging_listener()
# Buggy code
def _dec2hex(decval):
    """
    Converts decimal values to nicely formatted hex strings
    """
    return _pretty_hex("{:X}".format(decval))


# Traceback (ValueError)
# python2.6 -c "print '{:X}'.format(1234)"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ValueError: zero length field name in format
# python2.7 -c "print '{:X}'.format(1234)"
4D2

# Fixed code
def _dec2hex(decval):
    """
    Converts decimal values to nicely formatted hex strings
    """
    return _pretty_hex("{0:X}".format(decval))
# Buggy code
def expand_extensions(self):
    for connection in (self.compute_conn, self.volume_conn):
        if connection is None:
            continue
        for extension in self.extensions:
            for attr in extension.module.__dict__:
                if not inspect.isclass(getattr(extension.module, attr)):
                    continue
                for key, value in six.iteritems(connection.__dict__):
                    if not isinstance(value, novaclient.base.Manager):
                        continue
                    if value.__class__.__name__ == attr:
                        setattr(connection, key, getattr(connection, extension.name))


# Traceback (AttributeError)
[ERROR   ] There was a profile error: 'SaltNova' object has no attribute '_discover_extensions'
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/cli.py", line 275, in run
self.config.get('names')
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1410, in run_profile
ret[name] = self.create(vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1256, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/nova.py", line 603, in create
conn = get_conn()
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/nova.py", line 210, in get_conn
conn = nova.SaltNova(**kwargs)
File "/usr/lib/python2.7/dist-packages/salt/utils/openstack/nova.py", line 140, in __init__
self.extensions = self._discover_extensions('1.1')
AttributeError: 'SaltNova' object has no attribute '_discover_extensions'

# Fixed code
def expand_extensions(self):
    for connection in (self.compute_conn, self.volume_conn):
        if connection is None:
            continue
        for extension in self.extensions:
            for attr in extension.module.__dict__:
                if not inspect.isclass(getattr(extension.module, attr)):
                    continue
                for key, value in six.iteritems(connection.__dict__):
                    if not isinstance(value, novaclient.base.Manager):
                        continue
                    if value.__class__.__name__ == attr:
                        setattr(connection, key, extension.manager_class(connection))
# Buggy code
def delete(
    name,
    skip_final_snapshot=None,
    final_db_snapshot_identifier=None,
    region=None,
    key=None,
    keyid=None,
    profile=None,
):
    """
    Delete an RDS instance.

    CLI example::

        salt myminion boto_rds.delete myrds skip_final_snapshot=True \
                region=us-east-1
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not skip_final_snapshot or final_db_snapshot_identifier:
        raise SaltInvocationError(
            "At least on of the following must"
            " be specified: skip_final_snapshot"
            " final_db_snapshot_identifier"
        )
    try:
        conn.delete_db_instance(name, skip_final_snapshot, final_db_snapshot_identifier)
        msg = "Deleted RDS instance {0}.".format(name)
        log.info(msg)
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to delete RDS instance {0}".format(name)
        log.error(msg)
        return False


# Traceback (SaltInvocationError)
ID: my-blog
Function: boto_rds.absent
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 1594, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1491, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/boto_rds.py", line 414, in absent
region, key, keyid, profile)
File "/usr/lib/python2.7/dist-packages/salt/modules/boto_rds.py", line 490, in delete
raise SaltInvocationError('At least on of the following must'
SaltInvocationError: At least on of the following must be specified: skip_final_snapshot final_db_snapshot_identifier
Started: 14:42:54.723717
Duration: 120.964 ms
Changes:

# Fixed code
def delete(
    name,
    skip_final_snapshot=None,
    final_db_snapshot_identifier=None,
    region=None,
    key=None,
    keyid=None,
    profile=None,
):
    """
    Delete an RDS instance.

    CLI example::

        salt myminion boto_rds.delete myrds skip_final_snapshot=True \
                region=us-east-1
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not skip_final_snapshot and not final_db_snapshot_identifier:
        raise SaltInvocationError(
            "At least on of the following must"
            " be specified: skip_final_snapshot"
            " final_db_snapshot_identifier"
        )
    try:
        conn.delete_db_instance(name, skip_final_snapshot, final_db_snapshot_identifier)
        msg = "Deleted RDS instance {0}.".format(name)
        log.info(msg)
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        msg = "Failed to delete RDS instance {0}".format(name)
        log.error(msg)
        return False