Posts

  • How I finally migrated my whole website to the cloud

    This is going to be a tale of blood, sweat and tears, describing what I experienced over multiple years while trying to get rid of maintaining my own servers to host my website. This battle lasted for, literally, over a decade, until I was finally able to migrate every piece of code that comprises it (not just this blog). Since this week, it runs on a cloud infrastructure over multiple providers where I have little to no worries about its maintenance, offers more reliability than I actually need and it’s also pretty cheap.

    The myhro.info domain was registered in April 2007. Initially I had no real intentions of hosting anything on top of it, as it was more like “oh, now I have my first domain!”. In the first years, the web hosting was provided by 000webhost. It was free, but I also had no guarantee about its availability and faced some downtime every once in a while. This continued until, after finding some interesting offers on Low End Box, I migrated it to its own VPS server by the end of 2010. I remember the year because it was my first one at the Information Systems course, around the same time I got my first part-time System Administrator job. The experience I got maintaining my own Linux + Apache + PHP + MySQL (LAMP) server was crucial in the beginning of my professional career and some learnings from the time are still useful to me these days.

    In April 2011 this blog was started on a self-hosted WordPress installation, in the same previously mentioned server. At first I had almost no service to really care about its availability and probably the only exception was the Myhro.info URL Shortener (hosted under the myhro.net domain). The problem is that, after starting a blog, I had to worry about it being online at all times - otherwise people would not be able to read what I spent hours writing.

    Maintaining your own WordPress instance is not an easy job, even for small blogs. I spent endless hours fighting comment spam and keeping the installation secure and up-to-date. It was such a hassle that in less than two years, it was migrated to OctoPress, a static site generator in blog format, in the beginning of 2013. Publishing posts was now a matter of copying HTML files over rsync, but I still had to maintain a HTTP server for it. That’s why this blog was moved to GitHub Pages in 2014 and to Jekyll in 2015 and is still hosted there currently. Now I was free from maintaining a web server for it and this became a GitHub problem. At the same time the blog was migrated to Jekyll, its HTTPS support was re-enabled using Cloudflare (something that was lost in the GitHub Pages migration).

    Migrate blog.myhro.info to GitHub Pages + Cloudflare was marvelous and I haven’t worried about its maintenance ever since - not to mention that it also didn’t cost me a cent to do it. Now I had to take care of other parts of my website that required server-side scripts, like myhro.info/ip: a page that shows visitor’s IP address and user agent in a simple plain text format. It’s really handy to use it in the command line with curl and, in my experience, faster than using ifconfig.me. The main issue with this service is that it was written in PHP.

    I don’t remember exactly when was my first try of migrating the IP page to a cloud service, but it was probably between 2015 and 2016, when I tried AWS Lambda, rewriting it in a supported language. This didn’t worked, as to make a Lambda function available via HTTP, one have to use the Amazon API Gateway and it didn’t offered the possibility of using a simple endpoint like myhro.info/ip. I think this can be achieved with Amazon CloudFront, routing a specific path to a different origin, but it seemed too much work (and involved the usage of a bunch of different services) to achieve something that is really simple in nature. Trying to do the same using Google Cloud Functions yielded a similar experience.

    After these frustrating experiences, I stopped looking for alternatives. Maybe the technology to host a few dynamic pages (in this case, only one) for a website which has most static content wasn’t there yet. Then, after two hopeless years, I read the announcement of Cloudflare Workers which seemed exactly what I wanted: run code on a cloud service to answer specific requests. Finally, after reaching open beta and general availability, in 2018 I could truly and easily deploy small “serverless” applications tightly integrated to an already existing website. For that I just had to learn a little bit of JavaScript.

    It took me years of waiting and a few hours in a weekend to write JavaScript replacements for the PHP and Python (in the end I also migrated heroku.myhro.info, a service that returns random Heroku-style names) implementations, but I had finally reached the Holy Grail. Now it was a matter of moving the static parts of the website to Amazon S3, which is quite straightforward. S3 doesn’t offer HTTPS connections for static websites hosted in there, but as I already used Cloudflare, this was a no-brainer.

    So, Cloudflare Workers aren’t free (the minimum fee is $5/month), neither are they perfect. There are some serious limitations, like the “one worker per domain” restriction on non-Enterprise accounts, that can be a blocker for larger projects. But in this case, where I wanted to have a couple dynamic pages for a mostly static website, they fit perfectly. I’m also happy to pay an amount I consider reasonable for a service I’ve been using for free for years. Looking at the company recent innovations, they may become even better in the future.

  • People, not software, first

    During my first year at the university, I remember asking my Algorithms and Data Structures professor about how to properly handle user input in C. “If we are going to store this input, how we can be sure that the user only types an integer and not a string?”. I don’t actually recall his exact answer, but it was the first time that someone mentioned to me that handling user input is a recurring problem in Computer Science. And this was way before I learned about related problems like database input sanitization.

    Unfortunately, I learned the wrong lesson that day. To me, the problem was that we can’t trust the user, so we have to babysit every step of its human-computer interaction. If we don’t, they will crash our beloved hand-crafted software, which will make us - software developers - sad. And I couldn’t be more wrong. When a piece of software crashes, no one can ever gets sadder than the users who faced an error screen themselves. After all, they needed to use our software and weren’t able to.

    I took a few years to figure this out. Even a little after I’ve graduated at the university, I thought that every software that goes to production should be perfect. Every exception that can be raised in its code should be treated and it cannot ever crash in an unpredictable way. But in the real world, things do not work like this. And guess what? Users don’t care if your software isn’t perfect, as long as it suits their needs. All you have to care is about offering a friendly UI and giving proper feedback when things doesn’t work as expected.

    A couple weeks ago I found (on this post by Julia Evans - her blog is awesome, you should check it out) a series of tweets by Kelsey Hightower. He talks about how his working life got a lot more meaningful when he started to put people first. The part which I like most is when he mentions that computers are just machines waiting to break and that software is worse, because it’s always broken! Accepting that software isn’t just not perfect, but also broken by design, may be the best way to deal with the issues we face everyday in this industry.

    See, I’m not saying that we should be narcissist/nihilist professionals that don’t care about the quality of the work we publish to whomever our users are. I think that maybe, if we treat problems with its proper importance (e.g. pretty serious when it breaks user experience, and not so much if its a known problem that is not user-visible and we can ignore), we can feel a little more proud about the systems we maintain. Otherwise we’ll be doing a Sisyphus job, which can only led to an eternity of useless efforts and unending frustration.

  • Software engineering tips from a DevOps

    There’s a pattern that I’ve observed in nearly every software development company that I worked for. When discussing solutions with developer teams, two distinct things can happen: if it’s something related to operating systems, networking or infrastructure in general, they agree with me almost never arguing against anything. Sometimes this is bad, as I could possibly be missing an important detail which they thought that’s already figured out. On the other hand, when the matter is related to programming and software engineering, they ignore me virtually every time. It’s almost like if I’ve not even said anything meaningful.

    Based on this behavior, I’ve compiled a list of software engineering tips (or best practices) that I urge every developer to follow (and every DevOps/SysAdmin to remember them about it). None of these items were invented by me, nor they are just theoretical things. Those are battle-worn recommendations from someone who is part of this industry for quite a few years, which have seen many things that can go wrong when bad decisions are made. They are not hard to follow, but I’ve seen even experienced developers making the same mistakes mentioned here.

    Do not hardcode configuration parameters

    This one is tempting and source of “works on my machine” symptoms. We know that developers love to have control about what they are creating and sometimes afraid of someone running their software with badly formatted input. This is even worse with configuration parameters: “you put an ‘http://’ in there, please just use the hostname”. So this may be difficult to ask, but please, read configuration parameters from environment variables not only when you should, but every time you can. A default value can not only be useful for a specific environment (e.g. development), but also works as documentation for the expected format. See this Python example:

    import os
    
    database_url = os.environ.get('DATABASE_URL', 'postgres://user:[email protected]/app_db')
    redis_host = os.environ.get('REDIS_HOST', 'localhost')
    

    You can assume some things like “this web app will only run on port 80”, but there isn’t a way to know this for sure when it goes to production. It can be inside a container that have its ports forwarded or not. A reverse proxy can be in front of it and the app server will have to bind to a higher port. If the application can dynamically read this kind of information from its environment, you’ll be making both of our jobs way easier. I won’t have to ask you for changes and you won’t have to change the implementation (or worse, force me to do this).

    Do not try reinvent the wheel

    We all know: software development is great. You can ask a computer to do anything you want and it will do it over and over again. Because of this, you may be attracted by the idea that not only you can do anything, but also get the best possible solution without thinking too much about it. The reality is that this is not going to happen, maybe not even if you are truly a genius. I’ve seen this happening multiple times, specially with parsers for structured text, “things that can be solved with a clever regex” and the like.

    The advice I can do to avoid this is: be humble. Assume that your solution may not work for every case. Actually, the most important part is to realize that if you can’t think about an use case, it doesn’t mean that it doesn’t exist and won’t ever appear. A few weeks from now an edge case can come to bite you. Look for opensource frameworks and libraries that can do what you need. Learn to appreciate the work from people that have been polishing these pieces of software for years - and allowing you to use it for free. Maybe you can even do a significant contribution to make them better.

    Gerald Sussman, the legendary MIT professor who co-authored the SICP book, was once asked about the switch from Scheme (a Lisp dialect) to Python in the Computer Science undergraduate program. His answer was that it made sense, because these days programming is very different from what it was in the 80s and 90s. Today it’s “more like science”, where you grab some libraries and figure if they can do what you want. So, stand on the shoulder of giants and only write from scratch what you really need.

    Opt for rock-solid battle-tested solutions

    This one is related to “not reinventing the wheel”, but it’s more about choosing mature implementations that have a greater chance to work. Sometimes you may be tempted to pick this new framework that everyone is talking about (some of them without having ever touched it), but maybe it is not really ready to be used. Of course someone will have to start using it to prove if it works or not, but you probably don’t want to face the problems these early adopters will hit. At least not on a production environment.

    The same can be said when you need, for instance, a network protocol. Using raw sockets can be fast and fun, but when you application grows a little bit you’ll realize you need a real protocol. Then you will be implementing compression to trade data efficiently, defining a format to receive arguments, etc. In the end, something like GRPC was the answer of all the problems you were trying to solve, but what you got is a stripped-down version of it that wasn’t tested by thousands of other developers around the globe.

    Closing thoughts

    I could list a few more things about this subject, but it’s better if we keep this post short. Unfortunately, I’ve experienced some of the mentioned problems more than once in the last couple months. I’m not an expert in managing people, but one of the causes seems to be closely related to ego reasons. Sometimes I think that this may be naivety, when the person in question can’t see the broader picture of the problem they are facing. At the same time, this is funny because it also happens with multiple-year experienced individuals.

    If you are a developer who identified with at least part of this list, you don’t really need to listen to me. Think about yourself, as a professional in our area, and what you can do to write software that is easy and robust to be executed in different environments. Always remember that your responsibility doesn’t end when you push code in commits to a repository. You are at least responsible as I am for running your code in production. In the end, it’s your creation, right?

  • How SSH authentication works

    A great friend of mine, Diego “Diegão” Guimarães (which also happens to be one of the best programmers I ever met), recently asked me: “why do I have to specify the private key when connecting to an SSH server and not the public one?”. I found this question quite interesting, as it reminds us that even seasoned developers may have doubts about things they use every day. And, of course, it’s always better to ask than accept that “this is just the way it works”.

    Before explaining how SSH authentication is performed, we have to understand how public key cryptography (also known as asymmetric cryptography) takes part in this process. Worth mentioning that SSH authentication can also be done using passwords (and this usually is the default setting), but this won’t be discussed here. If you have a machine where its SSH server accepts passwords as an authentication method, you should probably disable this anyway.

    Public key cryptography works with pairs of keys. A public one, like its name suggests, can be known by anyone. It can be sent to an internet forum or be published as part of a blog post. The only thing you have to worry when facing a public key is that if its owner is really the same person who they affirm to be. Its trustworthiness relies on the fact that no one can impersonate the key owner, i.e., have the private counterpart of a public key pair - but anyone can generate a key and tell you that it’s from someone else.

    But how can you be sure about who is the owner looking at the key itself? The problem is that you can’t. A public (Ed25519) key looks like this:

    ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAII+kwSB7I6nTJ+mqhNMlEzofxa4UaGsU09A8Yk95MU1n [email protected]
    

    This format is pretty straightforward, based on {key algorithm} {base64 representation of the key itself} {comment}. The problem lies in the fact that pairs of keys can be easily generated with ssh-keygen. The “comment” part can even be altered after it was created. You can only be sure about who is the owner by the way you got a public key from someone else. Did they sent it to you via e-mail? Can you call them to confirm that this is the right key? Did you got it in a thumb drive brought to you personally by themselves?

    The core functionality of this whole system is that a piece of information encrypted with a public key can only be decrypted by its private key. The opposite is true as well, as this is how signing works. Based on this cryptographic principle, the authentication process of an SSH connection works (in a simplified view) as follows:

    • The client sends an authentication request, informing the username that will be used to log in.
    • The server responds, telling the client which authentication methods are accepted (e.g. “publickey”, in this case).
    • A message encrypted with the private key (a “signature”) is sent by the client to the server along with its corresponding public key.
    • If this public key is listed as acceptable for authentication (usually as an entry under ~/.ssh/authorized_keys) and the signature is correct, the process is considered successful.

    It’s important to point out that the only way one can generate a valid signature to be checked with a public key is by having the private key itself. That’s the very reason why private keys shouldn’t be shared in any way, even with people you trust. That’s no need for two or more persons to have access to the same private key. Everyone should have its own and the server should be configured to accept all of them.

    We should be aware that there’s a case where the user can be confused about whether the authentication is being done using passwords or public keys: when the private key has a passphrase. To safely store a key, a passphrase can be set to save it in a (symmetric) encrypted format. This also works as another layer of security, as someone who happens to obtain the keyfile would also have to know the passphrase to unlock it. In this situation, ssh-agent can be used to cache this information in order to avoid typing it every time.

    References:

  • Benchmarking IP and Unix domain sockets (for real)

    In a previous post an artificial benchmark was done to measure the performance difference between IP and Unix domain sockets. The results were somewhat impressive, as Unix sockets performing at least twice as fast as IP sockets. But how these two forms of communication behaves in the real-world, using a battle-tested application protocol? Would the throughput really double just by switching between them? We’ll be using a Flask app served by Gunicorn behind an nginx reverse proxy to find out.

    The following tests were executed on a c4.large (2 Cores, 3.75GB RAM) instance on Amazon Web Services (AWS). None of the multi-threading/multi-process options offered by Gunicorn were used, so what we’ve got here was really what it can serve using a single CPU core. This way, we’ll also have the benefit of a free core to run both nginx and the benchmarking (wrk) tool itself.

    The application is pretty close to the standard Flask “hello world” example:

    requirements.txt

    Flask==0.12
    gunicorn==19.6.0
    

    server.py

    from flask import Flask
    app = Flask(__name__)
    
    @app.route("/")
    def hello():
        return "Hello there!"
    
    if __name__ == "__main__":
        app.run()
    

    Gunicorn was used to serve the application with no other option besides --bind.

    • IP: gunicorn --bind 0.0.0.0:8000 server:app
    • Unix domain socket: gunicorn --bind unix:/tmp/gunicorn.sock server:app

    This is the nginx virtual host configuration for both Gunicorn instances:

    /etc/nginx/sites-available/gunicorn

    server {
        listen 80;
        server_name bench-ip.myhro.info;
    
        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_redirect off;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    
    server {
        listen 80;
        server_name bench-unix.myhro.info;
    
        location / {
            proxy_pass http://unix:/tmp/gunicorn.sock;
            proxy_redirect off;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    

    We’ll have to append both hostnames to our /etc/hosts, in order to avoid the need for a DNS server:

    (...)
    127.0.0.1 bench-ip.myhro.info
    127.0.0.1 bench-unix.myhro.info
    

    The parameters used in this benchmark were pretty much what wrk offers by default. Experimenting with more threads or connections didn’t resulted in a significant difference, so the only parameter set was -d5s, which means “send the maximum number of requests as you can during five seconds”.

    IP benchmark

    Running 5s test @ http://bench-ip.myhro.info/
      2 threads and 10 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency     5.44ms  303.33us  11.56ms   99.02%
        Req/Sec     0.92k    16.21     0.96k    66.00%
      9191 requests in 5.00s, 1.60MB read
    Requests/sec:   1837.29
    Transfer/sec:    328.26KB
    

    Unix domain socket benchmark

    Running 5s test @ http://bench-unix.myhro.info/
      2 threads and 10 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency     4.95ms  283.81us  11.25ms   97.96%
        Req/Sec     1.01k    24.75     1.04k    90.00%
      10107 requests in 5.00s, 1.76MB read
    Requests/sec:   2019.39
    Transfer/sec:    360.79KB
    

    During multiple runs, these numbers were consistent. The Unix socket virtual host answered around 5 to 10% more requests in average. This number is small but can be significant, specially when dealing with high traffic web servers answering thousands of requests per minute. Anyway, this isn’t anywhere near the 100% performance improvement we saw when comparing raw sockets instead of a real protocol like HTTP.

    It would still be interesting to compare how this application would perform running inside a Docker container. Docker is known for having network overhead when using forwarded ports, so we’ll see how much it means in this case. Two files will be used to create our application image and its containers:

    Dockerfile

    FROM ubuntu:xenial
    
    RUN apt-get update
    RUN apt-get install -y python-pip
    
    ADD . /app
    
    RUN pip install -r /app/requirements.txt
    
    WORKDIR /app
    

    docker-compose.yml

    version: "2"
    services:
      base:
        build: .
        image: flask
      ip:
        image: flask
        command: gunicorn --bind 0.0.0.0:8000 server:app
        ports:
          - "8000:8000"
        volumes:
          - .:/app
      uds:
        image: flask
        command: gunicorn --bind unix:/tmp/gunicorn.sock server:app
        volumes:
          - .:/app
          - /tmp:/tmp
    

    Let’s run wrk again, after docker-compose build and docker-compose up:

    Docker IP benchmark

    $ wrk -d5s http://bench-ip.myhro.info/
    Running 5s test @ http://bench-ip.myhro.info/
      2 threads and 10 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency     7.03ms  791.63us  16.84ms   93.51%
        Req/Sec   713.54     20.21   747.00     70.00%
      7109 requests in 5.01s, 1.24MB read
    Requests/sec:   1420.17
    Transfer/sec:    253.73KB
    

    Docker Unix domain socket benchmark

    $ wrk -d5s http://bench-unix.myhro.info/
    Running 5s test @ http://bench-unix.myhro.info/
      2 threads and 10 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency     4.94ms  266.67us  10.74ms   97.24%
        Req/Sec     1.02k    29.87     1.04k    95.00%
      10116 requests in 5.00s, 1.76MB read
    Requests/sec:   2022.18
    Transfer/sec:    361.29KB
    

    The difference between IP sockets over forwarded ports and Unix sockets via shared volumes were huge under Docker. 40-45% is a pretty big number when considering web server performance penalty. With a setup like this one, it would be needed almost twice as hardware resources to serve the same number of clients, which would directly reflect on infrastructure and project costs as a whole.

    A few conclusions can be drawn from this experiment:

    • Avoid Docker forwarded ports in production environments. Use either Unix sockets or the host network mode in this case, as it will introduce virtually no overhead.
    • Ports can be easier to manage, instead of a bunch of files, when dealing with multiple processes - either regarding many applications or scaling a single one. If you can afford a little drop in throughput, go for IP sockets.
    • If you have to extract every drop of performance available, use Unix domain sockets where possible.

Subscribe via RSS