gurudesh/pytracebugs huggingface dataset:
# Buggy code
def file_list(self, load):
    """
    Return a list of files from the dominant environment
    """
    if "env" in load:
        # "env" is not supported; Use "saltenv".
        load.pop("env")

    ret = set()
    if "saltenv" not in load:
        return []
    if not isinstance(load["saltenv"], six.string_types):
        load["saltenv"] = six.text_type(load["saltenv"])

    for fsb in self.backends(load.pop("fsbackend", None)):
        fstr = "{0}.file_list".format(fsb)
        if fstr in self.servers:
            ret.update(self.servers[fstr](load))
    # upgrade all set elements to a common encoding
    ret = [salt.utils.locales.sdecode(f) for f in ret]
    # some *fs do not handle prefix. Ensure it is filtered
    prefix = load.get("prefix", "").strip("/")
    if prefix != "":
        ret = [f for f in ret if f.startswith(prefix)]
    return sorted(ret)


# Traceback (UnicodeEncodeError)
ID: test1
Function: file.recurse
Name: /root/group2test
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 1746, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1703, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2807, in recurse
manage_file(dest, src)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2685, in manage_file
**pass_kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 1814, in managed
__env__
File "/usr/lib/python2.6/site-packages/salt/modules/file.py", line 3490, in source_list
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-34: ordinal not in range(128)
Started: 20:08:21.608398
Duration: 1467.811 ms
Changes:

# Fixed code
def file_list(self, load):
    """
    Return a list of files from the dominant environment
    """
    if "env" in load:
        # "env" is not supported; Use "saltenv".
        load.pop("env")

    ret = set()
    if "saltenv" not in load:
        return []
    if not isinstance(load["saltenv"], six.string_types):
        load["saltenv"] = six.text_type(load["saltenv"])

    for fsb in self.backends(load.pop("fsbackend", None)):
        fstr = "{0}.file_list".format(fsb)
        if fstr in self.servers:
            ret.update(self.servers[fstr](load))
    # some *fs do not handle prefix. Ensure it is filtered
    prefix = load.get("prefix", "").strip("/")
    if prefix != "":
        ret = [f for f in ret if f.startswith(prefix)]
    return sorted(ret)
# Buggy code
def file_list_emptydirs(self, load):
    """
    List all emptydirs in the given environment
    """
    if "env" in load:
        # "env" is not supported; Use "saltenv".
        load.pop("env")

    ret = set()
    if "saltenv" not in load:
        return []
    if not isinstance(load["saltenv"], six.string_types):
        load["saltenv"] = six.text_type(load["saltenv"])

    for fsb in self.backends(None):
        fstr = "{0}.file_list_emptydirs".format(fsb)
        if fstr in self.servers:
            ret.update(self.servers[fstr](load))
    # upgrade all set elements to a common encoding
    ret = [salt.utils.locales.sdecode(f) for f in ret]
    # some *fs do not handle prefix. Ensure it is filtered
    prefix = load.get("prefix", "").strip("/")
    if prefix != "":
        ret = [f for f in ret if f.startswith(prefix)]
    return sorted(ret)


# Traceback (UnicodeEncodeError)
ID: test1
Function: file.recurse
Name: /root/group2test
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 1746, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1703, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2807, in recurse
manage_file(dest, src)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2685, in manage_file
**pass_kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 1814, in managed
__env__
File "/usr/lib/python2.6/site-packages/salt/modules/file.py", line 3490, in source_list
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-34: ordinal not in range(128)
Started: 20:08:21.608398
Duration: 1467.811 ms
Changes:

# Fixed code
def file_list_emptydirs(self, load):
    """
    List all emptydirs in the given environment
    """
    if "env" in load:
        # "env" is not supported; Use "saltenv".
        load.pop("env")

    ret = set()
    if "saltenv" not in load:
        return []
    if not isinstance(load["saltenv"], six.string_types):
        load["saltenv"] = six.text_type(load["saltenv"])

    for fsb in self.backends(None):
        fstr = "{0}.file_list_emptydirs".format(fsb)
        if fstr in self.servers:
            ret.update(self.servers[fstr](load))
    # some *fs do not handle prefix. Ensure it is filtered
    prefix = load.get("prefix", "").strip("/")
    if prefix != "":
        ret = [f for f in ret if f.startswith(prefix)]
    return sorted(ret)
# Buggy code
def dir_list(self, load):
    """
    List all directories in the given environment
    """
    if "env" in load:
        # "env" is not supported; Use "saltenv".
        load.pop("env")

    ret = set()
    if "saltenv" not in load:
        return []
    if not isinstance(load["saltenv"], six.string_types):
        load["saltenv"] = six.text_type(load["saltenv"])

    for fsb in self.backends(load.pop("fsbackend", None)):
        fstr = "{0}.dir_list".format(fsb)
        if fstr in self.servers:
            ret.update(self.servers[fstr](load))
    # upgrade all set elements to a common encoding
    ret = [salt.utils.locales.sdecode(f) for f in ret]
    # some *fs do not handle prefix. Ensure it is filtered
    prefix = load.get("prefix", "").strip("/")
    if prefix != "":
        ret = [f for f in ret if f.startswith(prefix)]
    return sorted(ret)


# Traceback (UnicodeEncodeError)
ID: test1
Function: file.recurse
Name: /root/group2test
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 1746, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1703, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2807, in recurse
manage_file(dest, src)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2685, in manage_file
**pass_kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 1814, in managed
__env__
File "/usr/lib/python2.6/site-packages/salt/modules/file.py", line 3490, in source_list
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-34: ordinal not in range(128)
Started: 20:08:21.608398
Duration: 1467.811 ms
Changes:

# Fixed code
def dir_list(self, load):
    """
    List all directories in the given environment
    """
    if "env" in load:
        # "env" is not supported; Use "saltenv".
        load.pop("env")

    ret = set()
    if "saltenv" not in load:
        return []
    if not isinstance(load["saltenv"], six.string_types):
        load["saltenv"] = six.text_type(load["saltenv"])

    for fsb in self.backends(load.pop("fsbackend", None)):
        fstr = "{0}.dir_list".format(fsb)
        if fstr in self.servers:
            ret.update(self.servers[fstr](load))
    # some *fs do not handle prefix. Ensure it is filtered
    prefix = load.get("prefix", "").strip("/")
    if prefix != "":
        ret = [f for f in ret if f.startswith(prefix)]
    return sorted(ret)
# Buggy code
def symlink_list(self, load):
    """
    Return a list of symlinked files and dirs
    """
    if "env" in load:
        # "env" is not supported; Use "saltenv".
        load.pop("env")

    ret = {}
    if "saltenv" not in load:
        return {}
    if not isinstance(load["saltenv"], six.string_types):
        load["saltenv"] = six.text_type(load["saltenv"])

    for fsb in self.backends(load.pop("fsbackend", None)):
        symlstr = "{0}.symlink_list".format(fsb)
        if symlstr in self.servers:
            ret = self.servers[symlstr](load)
    # upgrade all set elements to a common encoding
    ret = dict(
        [
            (salt.utils.locales.sdecode(x), salt.utils.locales.sdecode(y))
            for x, y in ret.items()
        ]
    )
    # some *fs do not handle prefix. Ensure it is filtered
    prefix = load.get("prefix", "").strip("/")
    if prefix != "":
        ret = dict([(x, y) for x, y in six.iteritems(ret) if x.startswith(prefix)])
    return ret


# Traceback (UnicodeEncodeError)
ID: test1
Function: file.recurse
Name: /root/group2test
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 1746, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1703, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2807, in recurse
manage_file(dest, src)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2685, in manage_file
**pass_kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 1814, in managed
__env__
File "/usr/lib/python2.6/site-packages/salt/modules/file.py", line 3490, in source_list
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-34: ordinal not in range(128)
Started: 20:08:21.608398
Duration: 1467.811 ms
Changes:

# Fixed code
def symlink_list(self, load):
    """
    Return a list of symlinked files and dirs
    """
    if "env" in load:
        # "env" is not supported; Use "saltenv".
        load.pop("env")

    ret = {}
    if "saltenv" not in load:
        return {}
    if not isinstance(load["saltenv"], six.string_types):
        load["saltenv"] = six.text_type(load["saltenv"])

    for fsb in self.backends(load.pop("fsbackend", None)):
        symlstr = "{0}.symlink_list".format(fsb)
        if symlstr in self.servers:
            ret = self.servers[symlstr](load)
    # some *fs do not handle prefix. Ensure it is filtered
    prefix = load.get("prefix", "").strip("/")
    if prefix != "":
        ret = dict([(x, y) for x, y in six.iteritems(ret) if x.startswith(prefix)])
    return ret
# Buggy code
def decode_tuple(data, encoding=None, errors="strict", preserve_dict_class=False):
    """
    Decode all string values to Unicode
    """
    return tuple(decode_list(data, encoding, errors, preserve_dict_class, True))


# Traceback (UnicodeEncodeError)
ID: test1
Function: file.recurse
Name: /root/group2test
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 1746, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1703, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2807, in recurse
manage_file(dest, src)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2685, in manage_file
**pass_kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 1814, in managed
__env__
File "/usr/lib/python2.6/site-packages/salt/modules/file.py", line 3490, in source_list
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-34: ordinal not in range(128)
Started: 20:08:21.608398
Duration: 1467.811 ms
Changes:

# Fixed code
def decode_tuple(
    data, encoding=None, errors="strict", keep=False, preserve_dict_class=False
):
    """
    Decode all string values to Unicode
    """
    return tuple(decode_list(data, encoding, errors, keep, preserve_dict_class, True))
# Buggy code
def encode_tuple(data, encoding=None, errors="strict", preserve_dict_class=False):
    """
    Encode all string values to Unicode
    """
    return tuple(encode_list(data, encoding, errors, preserve_dict_class, True))


# Traceback (UnicodeEncodeError)
ID: test1
Function: file.recurse
Name: /root/group2test
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 1746, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1703, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2807, in recurse
manage_file(dest, src)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2685, in manage_file
**pass_kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 1814, in managed
__env__
File "/usr/lib/python2.6/site-packages/salt/modules/file.py", line 3490, in source_list
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-34: ordinal not in range(128)
Started: 20:08:21.608398
Duration: 1467.811 ms
Changes:

# Fixed code
def encode_tuple(
    data, encoding=None, errors="strict", keep=False, preserve_dict_class=False
):
    """
    Encode all string values to Unicode
    """
    return tuple(encode_list(data, encoding, errors, keep, preserve_dict_class, True))
# Buggy code
def wrapped(*args, **kwargs):
    start_time = time.time()
    ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs))
    end_time = time.time()
    if function.__module__.startswith("salt.loaded.int."):
        mod_name = function.__module__[16:]
    else:
        mod_name = function.__module__
    fstr = "Function %s.%s took %.{0}f seconds to execute".format(sys.float_info.dig)
    log.profile(fstr, mod_name, function.__name__, end_time - start_time)
    return ret


# Traceback (UnicodeEncodeError)
ID: test1
Function: file.recurse
Name: /root/group2test
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 1746, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1703, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2807, in recurse
manage_file(dest, src)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2685, in manage_file
**pass_kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 1814, in managed
__env__
File "/usr/lib/python2.6/site-packages/salt/modules/file.py", line 3490, in source_list
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-34: ordinal not in range(128)
Started: 20:08:21.608398
Duration: 1467.811 ms
Changes:

# Fixed code
def wrapped(*args, **kwargs):
    if six.PY2:
        return function(
            *salt.utils.data.decode_list(args), **salt.utils.data.decode_dict(kwargs)
        )
    else:
        return function(*args, **kwargs)
# Buggy code
def change_minion_cachedir(
    minion_id,
    cachedir,
    data=None,
    base=None,
):
    """
    Changes the info inside a minion's cachedir entry. The type of cachedir
    must be specified (i.e., 'requested' or 'active'). A dict is also passed in
    which contains the data to be changed.

    Example:

        change_minion_cachedir(
            'myminion',
            'requested',
            {'fingerprint': '26:5c:8c:de:be:fe:89:c0:02:ed:27:65:0e:bb:be:60'},
        )
    """
    if not isinstance(data, dict):
        return False

    if base is None:
        base = __opts__["cachedir"]

    fname = "{0}.p".format(minion_id)
    path = os.path.join(base, cachedir, fname)

    with salt.utils.fopen(path, "r") as fh_:
        cache_data = msgpack.load(fh_)

    cache_data.update(data)

    with salt.utils.fopen(path, "w") as fh_:
        msgpack.dump(cache_data, fh_)


# Traceback (UnicodeEncodeError)
$ salt-call -l trace cloud.full_query
.....
[DEBUG   ] Failed to execute 'ec2.list_nodes_min()' while querying for running nodes: 'ascii' codec can't encode characters in position 70860-70863: ordinal not in range(128)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 2198, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/ec2.py", line 2720, in list_nodes_min
instances = query(params)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/ec2.py", line 345, in query
result.text
UnicodeEncodeError: 'ascii' codec can't encode characters in position 70860-70863: ordinal not in range(128)
......

# Fixed code
def change_minion_cachedir(
    minion_id,
    cachedir,
    data=None,
    base=None,
):
    """
    Changes the info inside a minion's cachedir entry. The type of cachedir
    must be specified (i.e., 'requested' or 'active'). A dict is also passed in
    which contains the data to be changed.

    Example:

        change_minion_cachedir(
            'myminion',
            'requested',
            {'fingerprint': '26:5c:8c:de:be:fe:89:c0:02:ed:27:65:0e:bb:be:60'},
        )
    """
    if not isinstance(data, dict):
        return False

    if base is None:
        base = __opts__["cachedir"]

    fname = "{0}.p".format(minion_id)
    path = os.path.join(base, cachedir, fname)

    with salt.utils.fopen(path, "r") as fh_:
        cache_data = msgpack.load(fh_, encoding=MSGPACK_ENCODING)

    cache_data.update(data)

    with salt.utils.fopen(path, "w") as fh_:
        msgpack.dump(cache_data, fh_, encoding=MSGPACK_ENCODING)
# Buggy code
def destroy(self):
    if hasattr(self, "_monitor") and self._monitor is not None:
        self._monitor.stop()
        self._monitor = None
    if hasattr(self, "_stream"):
        # TODO: Optionally call stream.close() on newer pyzmq? Its broken on some
        self._stream.io_loop.remove_handler(self._stream.socket)
        self._stream.socket.close(0)
    elif hasattr(self, "_socket"):
        self._socket.close(0)
    if hasattr(self, "context") and self.context.closed is False:
        self.context.term()


# Traceback (zmq.error.ZMQError)
salt-call state.apply base.foo
[WARNING ] py.warnings - /usr/local/lib/python3.5/dist-packages/salt/minion.py:652: DeprecationWar
ning: ZMQLoop and zmq.eventloop.ioloop.install are deprecated in pyzmq 17. Special eventloop integ
ration is no longer needed.
io_loop = zmq.eventloop.ioloop.ZMQIOLoop()

Exception ignored in: <bound method AsyncZeroMQReqChannel.__del__ of <salt.transport.zeromq.AsyncZ
eroMQReqChannel object at 0x7f837e616908>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/salt/transport/zeromq.py", line 169, in __del__
self.message_client.destroy()
File "/usr/local/lib/python3.5/dist-packages/salt/transport/zeromq.py", line 862, in destroy
message_client.destroy()
File "/usr/local/lib/python3.5/dist-packages/salt/transport/zeromq.py", line 917, in destroy
self.stream.io_loop.remove_handler(self.stream.socket)
File "/usr/local/lib/python3.5/dist-packages/tornado/ioloop.py", line 735, in remove_handler
fd, obj = self.split_fd(fd)
File "/usr/local/lib/python3.5/dist-packages/tornado/ioloop.py", line 657, in split_fd
return fd.fileno(), fd
File "/usr/local/lib/python3.5/dist-packages/zmq/sugar/socket.py", line 161, in fileno
return self.FD
File "/usr/local/lib/python3.5/dist-packages/zmq/sugar/attrsettr.py", line 45, in __getattr__
return self._get_attr_opt(upper_key, opt)
File "/usr/local/lib/python3.5/dist-packages/zmq/sugar/attrsettr.py", line 49, in _get_attr_opt
return self.get(opt)
File "zmq/backend/cython/socket.pyx", line 477, in zmq.backend.cython.socket.Socket.get
File "zmq/backend/cython/socket.pyx", line 137, in zmq.backend.cython.socket._check_closed
zmq.error.ZMQError: Socket operation on non-socket

# Fixed code
def destroy(self):
    if hasattr(self, "_monitor") and self._monitor is not None:
        self._monitor.stop()
        self._monitor = None
    if hasattr(self, "_stream"):
        self._stream.close(0)
    elif hasattr(self, "_socket"):
        self._socket.close(0)
    if hasattr(self, "context") and self.context.closed is False:
        self.context.term()
# Buggy code
def destroy(self):
    if hasattr(self, "stream") and self.stream is not None:
        # TODO: Optionally call stream.close() on newer pyzmq? It is broken on some.
        if self.stream.socket:
            self.stream.socket.close()
        self.stream.io_loop.remove_handler(self.stream.socket)
        # set this to None, more hacks for messed up pyzmq
        self.stream.socket = None
        self.stream = None
        self.socket.close()
    if self.context.closed is False:
        self.context.term()


# Traceback (zmq.error.ZMQError)
salt-call state.apply base.foo
[WARNING ] py.warnings - /usr/local/lib/python3.5/dist-packages/salt/minion.py:652: DeprecationWar
ning: ZMQLoop and zmq.eventloop.ioloop.install are deprecated in pyzmq 17. Special eventloop integ
ration is no longer needed.
io_loop = zmq.eventloop.ioloop.ZMQIOLoop()

Exception ignored in: <bound method AsyncZeroMQReqChannel.__del__ of <salt.transport.zeromq.AsyncZ
eroMQReqChannel object at 0x7f837e616908>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/salt/transport/zeromq.py", line 169, in __del__
self.message_client.destroy()
File "/usr/local/lib/python3.5/dist-packages/salt/transport/zeromq.py", line 862, in destroy
message_client.destroy()
File "/usr/local/lib/python3.5/dist-packages/salt/transport/zeromq.py", line 917, in destroy
self.stream.io_loop.remove_handler(self.stream.socket)
File "/usr/local/lib/python3.5/dist-packages/tornado/ioloop.py", line 735, in remove_handler
fd, obj = self.split_fd(fd)
File "/usr/local/lib/python3.5/dist-packages/tornado/ioloop.py", line 657, in split_fd
return fd.fileno(), fd
File "/usr/local/lib/python3.5/dist-packages/zmq/sugar/socket.py", line 161, in fileno
return self.FD
File "/usr/local/lib/python3.5/dist-packages/zmq/sugar/attrsettr.py", line 45, in __getattr__
return self._get_attr_opt(upper_key, opt)
File "/usr/local/lib/python3.5/dist-packages/zmq/sugar/attrsettr.py", line 49, in _get_attr_opt
return self.get(opt)
File "zmq/backend/cython/socket.pyx", line 477, in zmq.backend.cython.socket.Socket.get
File "zmq/backend/cython/socket.pyx", line 137, in zmq.backend.cython.socket._check_closed
zmq.error.ZMQError: Socket operation on non-socket

# Fixed code
def destroy(self):
    if hasattr(self, "stream") and self.stream is not None:
        self.stream.close()
        self.socket = None
        self.stream = None
    if self.context.closed is False:
        self.context.term()
# Buggy code
def post(self, tag):  # pylint: disable=arguments-differ
    body = self.request.body
    headers = self.request.headers
    payload = {"headers": headers, "body": body}
    fire("salt/engines/hook/" + tag, payload)


# Traceback (TypeError)
2018-01-21 21:52:25,664 [tornado.application][ERROR   ][31253] Uncaught exception POST /prometheus/alertmanager (127.0.0.1)
HTTPServerRequest(protocol='http', host='localhost:8000', method='POST', uri='/prometheus/alertmanager', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Host': 'localhost:8000', 'User-Agent': 'Alertmanager/0.9.1', 'Content-Type': 'application/json', 'Content-Length': '850', 'Accept-Encoding': 'gzip'})
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/tornado/web.py", line 1509, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "/usr/lib/python2.7/site-packages/salt/engines/webhook.py", line 74, in post
fire('salt/engines/hook/' + tag, payload)
File "/usr/lib/python2.7/site-packages/salt/engines/webhook.py", line 65, in fire
fire_master(msg, tag)
File "/usr/lib/python2.7/site-packages/salt/utils/event.py", line 714, in fire_event
dump_data = self.serial.dumps(data)
File "/usr/lib/python2.7/site-packages/salt/payload.py", line 181, in dumps
return msgpack.dumps(msg, use_bin_type=use_bin_type)
File "/usr/lib/python2.7/site-packages/msgpack/__init__.py", line 47, in packb
return Packer(**kwargs).pack(o)
File "msgpack/_packer.pyx", line 274, in msgpack._packer.Packer.pack
File "msgpack/_packer.pyx", line 276, in msgpack._packer.Packer.pack
File "msgpack/_packer.pyx", line 224, in msgpack._packer.Packer._pack
File "msgpack/_packer.pyx", line 271, in msgpack._packer.Packer._pack
TypeError: can't serialize <tornado.httputil.HTTPHeaders object at 0x6005353be490>
2018-01-21 21:52:25,665 [tornado.access   ][ERROR   ][31253] 500 POST /prometheus/alertmanager (127.0.0.1) 1.90ms

# Fixed code
def post(self, tag):  # pylint: disable=arguments-differ
    body = self.request.body
    headers = self.request.headers
    payload = {
        "headers": headers if isinstance(headers, dict) else dict(headers),
        "body": body,
    }
    fire("salt/engines/hook/" + tag, payload)
# Buggy code
def _failed_compile(msg):
    log.error(msg)
    ret.setdefault("errors", {})[short_path_name] = [msg]
    return False


# Traceback (AttributeError)
salt my_win_minion pkg.refresh_db
mywin_minion:
The minion function caused an exception: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt\minion.py", line 1470, in _thread_return
return_data = executor.execute()
File "c:\salt\bin\lib\site-packages\salt\executors\direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "c:\salt\bin\lib\site-packages\salt\modules\win_pkg.py", line 605, in refresh_db
return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)
File "c:\salt\bin\lib\site-packages\salt\modules\win_pkg.py", line 761, in genrepo
successful_verbose
File "c:\salt\bin\lib\site-packages\salt\modules\win_pkg.py", line 829, in _repo_process_pkg_sls
for pkgname, versions in six.iteritems(config):
File "c:\salt\bin\lib\site-packages\salt\ext\six.py", line 606, in iteritems
return d.iteritems(**kw)
AttributeError: 'str' object has no attribute 'iteritems'

# Fixed code
def _failed_compile(prefix_msg, error_msg):
    log.error("{0} '{1}': {2} ".format(prefix_msg, short_path_name, error_msg))
    ret.setdefault("errors", {})[short_path_name] = [
        "{0}, {1} ".format(prefix_msg, error_msg)
    ]
    return False
# Buggy code
def __init__(self, opts, pillar=None, wrapper=None, fsclient=None):
    self.client = fsclient
    salt.state.BaseHighState.__init__(self, opts)
    self.state = SSHState(opts, pillar, wrapper)
    self.matcher = salt.minion.Matcher(self.opts)
    self.tops = salt.loader.tops(self.opts)


# Traceback (AttributeError)
root@1404-salt-master ~/.ssh # salt-ssh '*' state.highstate test=True
[CRITICAL] Rendering SLS base.users failed, render error: 'NoneType' object has no attribute 'building_highstate'
zabbix-server:
- Rendering SLS base.users failed, render error: 'NoneType' object has no attribute 'building_highstate'
- Traceback (most recent call last):
-   File "/usr/lib/python2.7/dist-packages/salt/state.py", line 2455, in render_state
-     sls, rendered_sls=mods
-   File "/usr/lib/python2.7/dist-packages/salt/template.py", line 84, in compile_template
-     ret = render(input_data, saltenv, sls, **render_kwargs)
-   File "/usr/lib/python2.7/dist-packages/salt/renderers/pydsl.py", line 358, in render
-     dsl_sls = pydsl.Sls(sls, saltenv, rendered_sls)
-   File "/usr/lib/python2.7/dist-packages/salt/utils/pydsl.py", line 117, in __init__
-     self.included_highstate = HighState.get_active().building_highstate
- AttributeError: 'NoneType' object has no attribute 'building_highstate'
root@1404-salt-master ~/.ssh # salt 'zabbix-server' state.highstate test=True
zabbix-server:
----------
ID: basic-packages
Function: pkg.installed
Result: None
Comment: The following packages are set to be installed/updated: sshfs, ncdu, zip.
Started: 14:47:40.732026
Duration: 971.393 ms
Changes:
----------
…

Summary
-------------
Succeeded: 38 (unchanged=38, changed=23)
Failed:     0
-------------
Total states run:     38

# Fixed code
def __init__(self, opts, pillar=None, wrapper=None, fsclient=None):
    self.client = fsclient
    salt.state.BaseHighState.__init__(self, opts)
    self.state = SSHState(opts, pillar, wrapper)
    self.matcher = salt.minion.Matcher(self.opts)
    self.tops = salt.loader.tops(self.opts)

    self._pydsl_all_decls = {}
    self._pydsl_render_stack = []
# Buggy code
def show_highstate():
    """
    Retrieve the highstate data from the salt master and display it

    CLI Example:

    .. code-block:: bash

        salt '*' state.show_highstate
    """
    __opts__["grains"] = __grains__
    st_ = salt.client.ssh.state.SSHHighState(
        __opts__, __pillar__, __salt__, __context__["fileclient"]
    )
    return st_.compile_highstate()


# Traceback (AttributeError)
root@1404-salt-master ~/.ssh # salt-ssh '*' state.highstate test=True
[CRITICAL] Rendering SLS base.users failed, render error: 'NoneType' object has no attribute 'building_highstate'
zabbix-server:
- Rendering SLS base.users failed, render error: 'NoneType' object has no attribute 'building_highstate'
- Traceback (most recent call last):
-   File "/usr/lib/python2.7/dist-packages/salt/state.py", line 2455, in render_state
-     sls, rendered_sls=mods
-   File "/usr/lib/python2.7/dist-packages/salt/template.py", line 84, in compile_template
-     ret = render(input_data, saltenv, sls, **render_kwargs)
-   File "/usr/lib/python2.7/dist-packages/salt/renderers/pydsl.py", line 358, in render
-     dsl_sls = pydsl.Sls(sls, saltenv, rendered_sls)
-   File "/usr/lib/python2.7/dist-packages/salt/utils/pydsl.py", line 117, in __init__
-     self.included_highstate = HighState.get_active().building_highstate
- AttributeError: 'NoneType' object has no attribute 'building_highstate'
root@1404-salt-master ~/.ssh # salt 'zabbix-server' state.highstate test=True
zabbix-server:
----------
ID: basic-packages
Function: pkg.installed
Result: None
Comment: The following packages are set to be installed/updated: sshfs, ncdu, zip.
Started: 14:47:40.732026
Duration: 971.393 ms
Changes:
----------
…

Summary
-------------
Succeeded: 38 (unchanged=38, changed=23)
Failed:     0
-------------
Total states run:     38

# Fixed code
def show_highstate():
    """
    Retrieve the highstate data from the salt master and display it

    CLI Example:

    .. code-block:: bash

        salt '*' state.show_highstate
    """
    __opts__["grains"] = __grains__
    st_ = salt.client.ssh.state.SSHHighState(
        __opts__, __pillar__, __salt__, __context__["fileclient"]
    )
    st_.push_active()
    chunks = st_.compile_highstate()
    _cleanup_slsmod_high_data(chunks)
    return chunks
# Buggy code
def show_lowstate():
    """
    List out the low data that will be applied to this minion

    CLI Example:

    .. code-block:: bash

        salt '*' state.show_lowstate
    """
    __opts__["grains"] = __grains__
    st_ = salt.client.ssh.state.SSHHighState(
        __opts__, __pillar__, __salt__, __context__["fileclient"]
    )
    return st_.compile_low_chunks()


# Traceback (AttributeError)
root@1404-salt-master ~/.ssh # salt-ssh '*' state.highstate test=True
[CRITICAL] Rendering SLS base.users failed, render error: 'NoneType' object has no attribute 'building_highstate'
zabbix-server:
- Rendering SLS base.users failed, render error: 'NoneType' object has no attribute 'building_highstate'
- Traceback (most recent call last):
-   File "/usr/lib/python2.7/dist-packages/salt/state.py", line 2455, in render_state
-     sls, rendered_sls=mods
-   File "/usr/lib/python2.7/dist-packages/salt/template.py", line 84, in compile_template
-     ret = render(input_data, saltenv, sls, **render_kwargs)
-   File "/usr/lib/python2.7/dist-packages/salt/renderers/pydsl.py", line 358, in render
-     dsl_sls = pydsl.Sls(sls, saltenv, rendered_sls)
-   File "/usr/lib/python2.7/dist-packages/salt/utils/pydsl.py", line 117, in __init__
-     self.included_highstate = HighState.get_active().building_highstate
- AttributeError: 'NoneType' object has no attribute 'building_highstate'
root@1404-salt-master ~/.ssh # salt 'zabbix-server' state.highstate test=True
zabbix-server:
----------
ID: basic-packages
Function: pkg.installed
Result: None
Comment: The following packages are set to be installed/updated: sshfs, ncdu, zip.
Started: 14:47:40.732026
Duration: 971.393 ms
Changes:
----------
…

Summary
-------------
Succeeded: 38 (unchanged=38, changed=23)
Failed:     0
-------------
Total states run:     38

# Fixed code
def show_lowstate():
    """
    List out the low data that will be applied to this minion

    CLI Example:

    .. code-block:: bash

        salt '*' state.show_lowstate
    """
    __opts__["grains"] = __grains__
    st_ = salt.client.ssh.state.SSHHighState(
        __opts__, __pillar__, __salt__, __context__["fileclient"]
    )
    st_.push_active()
    chunks = st_.compile_low_chunks()
    _cleanup_slsmod_low_data(chunks)
    return chunks
# Buggy code
def _windows_wwns():
    """
    Return Fibre Channel port WWNs from a Windows host.
    """
    ps_cmd = r'Get-WmiObject -class MSFC_FibrePortHBAAttributes -namespace "root\WMI" | Select -Expandproperty Attributes | %{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""}'

    ret = []

    cmdret = __salt__["cmd.run_ps"](ps_cmd)

    for line in cmdret:
        ret.append(line.rstrip())

    return ret


# Traceback (ValueError)
[INFO    ] Executing command 'Powershell -NonInteractive -NoProfile "Get-WmiObject -class MSFC_FibrePortHBAAttributes -namespace \"root\WMI\" | Select -Expandproperty Attributes | %{($_.PortWWN | % {\"{0:x2}\" -f $_}) -join \"\"} | ConvertTo-JSON"' in directory 'C:\Users\Shane'
[ERROR   ] Command 'Get-WmiObject -class MSFC_FibrePortHBAAttributes -namespace "root\WMI" | Select -Expandproperty Attributes | %{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""} | ConvertTo-JSON' failed with return code: 1
[ERROR   ] output: Get-WmiObject : Not supported
At line:1 char:1
+ Get-WmiObject -class MSFC_FibrePortHBAAttributes -namespace "root\WMI ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
[ERROR   ] Error converting PowerShell JSON return
Traceback (most recent call last):
File "c:\salt-dev\salt\salt\modules\cmdmod.py", line 3266, in powershell
return json.loads(response)
File "c:\python27\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "c:\python27\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "c:\python27\lib\json\decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

# Fixed code
def _windows_wwns():
    """
    Return Fibre Channel port WWNs from a Windows host.
    """
    ps_cmd = r'Get-WmiObject -ErrorAction Stop -class MSFC_FibrePortHBAAttributes -namespace "root\WMI" | Select -Expandproperty Attributes | %{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""}'

    ret = []

    cmdret = __salt__["cmd.run_ps"](ps_cmd)

    for line in cmdret:
        ret.append(line.rstrip())

    return ret
# Buggy code
def urlencoded_processor(entity):
    """
    Accept x-www-form-urlencoded data (run through CherryPy's formatter)
    and reformat it into a Low State data structure.

    Since we can't easily represent complicated data structures with
    key-value pairs, any more complicated requirements (e.g. compound
    commands) must instead be delivered via JSON or YAML.

    For example::

    .. code-block:: bash

        curl -si localhost:8000 -d client=local -d tgt='*' \\
                -d fun='test.kwarg' -d arg='one=1' -d arg='two=2'

    :param entity: raw POST data
    """
    if six.PY3:
        # https://github.com/cherrypy/cherrypy/pull/1572
        contents = six.StringIO()
        entity.fp.read(fp_out=contents)
        contents.seek(0)
        body_str = contents.read()
        body_bytes = salt.utils.stringutils.to_bytes(body_str)
        body_bytes = six.BytesIO(body_bytes)
        body_bytes.seek(0)
        # Patch fp
        entity.fp = body_bytes
        del contents
    # First call out to CherryPy's default processor
    cherrypy._cpreqbody.process_urlencoded(entity)
    cherrypy._cpreqbody.process_urlencoded(entity)
    cherrypy.serving.request.unserialized_data = entity.params
    cherrypy.serving.request.raw_body = ""


# Traceback (AttributeError)
2017-10-04 21:14:12,457 [cherrypy.error                           :219 ][ERROR   ][8155] [04/Oct/2017:21:14:12] ENGINE Error in background task thread function <bound method Autoreloader.run of <cherrypy.process.plugins.Autoreloader object at 0x7f03d2d2e320>>.
AttributeError: cffi library '_constant_time' has no function, constant or global variable named '__loader__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 519, in run
self.function(*self.args, **self.kwargs)
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 651, in run
for filename in self.sysfiles() | self.files:
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 635, in sysfiles
hasattr(m, '__loader__') and
SystemError: <built-in function hasattr> returned a result with an error set

# Fixed code
def urlencoded_processor(entity):
    """
    Accept x-www-form-urlencoded data (run through CherryPy's formatter)
    and reformat it into a Low State data structure.

    Since we can't easily represent complicated data structures with
    key-value pairs, any more complicated requirements (e.g. compound
    commands) must instead be delivered via JSON or YAML.

    For example::

    .. code-block:: bash

        curl -si localhost:8000 -d client=local -d tgt='*' \\
                -d fun='test.kwarg' -d arg='one=1' -d arg='two=2'

    :param entity: raw POST data
    """
    # First call out to CherryPy's default processor
    cherrypy._cpreqbody.process_urlencoded(entity)
    cherrypy._cpreqbody.process_urlencoded(entity)
    cherrypy.serving.request.unserialized_data = entity.params
    cherrypy.serving.request.raw_body = ""
# Buggy code
def json_processor(entity):
    """
    Unserialize raw POST data in JSON format to a Python data structure.

    :param entity: raw POST data
    """
    if six.PY2:
        body = entity.fp.read()
    else:
        # https://github.com/cherrypy/cherrypy/pull/1572
        contents = six.StringIO()
        body = entity.fp.read(fp_out=contents)
        contents.seek(0)
        body = contents.read()
        del contents
    try:
        cherrypy.serving.request.unserialized_data = json.loads(body)
    except ValueError:
        raise cherrypy.HTTPError(400, "Invalid JSON document")

    cherrypy.serving.request.raw_body = body


# Traceback (AttributeError)
2017-10-04 21:14:12,457 [cherrypy.error                           :219 ][ERROR   ][8155] [04/Oct/2017:21:14:12] ENGINE Error in background task thread function <bound method Autoreloader.run of <cherrypy.process.plugins.Autoreloader object at 0x7f03d2d2e320>>.
AttributeError: cffi library '_constant_time' has no function, constant or global variable named '__loader__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 519, in run
self.function(*self.args, **self.kwargs)
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 651, in run
for filename in self.sysfiles() | self.files:
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 635, in sysfiles
hasattr(m, '__loader__') and
SystemError: <built-in function hasattr> returned a result with an error set

# Fixed code
def json_processor(entity):
    """
    Unserialize raw POST data in JSON format to a Python data structure.

    :param entity: raw POST data
    """
    if six.PY2:
        body = entity.fp.read()
    else:
        # https://github.com/cherrypy/cherrypy/pull/1572
        contents = BytesIO()
        body = entity.fp.read(fp_out=contents)
        contents.seek(0)
        body = salt.utils.stringutils.to_unicode(contents.read())
        del contents
    try:
        cherrypy.serving.request.unserialized_data = json.loads(body)
    except ValueError:
        raise cherrypy.HTTPError(400, "Invalid JSON document")

    cherrypy.serving.request.raw_body = body
# Buggy code
def yaml_processor(entity):
    """
    Unserialize raw POST data in YAML format to a Python data structure.

    :param entity: raw POST data
    """
    if six.PY2:
        body = entity.fp.read()
    else:
        # https://github.com/cherrypy/cherrypy/pull/1572
        contents = six.StringIO()
        body = entity.fp.read(fp_out=contents)
        contents.seek(0)
        body = contents.read()
    try:
        cherrypy.serving.request.unserialized_data = yaml.safe_load(body)
    except ValueError:
        raise cherrypy.HTTPError(400, "Invalid YAML document")

    cherrypy.serving.request.raw_body = body


# Traceback (AttributeError)
2017-10-04 21:14:12,457 [cherrypy.error                           :219 ][ERROR   ][8155] [04/Oct/2017:21:14:12] ENGINE Error in background task thread function <bound method Autoreloader.run of <cherrypy.process.plugins.Autoreloader object at 0x7f03d2d2e320>>.
AttributeError: cffi library '_constant_time' has no function, constant or global variable named '__loader__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 519, in run
self.function(*self.args, **self.kwargs)
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 651, in run
for filename in self.sysfiles() | self.files:
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 635, in sysfiles
hasattr(m, '__loader__') and
SystemError: <built-in function hasattr> returned a result with an error set

# Fixed code
def yaml_processor(entity):
    """
    Unserialize raw POST data in YAML format to a Python data structure.

    :param entity: raw POST data
    """
    if six.PY2:
        body = entity.fp.read()
    else:
        # https://github.com/cherrypy/cherrypy/pull/1572
        contents = BytesIO()
        body = entity.fp.read(fp_out=contents)
        contents.seek(0)
        body = salt.utils.stringutils.to_unicode(contents.read())
    try:
        cherrypy.serving.request.unserialized_data = yaml.safe_load(body)
    except ValueError:
        raise cherrypy.HTTPError(400, "Invalid YAML document")

    cherrypy.serving.request.raw_body = body
# Buggy code
def text_processor(entity):
    """
    Attempt to unserialize plain text as JSON

    Some large services still send JSON with a text/plain Content-Type. Those
    services are bad and should feel bad.

    :param entity: raw POST data
    """
    if six.PY2:
        body = entity.fp.read()
    else:
        # https://github.com/cherrypy/cherrypy/pull/1572
        contents = six.StringIO()
        body = entity.fp.read(fp_out=contents)
        contents.seek(0)
        body = contents.read()
    try:
        cherrypy.serving.request.unserialized_data = json.loads(body)
    except ValueError:
        cherrypy.serving.request.unserialized_data = body

    cherrypy.serving.request.raw_body = body


# Traceback (AttributeError)
2017-10-04 21:14:12,457 [cherrypy.error                           :219 ][ERROR   ][8155] [04/Oct/2017:21:14:12] ENGINE Error in background task thread function <bound method Autoreloader.run of <cherrypy.process.plugins.Autoreloader object at 0x7f03d2d2e320>>.
AttributeError: cffi library '_constant_time' has no function, constant or global variable named '__loader__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 519, in run
self.function(*self.args, **self.kwargs)
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 651, in run
for filename in self.sysfiles() | self.files:
File "/tmp/tmp.LDk01pqr8F/lib/python3.5/site-packages/cherrypy/process/plugins.py", line 635, in sysfiles
hasattr(m, '__loader__') and
SystemError: <built-in function hasattr> returned a result with an error set

# Fixed code
def text_processor(entity):
    """
    Attempt to unserialize plain text as JSON

    Some large services still send JSON with a text/plain Content-Type. Those
    services are bad and should feel bad.

    :param entity: raw POST data
    """
    if six.PY2:
        body = entity.fp.read()
    else:
        # https://github.com/cherrypy/cherrypy/pull/1572
        contents = BytesIO()
        body = entity.fp.read(fp_out=contents)
        contents.seek(0)
        body = salt.utils.stringutils.to_unicode(contents.read())
    try:
        cherrypy.serving.request.unserialized_data = json.loads(body)
    except ValueError:
        cherrypy.serving.request.unserialized_data = body

    cherrypy.serving.request.raw_body = body
# Buggy code
def update_pricing(kwargs=None, call=None):
    """
    Download most recent pricing information from GCE and save locally

    CLI Examples:

    .. code-block:: bash

        salt-cloud -f update_pricing my-gce-config

    .. versionadded:: 2015.8.0
    """
    url = "https://cloudpricingcalculator.appspot.com/static/data/pricelist.json"
    price_json = http.query(url, decode=True, decode_type="json")

    outfile = os.path.join(__opts__["cachedir"], "gce-pricing.p")
    with salt.utils.fopen(outfile, "w") as fho:
        msgpack.dump(price_json["dict"], fho)

    return True


# Traceback (IOError)
self.cc.action(fun='update_pricing', provider='gce')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 492, in action
return mapper.do_function(provider, fun, kwargs)
File "/usr/local/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 1615, in do_function
driver: self.clouds[fun](call='function')
File "/usr/local/lib/python2.7/dist-packages/salt/cloud/clouds/gce.py", line 2629, in update_pricing
with salt.utils.fopen(outfile, 'w') as fho:
File "/usr/local/lib/python2.7/dist-packages/salt/utils/__init__.py", line 1373, in fopen
fhandle = open(*args, **kwargs)  # pylint: disable=resource-leakage
IOError: [Errno 2] No such file or directory: '/var/cache/salt/cloud/gce-pricing.p'

# Fixed code
def update_pricing(kwargs=None, call=None):
    """
    Download most recent pricing information from GCE and save locally

    CLI Examples:

    .. code-block:: bash

        salt-cloud -f update_pricing my-gce-config

    .. versionadded:: 2015.8.0
    """
    url = "https://cloudpricingcalculator.appspot.com/static/data/pricelist.json"
    price_json = http.query(url, decode=True, decode_type="json")

    if not os.path.exists(__opts__["cachedir"]):
        os.makedirs(__opts__["cachedir"])

    outfile = os.path.join(__opts__["cachedir"], "gce-pricing.p")
    with salt.utils.fopen(outfile, "w") as fho:
        msgpack.dump(price_json["dict"], fho)

    return True