Blog posts for tags/python

  1. Recognize connection errors

    Lately I've been dealing with an asynchronous TCP client app which sends messages to a remote server. Some of these messages are important, and cannot get lost. Because the connection may drop at any time, I had to implement a mechanism to resend the message once the client reconnects. As such, I needed a way to identify what constitutes a connection error.

    Python provides a builtin ConnectionError exception precisely for this purpose, but it turns out it's not enough. After observing logs in production, I found some errors that were not related to the socket connection per se, but rather to the system connectivity, like ENETUNREACH ("network unreachable") or ENETDOWN ("network down"). It's interesting to note how this distinction is reflected in the UNIX errno code prefixes: ECONN* (connection errors) vs. ENET* (network errors). I've noticed ENET* errors usually occur on a DHCP renewal, or more in general when the Wi-Fi signal is weak or absent. Because this code runs on a cleaning robot which constantly moves around the house, connection can become unstable when the robot gets far from the Wi-Fi Access Point, so it's pretty common to bump into errors like these:

    File "/usr/lib/python3.7/ssl.py", line 934, in send
        return self._sslobj.write(data)
    OSError: [Errno 101] Network is unreachable
    
    File "/usr/lib/python3.7/socket.py", line 222, in getaddrinfo
        for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    socket.gaierror: [Errno -3] Temporary failure in name resolution
    
    File "/usr/lib/python3.7/ssl.py", line 934, in send
        return self._sslobj.write(data)
    BrokenPipeError: [Errno 32] Broken pipe
    
    File "/usr/lib/python3.7/ssl.py", line 934, in send
        return self._sslobj.write(data)
    socket.timeout: The write operation timed out
    

    Production logs also revealed a considerable amount of SSL-related errors. I was uncertain what to do about those. The app is supposed to gracefully handle them, so theoretically they should represent a bug. Still, they are unequivocally related to the connection stream, and represent a failed attempt to send data, so we want to retry it. Example of logs I found:

    File "/usr/lib/python3.7/ssl.py", line 934, in send
        return self._sslobj.write(data)
    ssl.SSLZeroReturnError: TLS/SSL connection has been closed (EOF)
    
    File "/usr/lib/python3.7/ssl.py", line 934, in send
        return self._sslobj.write(data)
    ssl.SSLError: [SSL: BAD_LENGTH] bad length
    

    Looking at production logs revealed what sort of brutal, rough and tumble place the Internet is, and how a network app must be ready to handle all sorts of unexpected error conditions which hardly show up during testing. To handle all of these cases I came up with this solution which I think is worth sharing, as it's generic enough to be reused in similar situations. If needed, this can be easily extended to include specific exceptions of third party libraries, like requests.exceptions.ConnectionError.

    import errno, socket, ssl
    
    # Network errors, usually related to DHCP or wpa_supplicant (Wi-Fi).
    NETWORK_ERRNOS = frozenset((
        errno.ENETUNREACH,  # "Network is unreachable"
        errno.ENETDOWN,  # "Network is down"
        errno.ENETRESET,  # "Network dropped connection on reset"
        errno.ENONET,  # "Machine is not on the network"
    ))
    
    def is_connection_err(exc):
        """Return True if an exception is connection-related."""
        if isinstance(exc, ConnectionError):
            # https://docs.python.org/3/library/exceptions.html#ConnectionError
            # ConnectionError includes:
            # * BrokenPipeError (EPIPE, ESHUTDOWN)
            # * ConnectionAbortedError (ECONNABORTED)
            # * ConnectionRefusedError (ECONNREFUSED)
            # * ConnectionResetError (ECONNRESET)
            return True
        if isinstance(exc, socket.gaierror):
            # failed DNS resolution on connect()
            return True
        if isinstance(exc, (socket.timeout, TimeoutError)):
            # timeout on connect(), recv(), send()
            return True
        if isinstance(exc, OSError):
            # ENOTCONN == "Transport endpoint is not connected"
            return (exc.errno in NETWORK_ERRNOS) or (exc.errno == errno.ENOTCONN)
        if isinstance(exc, ssl.SSLError):
            # Let's consider any SSL error a connection error. Usually this is:
            # * ssl.SSLZeroReturnError: "TLS/SSL connection has been closed"
            # * ssl.SSLError: [SSL: BAD_LENGTH]
            return True
        return False
    

    To use it:

    try:
        sock.sendall(b"hello there")
    except Exception as err:
        if is_connection_err(err):
            schedule_on_reconnect(lambda: sock.sendall(b"hello there"))
        raise
    
  2. Sublime Text: remember cursor position plugin

    My editor of choice for Python development is Sublime Text. It has been for a very long time (10 years). It's fast, minimalist and straight to the point, which is why I always resisted the temptation to use more advanced and modern IDEs such as PyCharm or VS code, which admittedly have superior auto-completion and refactoring tools.

    There is a very simple feature I've always missed in ST: the possibility to "remember" / save the cursor position when a file is closed. The only plugin promising to do such a thing is called BufferScroll, but for some reason it ceased working for me at some point. I spent a considerable amount of time Googling for an alternative but, to my surprise, I couldn't find any plugin which implements such a simple feature. Therefore today I decided to bite the bullet and try to implement this myself, by writing my first ST plugin, which I paste below.

    What it does is this:

    • every time a file is closed, save the cursor position (x and y axis) to a JSON file
    • if that same file is re-opened, restore the cursor at that position

    What's neat about ST plugins is that they are just Python files which you can install by copying them in ST's config directory. On Linux you can copy the script below in:

    ~/.config/sublime-text-3/Packages/User/cursor_positions.py

    ...and will work out of the box. This is exactly the kind of minimalism which I love about ST, and which I've always missed in other IDEs.

    # cursor_positions.py
    
    """
    A plugin for SublimeText which saves (remembers) cursor position when
    a file is closed.
    Install it by copying this file in ~/.config/sublime-text-3/Packages/User/
    directory (Linux).
    
    Author: Giampaolo Rodola'
    License: MIT
    """
    
    import datetime
    import json
    import os
    import tempfile
    import threading
    
    import sublime
    import sublime_plugin
    
    
    SUBLIME_ROOT = os.path.realpath(os.path.join(sublime.packages_path(), '..'))
    SESSION_FILE = os.path.join(
        SUBLIME_ROOT, "Local", "cursor_positions.session.json")
    # when reading the session file on startup, we'll remove entries
    # older than X days
    RM_FILE_OLDER_THAN_DAYS = 180
    
    
    def log(*args):
        print("    %s: " % os.path.basename(__file__), end="")
        print(*args)
    
    
    class Session:
    
        def __init__(self):
            self._lock = threading.Lock()
            os.makedirs(os.path.dirname(SESSION_FILE), exist_ok=True)
            self.prune_old_entries()
    
        # --- file
    
        def read_session_file(self):
            try:
                with self._lock:
                    with open(SESSION_FILE, "r") as f:
                        return json.load(f)
            except (FileNotFoundError, json.decoder.JSONDecodeError):
                return {}
    
        def write_session_file(self, d):
            # Use the same FS so that the move operation is atomic:
            # https://stackoverflow.com/a/18706666
            with tempfile.NamedTemporaryFile(
                    "wt", delete=False, dir=os.path.dirname(SESSION_FILE)) as f:
                f.write(json.dumps(d, indent=4, sort_keys=True))
            with self._lock:
                os.rename(f.name, SESSION_FILE)
    
        def prune_old_entries(self):
            old = self.read_session_file()
            new = old.copy()
            now = datetime.datetime.now()
            for file, entry in old.items():
                tstamp = entry["last_update"]
                last_update = datetime.datetime.strptime(
                    tstamp, '%Y-%m-%d %H:%M:%S.%f')
                delta_days = (now - last_update).days
                if delta_days > RM_FILE_OLDER_THAN_DAYS:
                    log("removing old saved file %r" % file)
                    del new[file]
            if new != old:
                self.write_session_file(new)
    
        # --- operations
    
        def add_entry(self, file, x, y):
            d = self.read_session_file()
            d[file] = dict(
                x=x,
                y=y,
                last_update=str(datetime.datetime.now()),
            )
            self.write_session_file(d)
    
        def load_entry(self, file):
            d = self.read_session_file()
            try:
                return d[file]
            except KeyError:
                return None
    
    
    session = Session()
    
    
    class Events(sublime_plugin.EventListener):
    
        # --- utils
    
        @staticmethod
        def get_cursor_pos(view):
            x, y = view.rowcol(view.sel()[0].begin())
            return x, y
    
        @staticmethod
        def set_cursor_pos(view, x, y):
            pt = view.text_point(x, y)
            view.sel().clear()
            view.sel().add(sublime.Region(pt))
            view.show(pt)
    
        def save_cursor_position(self, view):
            file_name = view.file_name()
            if file_name is None:
                return  # non-existent file
            log("saving cursor position for %s" % file_name)
            x, y = self.get_cursor_pos(view)
            session.add_entry(file_name, x, y)
    
        def load_cursor_position(self, view):
            entry = session.load_entry(view.file_name())
            if entry:
                self.set_cursor_pos(view, entry["x"], entry["y"])
    
        # --- callbacks
    
        def on_close(self, view):
            # called when a file is closed
            self.save_cursor_position(view)
    
        def on_load(self, view):
            # called when a file is opened
            self.load_cursor_position(view)
    
  3. New Pelican website

    Hello there. I present you my new blog / personal website! This is something I've been wanting to do for a very long time, since the old blog hosted at https://grodola.blogspot.com/ was... well, too old. =) This new site is based on Pelican, a static website generator similar to Jekyll. Differently from Jekyll, it uses Python instead of Ruby, and that's why I chose it. It's minimal, straight to the point and I feel I have control of things. This is what Pelican gave me out of the box:

    • blog functionality
    • ability to write content by using reStructuredText
    • RSS & Atom feed
    • easy integration with GitHub pages
    • ability to add comments via Disqus

    To this I added a mailing list (I used feedburner), so that users can subscribe and receive an email every time I make a new blog post. As you can see the website is very simple, but it's exactly what I wanted (minimalism). As for the domain name I opted for gmpy.dev, mostly because I know my name is hard to type and pronounce for non-english speakers. And also because I couldn't come up with a better name. ;)

    GIT-based workflow

    The main reason why I blogged so rarely over the years was mostly because blogger.com provided me no way to edit content in RsT or markdown, and the lack of GIT integration. This made me lazy. With Pelican + GitHub pages the workflow to create and publish new content is very straightforward. I use 2 branches: gh-pages, which is the source code of this web-site, and master, which is where the generated HTML content lives and it is being served by GitHub pages. This is what I do when I have to create a new blog post:

    • under gh-pages branch I create a new file, e.g. content/blog/2020/new-blog-post.rst:
    New blog post
    #############
    
    :date: 2020-06-26
    :tags: announce, python
    
    Hello world!
    
    • commit it:
    git add content/blog/2020/new-blog-post.rst
    git ci -am "new blog post"
    git push
    
    • publish it:
    make github
    

    Within 1 minute or something, GitHub will automatically serve gmpy.dev with the updated content. And this is why I think I will start blogging more often. =) The core of Pelican is pelicanconf.py, which lets you customize a lot of things by remaining independent from the theme. I still ended up modifying the default theme though, writing a customized "archives" view and editing CSS to make the site look better on mobile phones. All in all, I am very satisfied with Pelican, and I'm keen on recommending it to anyone who doesn't need dynamism.

    About me

    I spent most of last year (2019) in China, dating my girlfriend, remote working from a shared office space in Shenzhen, and I even taught some Python to a class of Chinese folks with no previous programming experience. The course was about the basics of the language + basic filesystem operations, and the most difficult thing to explain was indentation. I guess that shows the difference between knowing a language and knowing how to teach it.

    I got back to Italy in December 2020, just before the pandemic occurred. Because of my connections with China, I knew about the incoming pandemic sooner than the rest of my friends, which for a while (until the lockdown) made them think I was crazy. =)

    Since I knew I would be stuck at home for a long time, I bought a quite nice acoustic guitar (Taylor) after many years, and resumed playing (and singing). I learned a bunch of new songs, mostly about Queen, including Bohemian Rhapsody, which is something I've been wanting to do since forever.

    I also spent some time working on a personal project that I'm keeping private for the moment, something to speed up file copies, which follows the experiments I made in BPO-33671. It's still very beta, but I managed to make file copies around 170% faster compared to cp command on Linux, which is pretty impressive (and I think I can push it even further). I will blog about that once I'll have something more solid / stable. Most likely it'll become my next OSS project, even tough I have mixed feelings about that, since the amount of time I'm devoting to psutil is already a lot.

    Speaking of which, today I'm also releasing psutil 5.7.1, which adds support for Windows Nano.

    I guess this is all. Cheers and subscribe!

  4. System load average on Windows in Python

    New psutil 5.6.2 release implements an emulation of os.getloadavg() on Windows which was kindly contributed by Ammar Askar who originally implemented it for cPython's test suite. This idea has been floating around for quite a while. The first proposal dates back to 2010, when psutil was still hosted on Google Code, and it popped up multiple times throughout the years. There was/is a bunch of info on internet mentioning the bits with which it's theoretically possible to do this (the so called System Processor Queue Length), but I couldn't find any real implementation. A Google search tells there is quite some demand for this, but very few tools out there providing this natively (the only one I could find is this sFlowTrend tool and Zabbix), so I'm very happy this finally landed into psutil / Python.

    Other improvements and bugfixes in psutil 5.6.2

    The full list is here but I would like to mention a couple:

    • 1476: the possibility to set process' high I/O priority on Windows
    • 1458: colorized test output. I admit nobody will use this directly but it's very cool and I'm porting it to a bunch of other projects I work on (e.g. pyftpdlib). Also, perhaps this could be a good candidate for a small module to put on PYPI which can also include some functionalities taken from pytest and which I'm gradually re-implementing in unittest module amongst which:
      • 1478: re-running failed tests
      • display test timings/durations: this is something I'm contributing to cPython, see BPO-4080 and and PR-12271

    About me

    I'm currently in China (Shenzhen) for a mix of vacation and work, and I will likely take a break from Open Source for a while (likely 2.5 months, during which I will also go to Philippines and Japan - I love Asia ;-)).

    External

  5. psutil 5.6.0 and process parents

    Hello world =)

    It was a long time since my last blog post (over 1 year and a half). During this time I moved between Italy, Prague and Shenzhen (China), and also contributed a couple of nice patches for Python I want to blog about when Python 3.8 will be out: zero-copy for shutil.copy() functions and socket.create_server() utility function. But let's move on and talk about what this blog post is about: the next major psutil version.

    Process parents()

    From the doc: return the parents of this process as a list of Process instances. If no parents are known return an empty list.

    >>> import psutil
    >>> p = psutil.Process(5312)
    >>> p.parents()
    [psutil.Process(pid=4699, name='bash', started='09:06:44'),
     psutil.Process(pid=4689, name='gnome-terminal-server', started='0:06:44'),
     psutil.Process(pid=1, name='systemd', started='05:56:55')]
    

    Nothing really new here, as it's a convenience method based on the existing parent() method, but still it's something nice to have implemented as a builtin and which can be used to work with process trees in conjunction with children() method. The idea was proposed by Ghislain Le Meur.

    Windows

    A bunch of interesting improvements occurred on Windows.

    The first one is that certain Windows APIs requiring to be dynamically loaded from DLL libraries are now loaded only once on startup (instead of on per function call), significantly speeding up different functions and methods. This is described and implemented in PR #1422 which also provides benchmarks.

    Another one is Process' suspend() and resume() methods. Before they were using CreateToolhelp32Snapshot() to iterate over all process' threads which was somewhat unorthodox and didn't work if process was suspended via Process Hacker. Now it relies on undocumented NtSuspendProcess and NtResumeProcess APIs, which is the same approach used by ProcessHacker and other famous Sysinternals tools. The change was proposed and discussed in issue #1379 and implemented in PR #1435. I think I will later propose the addition of suspend() and resume() method in subprocess module in Python.

    Last nice improvement about Windows it's about SE DEBUG mode. SE DEBUG mode can be seen as a "bit" which you can set on the Python process on startup so that we have more chances of querying processes owned by other users, including many owned by Administrator and Local System. Practically speaking this means we will get less AccessDenied exceptions for low PID processes. It turns out the code doing this has been broken presumably for years, and never set SE DEBUG. This is fixed now and the change was made in PR #1429.

    Removal of Process.memory_maps() on OSX

    This was somewhat controversial. The history about memory_maps() on OSX is a painful one. It was based on an undocumented and probably broken Apple API called proc_regionfilename() which made memory_maps() either randomly raise EINVAL or result in segfault! Also, memory_maps() could only be used for the current process, limiting its usefulness to os.getpid() only. For any other process it raised AccessDenied. This has been a known problem for a long time but sometime over the last few years I got tired of seeing random test failures on Travis that I couldn't reproduce locally, so I commented the unit-test and forget about it until last week, when I realized the real impact this has on production code. I tried looking for a solution once again, spending quite some time looking for public source codes which managed to do this right with no luck. The only tool I'm aware of which does this right is vmmap from Apple, but it's closed source. After careful thinking, since no solution was found, I decided to just remove memory_maps() from OSX. This is not something I took lightly, but considering the alternative is getting a segfault I decided to sacrifice backward compatibility (hence the major version bump).

    Improved exceptions

    One problem which afflicted psutil maintenance over the years was receiving bug reports including tracebacks which didn't provide any information on what syscall failed exactly. This was especially painful on Windows where a single routine can invoke different Windows APIs. Now the OSError (or WindowsError) exception will include the syscall from which the error originated, see PR-#1428.

    Other important bugfixes

    • #1353: process_iter() is now thread safe
    • #1411: [BSD] segfault could occur on Process instantiation
    • #1427: [OSX] Process cmdline() and environ() may erroneously raise OSError on failed malloc().
    • #1447: original exception wasn't turned into NoSuchProcess / AccessDenied exceptions when using Process.oneshot() ctx manager.

    A full list of enhancements and bug fixes is available here.

Page 1 / 5 »

Social

Feeds