gurudesh/pytracebugs huggingface dataset:
# Buggy code
def processlist(**connection_args):
    """
    Retrieves the processlist from the MySQL server via
    "SHOW FULL PROCESSLIST".

    Returns: a list of dicts, with each dict representing a process:
        {'Command': 'Query',
                          'Host': 'localhost',
                          'Id': 39,
                          'Info': 'SHOW FULL PROCESSLIST',
                          'Rows_examined': 0,
                          'Rows_read': 1,
                          'Rows_sent': 0,
                          'State': None,
                          'Time': 0,
                          'User': 'root',
                          'db': 'mysql'}

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.processlist

    """
    ret = []

    dbc = _connect(**connection_args)
    cur = dbc.cursor()
    _execute(cur, "SHOW FULL PROCESSLIST")
    hdr = [c[0] for c in cur.description]
    for _ in range(cur.rowcount):
        row = cur.fetchone()
        idx_r = {}
        for idx_j in range(len(hdr)):
            idx_r[hdr[idx_j]] = row[idx_j]
        ret.append(idx_r)
    cur.close()
    return ret


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 366, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 60, in top-level template code
File "/usr/lib/python2.7/dist-packages/salt/modules/mysql.py", line 1958, in get_slave_status
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
File "/usr/lib/python2.7/dist-packages/salt/modules/mysql.py", line 1837, in __do_query_into_hash
cursor = conn.cursor()
AttributeError: 'NoneType' object has no attribute 'cursor'

# Fixed code
def processlist(**connection_args):
    """
    Retrieves the processlist from the MySQL server via
    "SHOW FULL PROCESSLIST".

    Returns: a list of dicts, with each dict representing a process:
        {'Command': 'Query',
                          'Host': 'localhost',
                          'Id': 39,
                          'Info': 'SHOW FULL PROCESSLIST',
                          'Rows_examined': 0,
                          'Rows_read': 1,
                          'Rows_sent': 0,
                          'State': None,
                          'Time': 0,
                          'User': 'root',
                          'db': 'mysql'}

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.processlist

    """
    ret = []

    dbc = _connect(**connection_args)
    if dbc is None:
        return []
    cur = dbc.cursor()
    _execute(cur, "SHOW FULL PROCESSLIST")
    hdr = [c[0] for c in cur.description]
    for _ in range(cur.rowcount):
        row = cur.fetchone()
        idx_r = {}
        for idx_j in range(len(hdr)):
            idx_r[hdr[idx_j]] = row[idx_j]
        ret.append(idx_r)
    cur.close()
    return ret
# Buggy code
def get_master_status(**connection_args):
    """
    Retrieves the master status from the minion.

    Returns::

        {'host.domain.com': {'Binlog_Do_DB': '',
                         'Binlog_Ignore_DB': '',
                         'File': 'mysql-bin.000021',
                         'Position': 107}}

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.get_master_status

    """
    mod = sys._getframe().f_code.co_name
    log.debug("{0}<--".format(mod))
    conn = _connect(**connection_args)
    rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
    conn.close()

    # check for if this minion is not a master
    if len(rtnv) == 0:
        rtnv.append([])

    log.debug("{0}-->{1}".format(mod, len(rtnv[0])))
    return rtnv[0]


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 366, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 60, in top-level template code
File "/usr/lib/python2.7/dist-packages/salt/modules/mysql.py", line 1958, in get_slave_status
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
File "/usr/lib/python2.7/dist-packages/salt/modules/mysql.py", line 1837, in __do_query_into_hash
cursor = conn.cursor()
AttributeError: 'NoneType' object has no attribute 'cursor'

# Fixed code
def get_master_status(**connection_args):
    """
    Retrieves the master status from the minion.

    Returns::

        {'host.domain.com': {'Binlog_Do_DB': '',
                         'Binlog_Ignore_DB': '',
                         'File': 'mysql-bin.000021',
                         'Position': 107}}

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.get_master_status

    """
    mod = sys._getframe().f_code.co_name
    log.debug("{0}<--".format(mod))
    conn = _connect(**connection_args)
    if conn is None:
        return []
    rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
    conn.close()

    # check for if this minion is not a master
    if len(rtnv) == 0:
        rtnv.append([])

    log.debug("{0}-->{1}".format(mod, len(rtnv[0])))
    return rtnv[0]
# Buggy code
def showvariables(**connection_args):
    """
    Retrieves the show variables from the minion.

    Returns::
        show variables full dict

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.showvariables

    """
    mod = sys._getframe().f_code.co_name
    log.debug("{0}<--".format(mod))
    conn = _connect(**connection_args)
    rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
    conn.close()
    if len(rtnv) == 0:
        rtnv.append([])

    log.debug("{0}-->{1}".format(mod, len(rtnv[0])))
    return rtnv


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 366, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 60, in top-level template code
File "/usr/lib/python2.7/dist-packages/salt/modules/mysql.py", line 1958, in get_slave_status
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
File "/usr/lib/python2.7/dist-packages/salt/modules/mysql.py", line 1837, in __do_query_into_hash
cursor = conn.cursor()
AttributeError: 'NoneType' object has no attribute 'cursor'

# Fixed code
def showvariables(**connection_args):
    """
    Retrieves the show variables from the minion.

    Returns::
        show variables full dict

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.showvariables

    """
    mod = sys._getframe().f_code.co_name
    log.debug("{0}<--".format(mod))
    conn = _connect(**connection_args)
    if conn is None:
        return []
    rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
    conn.close()
    if len(rtnv) == 0:
        rtnv.append([])

    log.debug("{0}-->{1}".format(mod, len(rtnv[0])))
    return rtnv
# Buggy code
def showglobal(**connection_args):
    """
    Retrieves the show global variables from the minion.

    Returns::
        show global variables full dict

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.showglobal

    """
    mod = sys._getframe().f_code.co_name
    log.debug("{0}<--".format(mod))
    conn = _connect(**connection_args)
    rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
    conn.close()
    if len(rtnv) == 0:
        rtnv.append([])

    log.debug("{0}-->{1}".format(mod, len(rtnv[0])))
    return rtnv


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 366, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 60, in top-level template code
File "/usr/lib/python2.7/dist-packages/salt/modules/mysql.py", line 1958, in get_slave_status
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
File "/usr/lib/python2.7/dist-packages/salt/modules/mysql.py", line 1837, in __do_query_into_hash
cursor = conn.cursor()
AttributeError: 'NoneType' object has no attribute 'cursor'

# Fixed code
def showglobal(**connection_args):
    """
    Retrieves the show global variables from the minion.

    Returns::
        show global variables full dict

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.showglobal

    """
    mod = sys._getframe().f_code.co_name
    log.debug("{0}<--".format(mod))
    conn = _connect(**connection_args)
    if conn is None:
        return []
    rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
    conn.close()
    if len(rtnv) == 0:
        rtnv.append([])

    log.debug("{0}-->{1}".format(mod, len(rtnv[0])))
    return rtnv
# Buggy code
def _datavalue(datatype, data):
    if datatype == "int":
        return int(data)
    elif datatype and datatype[0] == "re_int":
        return int(re.search(datatype[1], data).group(1))
    else:
        return data


# Traceback (ValueError)
[salt.loader                                                ][CRITICAL][80377] Failed to load grains defined in grain file disks.disks in function <function disks at 0x80cff9140>, error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/loader.py", line 724, in grains
ret = fun()
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 31, in disks
return _freebsd_geom()
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 107, in _freebsd_geom
parse_geom_attribs(device)
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 94, in parse_geom_attribs
search.group(1))
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 69, in _datavalue
return int(data)
ValueError: invalid literal for int() with base 10: 'unknown'

# Fixed code
def _datavalue(datatype, data):
    if datatype == "try_int":
        try:
            return int(data)
        except ValueError:
            return None
    elif datatype is tuple and datatype[0] == "re_int":
        search = re.search(datatype[1], data)
        if search:
            try:
                return int(search.group(1))
            except ValueError:
                return None
        return None
    else:
        return data
# Buggy code
def _freebsd_geom():
    geom = salt.utils.which("geom")
    ret = {"disks": {}, "SSDs": []}

    devices = __salt__["cmd.run"]("{0} disk list".format(geom))
    devices = devices.split("\n\n")

    def parse_geom_attribs(device):
        tmp = {}
        for line in device.split("\n"):
            for attrib in _geom_attribs:
                search = re.search(r"{0}:\s(.*)".format(attrib), line)
                if search:
                    value = _datavalue(
                        _geomconsts._datatypes.get(attrib), search.group(1)
                    )
                    tmp[attrib] = value
                    if attrib in _geomconsts._aliases:
                        tmp[_geomconsts._aliases[attrib]] = value

        name = tmp.pop(_geomconsts.GEOMNAME)

        ret["disks"][name] = tmp
        if tmp[_geomconsts.ROTATIONRATE] == 0:
            log.trace("Device {0} reports itself as an SSD".format(device))
            ret["SSDs"].append(name)

    for device in devices:
        parse_geom_attribs(device)

    return ret


# Traceback (ValueError)
[salt.loader                                                ][CRITICAL][80377] Failed to load grains defined in grain file disks.disks in function <function disks at 0x80cff9140>, error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/loader.py", line 724, in grains
ret = fun()
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 31, in disks
return _freebsd_geom()
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 107, in _freebsd_geom
parse_geom_attribs(device)
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 94, in parse_geom_attribs
search.group(1))
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 69, in _datavalue
return int(data)
ValueError: invalid literal for int() with base 10: 'unknown'

# Fixed code
def _freebsd_geom():
    geom = salt.utils.which("geom")
    ret = {"disks": {}, "SSDs": []}

    devices = __salt__["cmd.run"]("{0} disk list".format(geom))
    devices = devices.split("\n\n")

    def parse_geom_attribs(device):
        tmp = {}
        for line in device.split("\n"):
            for attrib in _geom_attribs:
                search = re.search(r"{0}:\s(.*)".format(attrib), line)
                if search:
                    value = _datavalue(
                        _geomconsts._datatypes.get(attrib), search.group(1)
                    )
                    tmp[attrib] = value
                    if attrib in _geomconsts._aliases:
                        tmp[_geomconsts._aliases[attrib]] = value

        name = tmp.pop(_geomconsts.GEOMNAME)
        if name.startswith("cd"):
            return

        ret["disks"][name] = tmp
        if tmp[_geomconsts.ROTATIONRATE] == 0:
            log.trace("Device {0} reports itself as an SSD".format(device))
            ret["SSDs"].append(name)

    for device in devices:
        parse_geom_attribs(device)

    return ret
# Buggy code
def parse_geom_attribs(device):
    tmp = {}
    for line in device.split("\n"):
        for attrib in _geom_attribs:
            search = re.search(r"{0}:\s(.*)".format(attrib), line)
            if search:
                value = _datavalue(_geomconsts._datatypes.get(attrib), search.group(1))
                tmp[attrib] = value
                if attrib in _geomconsts._aliases:
                    tmp[_geomconsts._aliases[attrib]] = value

    name = tmp.pop(_geomconsts.GEOMNAME)

    ret["disks"][name] = tmp
    if tmp[_geomconsts.ROTATIONRATE] == 0:
        log.trace("Device {0} reports itself as an SSD".format(device))
        ret["SSDs"].append(name)


# Traceback (ValueError)
[salt.loader                                                ][CRITICAL][80377] Failed to load grains defined in grain file disks.disks in function <function disks at 0x80cff9140>, error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/loader.py", line 724, in grains
ret = fun()
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 31, in disks
return _freebsd_geom()
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 107, in _freebsd_geom
parse_geom_attribs(device)
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 94, in parse_geom_attribs
search.group(1))
File "/usr/local/lib/python2.7/site-packages/salt/grains/disks.py", line 69, in _datavalue
return int(data)
ValueError: invalid literal for int() with base 10: 'unknown'

# Fixed code
def parse_geom_attribs(device):
    tmp = {}
    for line in device.split("\n"):
        for attrib in _geom_attribs:
            search = re.search(r"{0}:\s(.*)".format(attrib), line)
            if search:
                value = _datavalue(_geomconsts._datatypes.get(attrib), search.group(1))
                tmp[attrib] = value
                if attrib in _geomconsts._aliases:
                    tmp[_geomconsts._aliases[attrib]] = value

    name = tmp.pop(_geomconsts.GEOMNAME)
    if name.startswith("cd"):
        return

    ret["disks"][name] = tmp
    if tmp[_geomconsts.ROTATIONRATE] == 0:
        log.trace("Device {0} reports itself as an SSD".format(device))
        ret["SSDs"].append(name)
# Buggy code
def __virtual__():
    """
    Confirm this module is on a Debian based system
    """
    if __grains__.get("os_family") in ("Kali", "Debian", "LinuxMint"):
        return __virtualname__
    return False


# Traceback (KeyError)
[INFO    ] Completed state [ssh] at time 22:06:57.799060
local:
----------
ID: testsvc
Function: service.running
Name: ssh
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 1626, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1492, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/service.py", line 296, in running
before_toggle_enable_status = __salt__['service.enabled'](name)
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 900, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/dist-packages/salt/utils/lazy.py", line 93, in __getitem__
raise KeyError(key)
KeyError: 'service.enabled'
Started: 22:06:57.438366
Duration: 360.694 ms
Changes:

# Fixed code
def __virtual__():
    """
    Confirm this module is on a Debian based system
    """
    if __grains__.get("os_family") in ("Kali", "Debian"):
        return __virtualname__
    return False
# Buggy code
def create_node(**kwargs):
    """
    convenience function to make the rest api call for node creation.
    """
    name = kwargs["name"]
    size = kwargs["size"]
    image = kwargs["image"]
    location = kwargs["location"]
    networks = kwargs["networks"]

    data = json.dumps(
        {
            "name": name,
            "package": size["name"],
            "image": image["name"],
            "networks": networks,
        }
    )

    try:
        ret = query(command="/my/machines", data=data, method="POST", location=location)
        if ret[0] in VALID_RESPONSE_CODES:
            return ret[1]
    except Exception as exc:
        log.error("Failed to create node {0}: {1}".format(name, exc))

    return {}


# Traceback (TypeError)
name: ch3ll-joyent
None
[15:35:12,413][salt.cloud.cli                           :442 ][ERROR   ] There was a profile error: 'NoneType' object has no attribute '__getitem__'
Traceback (most recent call last):
File "/testing/salt/cloud/cli.py", line 284, in run
self.config.get('names')
File "/testing/salt/cloud/__init__.py", line 1446, in run_profile
ret[name] = self.create(vm_)
File "/testing/salt/cloud/__init__.py", line 1281, in create
output = self.clouds[func](vm_)
File "/testing/salt/cloud/clouds/joyent.py", line 318, in create
query_instance(vm_)
File "/testing/salt/cloud/clouds/joyent.py", line 220, in query_instance
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
File "/testing/salt/utils/cloud.py", line 2315, in wait_for_ip
data = update_callback(*update_args, **update_kwargs)
File "/testing/salt/cloud/clouds/joyent.py", line 191, in _query_ip_address
data = show_instance(vm_['name'], call='action')
File "/testing/salt/cloud/clouds/joyent.py", line 653, in show_instance
ret = query(command='my/machines/{0}'.format(node['id']),
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def create_node(**kwargs):
    """
    convenience function to make the rest api call for node creation.
    """
    name = kwargs["name"]
    size = kwargs["size"]
    image = kwargs["image"]
    location = kwargs["location"]
    networks = kwargs.get("networks")

    create_data = {
        "name": name,
        "package": size["name"],
        "image": image["name"],
    }
    if networks is not None:
        create_data["networks"] = networks
    data = json.dumps(create_data)

    try:
        ret = query(command="/my/machines", data=data, method="POST", location=location)
        if ret[0] in VALID_RESPONSE_CODES:
            return ret[1]
    except Exception as exc:
        log.error("Failed to create node {0}: {1}".format(name, exc))

    return {}
# Buggy code
def __virtual__():
    """
    Confirm this module is on a Debian based system
    """
    if __grains__.get("os_family") in ("Kali", "Debian", "LinuxMint"):
        return __virtualname__
    elif __grains__.get("os_family", False) == "Cumulus":
        return __virtualname__
    return (False, "The pkg module could not be loaded: unsupported OS family")


# Traceback (ParserError)
li1105-12 ~ master # salt jmoney-master state.show_top
jmoney-master:
The minion function caused an exception: Traceback (most recent call last):
File "/root/salt/salt/minion.py", line 1173, in _thread_return
return_data = func(*args, **kwargs)
File "/root/salt/salt/modules/state.py", line 1045, in show_top
top_ = st_.get_top()
File "/root/salt/salt/state.py", line 2436, in get_top
tops = self.get_tops()
File "/root/salt/salt/state.py", line 2313, in get_tops
saltenv=saltenv
File "/root/salt/salt/template.py", line 79, in compile_template
ret = render(input_data, saltenv, sls, **render_kwargs)
File "/root/salt/salt/renderers/yaml.py", line 50, in render
data = load(yaml_data, Loader=get_yaml_loader(argline))
File "/usr/lib/python2.7/dist-packages/yaml/__init__.py", line 71, in load
return loader.get_single_data()
File "/usr/lib/python2.7/dist-packages/yaml/constructor.py", line 37, in get_single_data
node = self.get_single_node()
File "/usr/lib/python2.7/dist-packages/yaml/composer.py", line 36, in get_single_node
document = self.compose_document()
File "/usr/lib/python2.7/dist-packages/yaml/composer.py", line 55, in compose_document
node = self.compose_node(None, None)
File "/usr/lib/python2.7/dist-packages/yaml/composer.py", line 84, in compose_node
node = self.compose_mapping_node(anchor)
File "/usr/lib/python2.7/dist-packages/yaml/composer.py", line 127, in compose_mapping_node
while not self.check_event(MappingEndEvent):
File "/usr/lib/python2.7/dist-packages/yaml/parser.py", line 98, in check_event
self.current_event = self.state()
File "/usr/lib/python2.7/dist-packages/yaml/parser.py", line 439, in parse_block_mapping_key
"expected <block end>, but found %r" % token.id, token.start_mark)
ParserError: while parsing a block mapping
in "<unicode string>", line 1, column 1:
base:
^
expected <block end>, but found '<block sequence start>'
in "<unicode string>", line 3, column 5:
- state1
^

# Fixed code
def __virtual__():
    """
    Confirm this module is on a Debian based system
    """
    if __grains__.get("os_family") in ("Kali", "Debian"):
        return __virtualname__
    elif __grains__.get("os_family", False) == "Cumulus":
        return __virtualname__
    return (False, "The pkg module could not be loaded: unsupported OS family")
# Buggy code
def _sysv_enabled(name):
    """
    A System-V style service is assumed disabled if the "startup" symlink
    (starts with "S") to its script is found in /etc/init.d in the current
    runlevel.
    """
    return bool(glob.glob("/etc/rc%s.d/S*%s" % (_runlevel(), name)))


# Traceback (ParserError)
li1105-12 ~ master # salt jmoney-master state.show_top
jmoney-master:
The minion function caused an exception: Traceback (most recent call last):
File "/root/salt/salt/minion.py", line 1173, in _thread_return
return_data = func(*args, **kwargs)
File "/root/salt/salt/modules/state.py", line 1045, in show_top
top_ = st_.get_top()
File "/root/salt/salt/state.py", line 2436, in get_top
tops = self.get_tops()
File "/root/salt/salt/state.py", line 2313, in get_tops
saltenv=saltenv
File "/root/salt/salt/template.py", line 79, in compile_template
ret = render(input_data, saltenv, sls, **render_kwargs)
File "/root/salt/salt/renderers/yaml.py", line 50, in render
data = load(yaml_data, Loader=get_yaml_loader(argline))
File "/usr/lib/python2.7/dist-packages/yaml/__init__.py", line 71, in load
return loader.get_single_data()
File "/usr/lib/python2.7/dist-packages/yaml/constructor.py", line 37, in get_single_data
node = self.get_single_node()
File "/usr/lib/python2.7/dist-packages/yaml/composer.py", line 36, in get_single_node
document = self.compose_document()
File "/usr/lib/python2.7/dist-packages/yaml/composer.py", line 55, in compose_document
node = self.compose_node(None, None)
File "/usr/lib/python2.7/dist-packages/yaml/composer.py", line 84, in compose_node
node = self.compose_mapping_node(anchor)
File "/usr/lib/python2.7/dist-packages/yaml/composer.py", line 127, in compose_mapping_node
while not self.check_event(MappingEndEvent):
File "/usr/lib/python2.7/dist-packages/yaml/parser.py", line 98, in check_event
self.current_event = self.state()
File "/usr/lib/python2.7/dist-packages/yaml/parser.py", line 439, in parse_block_mapping_key
"expected <block end>, but found %r" % token.id, token.start_mark)
ParserError: while parsing a block mapping
in "<unicode string>", line 1, column 1:
base:
^
expected <block end>, but found '<block sequence start>'
in "<unicode string>", line 3, column 5:
- state1
^

# Fixed code
def _sysv_enabled(name):
    """
    A System-V style service is assumed disabled if the "startup" symlink
    (starts with "S") to its script is found in /etc/init.d in the current
    runlevel.
    """
    # Find exact match (disambiguate matches like "S01anacron" for cron)
    for match in glob.glob("/etc/rc%s.d/S*%s" % (_runlevel(), name)):
        if re.match(r"S\d{,2}%s" % name, os.path.basename(match)):
            return True
    return False
# Buggy code
def start(self):
    """
    Start the actual minion.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    try:
        self.prepare()
        if check_user(self.config["user"]):
            self.verify_hash_type()
            self.start_log_info()
            self.minion.tune_in()
    finally:
        self.shutdown()


# Traceback (TypeError)
2016-04-15 13:23:12,471 [salt.minion      ][ERROR   ] No master could be reached or all masters denied the minions connection attempt.
2016-04-15 13:23:12,473 [tornado.application][ERROR   ] Exception in callback <functools.partial object at 0x7fbd0876e158>
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/tornado/ioloop.py", line 592, in _run_callback
ret = callback()
File "/usr/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/tornado/ioloop.py", line 598, in <lambda>
self.add_future(ret, lambda f: f.result())
File "/usr/lib/python2.7/dist-packages/tornado/concurrent.py", line 215, in result
raise_exc_info(self._exc_info)
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 879, in run
yielded = self.gen.send(value)
File "/usr/lib/python2.7/dist-packages/salt/minion.py", line 1608, in handle_event
failed=True)
TypeError: 'NoneType' object is not iterable

# Fixed code
def start(self):
    """
    Start the actual minion.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    try:
        self.prepare()
        if check_user(self.config["user"]):
            self.verify_hash_type()
            self.start_log_info()
            self.minion.tune_in()
            if self.minion.restart:
                raise SaltClientError("Minion could not connect to Master")
    finally:
        self.shutdown()
# Buggy code
def __virtual__():
    """
    Only load if the dockerng execution module is available
    """
    if "dockerng.version" in __salt__:
        global _validate_input  # pylint: disable=global-statement
        _validate_input = salt.utils.namespaced_function(_validate_input, globals())
        return __virtualname__
    return (False, __salt__.missing_fun_string("dockerng.version"))


# Traceback (NameError)
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1703, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1660, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/dockerng.py", line 1615, in running
validate_ip_addrs=validate_ip_addrs)
File "/usr/lib/python2.7/site-packages/salt/modules/dockerng.py", line 1776, in _validate_input
cur_docker_py = _get_docker_py_versioninfo()
NameError: global name '_get_docker_py_versioninfo' is not defined

# Fixed code
def __virtual__():
    """
    Only load if the dockerng execution module is available
    """
    if "dockerng.version" in __salt__:
        global _validate_input  # pylint: disable=global-statement
        _validate_input = salt.utils.namespaced_function(
            _validate_input,
            globals(),
            preserve_context=True,
        )
        return __virtualname__
    return (False, __salt__.missing_fun_string("dockerng.version"))
# Buggy code
def namespaced_function(function, global_dict, defaults=None):
    """
    Redefine (clone) a function under a different globals() namespace scope
    """
    if defaults is None:
        defaults = function.__defaults__

    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 (NameError)
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1703, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1660, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/dockerng.py", line 1615, in running
validate_ip_addrs=validate_ip_addrs)
File "/usr/lib/python2.7/site-packages/salt/modules/dockerng.py", line 1776, in _validate_input
cur_docker_py = _get_docker_py_versioninfo()
NameError: global name '_get_docker_py_versioninfo' is not defined

# 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
    )
    new_namespaced_function.__dict__.update(function.__dict__)
    return new_namespaced_function
# Buggy code
def get_loginclass(name):
    """
    Get the login class of the user

    .. note::
        This function only applies to OpenBSD systems.

    CLI Example:

    .. code-block:: bash

        salt '*' user.get_loginclass foo
    """
    if __grains__["kernel"] != "OpenBSD":
        return False
    userinfo = __salt__["cmd.run_stdout"](["userinfo", name], python_shell=False)
    for line in userinfo.splitlines():
        if line.startswith("class"):
            try:
                ret = line.split(None, 1)[1]
                break
            except ValueError:
                continue
    else:
        ret = ""
    return ret


# Traceback (IndexError)
ID: dev-account
Function: user.present
Name: dev
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/salt/state.py", line 1624, in call
**cdata['kwargs'])
File "/usr/local/lib/python2.7/site-packages/salt/loader.py", line 1491, in wrapper
return f(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/salt/states/user.py", line 457, in present
lcpre = __salt__['user.get_loginclass'](name)
File "/usr/local/lib/python2.7/site-packages/salt/modules/useradd.py", line 509, in get_loginclass
ret = line.split(None, 1)[1]
IndexError: list index out of range
Started: 19:09:14.276952
Duration: 50.02 ms
Changes:

# Fixed code
def get_loginclass(name):
    """
    Get the login class of the user

    .. note::
        This function only applies to OpenBSD systems.

    CLI Example:

    .. code-block:: bash

        salt '*' user.get_loginclass foo
    """
    if __grains__["kernel"] != "OpenBSD":
        return False
    userinfo = __salt__["cmd.run_stdout"](["userinfo", name], python_shell=False)
    for line in userinfo.splitlines():
        if line.startswith("class"):
            try:
                ret = line.split(None, 1)[1]
                break
            except (ValueError, IndexError):
                continue
    else:
        ret = ""
    return ret
# Buggy code
def _get_service_exec():
    """
    Debian uses update-rc.d to manage System-V style services.
    http://www.debian.org/doc/debian-policy/ch-opersys.html#s9.3.3
    """
    executable = "update-rc.d"
    salt.utils.check_or_die(executable)
    return executable


# Traceback (CommandNotFoundError)
==> default:      Comment: An exception occurred in this state: Traceback (most recent call last):
==> default:                 File "/usr/lib/python2.7/site-packages/salt/state.py", line 1703, in call
==> default:                   **cdata['kwargs'])
==> default:                 File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1612, in wrapper
==> default:                   return f(*args, **kwargs)
==> default:                 File "/usr/lib/python2.7/site-packages/salt/states/service.py", line 469, in enabled
==> default:                   ret.update(_enable(name, None, **kwargs))
==> default:                 File "/usr/lib/python2.7/site-packages/salt/states/service.py", line 127, in _enable
==> default:                   if __salt__['service.enable'](name, **kwargs):
==> default:                 File "/usr/lib/python2.7/site-packages/salt/modules/systemd.py", line 704, in enable
==> default:                   cmd = [_get_service_exec(), '-f', name, 'defaults', '99']
==> default:                 File "/usr/lib/python2.7/site-packages/salt/modules/systemd.py", line 144, in _get_service_exec
==> default:                   salt.utils.check_or_die(executable)
==> default:                 File "/usr/lib/python2.7/site-packages/salt/utils/__init__.py", line 804, in check_or_die
==> default:                   raise CommandNotFoundError(command)
==> default:               CommandNotFoundError: update-rc.d

# Fixed code
def _get_service_exec():
    """
    Returns the path to the sysv service manager (either update-rc.d or
    chkconfig)
    """
    contextkey = "systemd._get_service_exec"
    if contextkey not in __context__:
        executables = ("update-rc.d", "chkconfig")
        for executable in executables:
            service_exec = salt.utils.which(executable)
            if service_exec is not None:
                break
        else:
            raise CommandExecutionError(
                "Unable to find sysv service manager (tried {0})".format(
                    ", ".join(executables)
                )
            )
        __context__[contextkey] = service_exec
    return __context__[contextkey]
# Buggy code
def enable(name, **kwargs):  # pylint: disable=unused-argument
    """
    Enable the named service to start when the system boots

    CLI Example:

    .. code-block:: bash

        salt '*' service.enable <service name>
    """
    _check_for_unit_changes(name)
    unmask(name)
    if name in _get_sysv_services():
        cmd = [_get_service_exec(), "-f", name, "defaults", "99"]
        return (
            __salt__["cmd.retcode"](cmd, python_shell=False, ignore_retcode=True) == 0
        )
    return (
        __salt__["cmd.retcode"](
            _systemctl_cmd("enable", name), python_shell=False, ignore_retcode=True
        )
        == 0
    )


# Traceback (CommandNotFoundError)
==> default:      Comment: An exception occurred in this state: Traceback (most recent call last):
==> default:                 File "/usr/lib/python2.7/site-packages/salt/state.py", line 1703, in call
==> default:                   **cdata['kwargs'])
==> default:                 File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1612, in wrapper
==> default:                   return f(*args, **kwargs)
==> default:                 File "/usr/lib/python2.7/site-packages/salt/states/service.py", line 469, in enabled
==> default:                   ret.update(_enable(name, None, **kwargs))
==> default:                 File "/usr/lib/python2.7/site-packages/salt/states/service.py", line 127, in _enable
==> default:                   if __salt__['service.enable'](name, **kwargs):
==> default:                 File "/usr/lib/python2.7/site-packages/salt/modules/systemd.py", line 704, in enable
==> default:                   cmd = [_get_service_exec(), '-f', name, 'defaults', '99']
==> default:                 File "/usr/lib/python2.7/site-packages/salt/modules/systemd.py", line 144, in _get_service_exec
==> default:                   salt.utils.check_or_die(executable)
==> default:                 File "/usr/lib/python2.7/site-packages/salt/utils/__init__.py", line 804, in check_or_die
==> default:                   raise CommandNotFoundError(command)
==> default:               CommandNotFoundError: update-rc.d

# Fixed code
def enable(name, **kwargs):  # pylint: disable=unused-argument
    """
    Enable the named service to start when the system boots

    CLI Example:

    .. code-block:: bash

        salt '*' service.enable <service name>
    """
    _check_for_unit_changes(name)
    unmask(name)
    if name in _get_sysv_services():
        service_exec = _get_service_exec()
        if service_exec.endswith("/update-rc.d"):
            cmd = [service_exec, "-f", name, "defaults", "99"]
        elif service_exec.endswith("/chkconfig"):
            cmd = [service_exec, name, "on"]
        return (
            __salt__["cmd.retcode"](cmd, python_shell=False, ignore_retcode=True) == 0
        )
    return (
        __salt__["cmd.retcode"](
            _systemctl_cmd("enable", name), python_shell=False, ignore_retcode=True
        )
        == 0
    )
# Buggy code
def disable(name, **kwargs):  # pylint: disable=unused-argument
    """
    Disable the named service to not start when the system boots

    CLI Example:

    .. code-block:: bash

        salt '*' service.disable <service name>
    """
    _check_for_unit_changes(name)
    if name in _get_sysv_services():
        cmd = [_get_service_exec(), "-f", name, "remove"]
        return (
            __salt__["cmd.retcode"](cmd, python_shell=False, ignore_retcode=True) == 0
        )
    return (
        __salt__["cmd.retcode"](
            _systemctl_cmd("disable", name), python_shell=False, ignore_retcode=True
        )
        == 0
    )


# Traceback (CommandNotFoundError)
==> default:      Comment: An exception occurred in this state: Traceback (most recent call last):
==> default:                 File "/usr/lib/python2.7/site-packages/salt/state.py", line 1703, in call
==> default:                   **cdata['kwargs'])
==> default:                 File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1612, in wrapper
==> default:                   return f(*args, **kwargs)
==> default:                 File "/usr/lib/python2.7/site-packages/salt/states/service.py", line 469, in enabled
==> default:                   ret.update(_enable(name, None, **kwargs))
==> default:                 File "/usr/lib/python2.7/site-packages/salt/states/service.py", line 127, in _enable
==> default:                   if __salt__['service.enable'](name, **kwargs):
==> default:                 File "/usr/lib/python2.7/site-packages/salt/modules/systemd.py", line 704, in enable
==> default:                   cmd = [_get_service_exec(), '-f', name, 'defaults', '99']
==> default:                 File "/usr/lib/python2.7/site-packages/salt/modules/systemd.py", line 144, in _get_service_exec
==> default:                   salt.utils.check_or_die(executable)
==> default:                 File "/usr/lib/python2.7/site-packages/salt/utils/__init__.py", line 804, in check_or_die
==> default:                   raise CommandNotFoundError(command)
==> default:               CommandNotFoundError: update-rc.d

# Fixed code
def disable(name, **kwargs):  # pylint: disable=unused-argument
    """
    Disable the named service to not start when the system boots

    CLI Example:

    .. code-block:: bash

        salt '*' service.disable <service name>
    """
    _check_for_unit_changes(name)
    if name in _get_sysv_services():
        service_exec = _get_service_exec()
        if service_exec.endswith("/update-rc.d"):
            cmd = [service_exec, "-f", name, "remove"]
        elif service_exec.endswith("/chkconfig"):
            cmd = [service_exec, name, "off"]
        return (
            __salt__["cmd.retcode"](cmd, python_shell=False, ignore_retcode=True) == 0
        )
    return (
        __salt__["cmd.retcode"](
            _systemctl_cmd("disable", name), python_shell=False, ignore_retcode=True
        )
        == 0
    )
# Buggy code
def get_project(conn, vm_):
    """
    Return the project to use.
    """
    projects = conn.ex_list_projects()
    projid = config.get_cloud_config_value("projectid", vm_, __opts__)

    if not projid:
        return False

    for project in projects:
        if str(projid) in (str(project.id), str(project.name)):
            return project

    log.warning("Couldn't find project {0} in projects".format(projid))
    return False


# Traceback (AttributeError)
[DEBUG   ] Could not LazyLoad saltify.avail_sizes
[DEBUG   ] Could not LazyLoad saltify.avail_images
[DEBUG   ] Could not LazyLoad saltify.avail_locations
[DEBUG   ] LazyLoaded rackspace.reboot
[DEBUG   ] LazyLoaded openstack.list_locations
[DEBUG   ] LazyLoaded rackspace.list_locations
[DEBUG   ] Generating minion keys for 'mimi'
[DEBUG   ] MasterEvent PUB socket URI: ipc:///var/run/salt/master/master_event_pub.ipc
[DEBUG   ] MasterEvent PULL socket URI: ipc:///var/run/salt/master/master_event_pull.ipc
[DEBUG   ] Sending event - data = {'_stamp': '2016-03-07T21:43:57.821103'}
[DEBUG   ] Sending event - data = {'profile': 'micro_exo', 'event': 'starting create', '_stamp': '2016-03-07T21:43:57.824100', 'name': 'mimi', 'provider': 'my-exoscale:cloudstack'}
[INFO    ] Creating Cloud VM mimi
[ERROR   ] There was a profile error: 'CloudStackNodeDriver' object has no attribute 'ex_list_projects'
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/cli.py", line 254, in run
self.config.get('names')
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1391, in run_profile
ret[name] = self.create(vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1241, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/cloudstack.py", line 255, in create
if get_project(conn, vm_) is not False:
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/cloudstack.py", line 205, in get_project
projects = conn.ex_list_projects()
AttributeError: 'CloudStackNodeDriver' object has no attribute 'ex_list_projects'

# Fixed code
def get_project(conn, vm_):
    """
    Return the project to use.
    """
    try:
        projects = conn.ex_list_projects()
    except AttributeError:
        # with versions <0.15 of libcloud this is causing an AttributeError.
        return False
    projid = config.get_cloud_config_value("projectid", vm_, __opts__)

    if not projid:
        return False

    for project in projects:
        if str(projid) in (str(project.id), str(project.name)):
            return project

    log.warning("Couldn't find project {0} in projects".format(projid))
    return False
# Buggy code
def __virtual__():
    if not salt.utils.is_proxy():
        return False
    else:
        return __virtualname__


# 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__():
    try:
        if salt.utils.is_proxy() and __opts__["proxy"]["proxytype"] == "esxi":
            return __virtualname__
    except KeyError:
        pass

    return False
# Buggy code
def _grains():
    """
    Get the grains from the proxied device.
    """
    host = __pillar__["proxy"]["host"]
    username, password = _find_credentials(host)
    protocol = __pillar__["proxy"].get("protocol")
    port = __pillar__["proxy"].get("port")
    ret = salt.modules.vsphere.system_info(
        host=host, username=username, password=password, protocol=protocol, port=port
    )
    GRAINS_CACHE.update(ret)
    return GRAINS_CACHE


# 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 _grains():
    """
    Get the grains from the proxied device.
    """
    try:
        host = __pillar__["proxy"]["host"]
        if host:
            username, password = _find_credentials(host)
            protocol = __pillar__["proxy"].get("protocol")
            port = __pillar__["proxy"].get("port")
            ret = salt.modules.vsphere.system_info(
                host=host,
                username=username,
                password=password,
                protocol=protocol,
                port=port,
            )
            GRAINS_CACHE.update(ret)
    except KeyError:
        pass

    return GRAINS_CACHE