Squeezing Rust into production

ยท

Originally published 2017 on my old blog, preserved as-is.

Introducing new languages and frameworks into production use is always a bit of a challenge. With Rust, I've been looking for such an opportunity for some time now and when I saw an opening for it - simple as it was - I rushed to grab it!

So, now our main software line's updater component is made out of ~150 lines of Rust. In lots of ways, it was the ideal first target; there are no cross-code dependencies required. The task is simple enough to be doable in less than a day. The maintenance burden is minimal. There are no runtimes required and the only development requirement is Rust itself, which is installable in a few clicks.

Almost like scripting..

..If you allow the exaggeration.

Rust is a modern general-purpose language, which aims specifically for both high performance and high safety. It's relatively close to the hardware and by most part follows the zero-cost abstraction principle; that abstractions should incur no runtime overhead. It's also statically typed. All of these are generally not traits you want for writing quick, simple applications, but Rust being a modern beast of language, there are lots of small things it does just right from the perspective of making programmer's life a little simpler.

There was an article I read some time back - I believe it was this: Using Rust For Scripting - about someone using Rust for a task where they'd usually use Python. Their main focus was Rust's powerful multiplatform support and easy cross-compilation (complex linking aside). But Rust being a very modern language, there are lots of small things of convenience in it that ten years ago would have felt almost like cheating in a language close to hardware with zero-cost abstractions.

Convenience features include for example the enum type, where the enum variants have their type signature:

use std::env;

fn double_arg(mut argv: env::Args) -> Result<i32, String> {
    argv.nth(1)
        .ok_or("Please give at least one argument".to_owned())
        .and_then(|arg| arg.parse::<i32>().map_err(|err| err.to_string()))
        .map(|n| 2 * n)
}

fn main() {
    match double_arg(env::args()) {
        Ok(n) => println!("{}", n),
        Err(err) => println!("Error: {}", err),
    }
}

As seen above, the builder pattern with method chaining is also common throughout the standard library, leading to more concise code.

There's also pattern matching for Rust's powerful match statement, including bindings, ranges and logic in the match expressions:

let x = 1;

match x {
    e @ 1 ... 5 => println!("got a range element {}", e),
    _ => println!("anything"),
}

These are but a few examples of what's packed in Rust to make code easier to write. With language-level support for ranges, struct destructuring, solid tuple type, pattern matching, a powerful enum construct and so forth, writing Rust feels about as easy as you'd expect when you're working with a language designed to be uncompromising in regards of performance expectations.

One of the coolest things about Rust is its package manager/build system helper glorified, called Cargo. Cargo makes it pretty damn straightforward to describe your project and its dependencies and is generally really nice to work with. You install packages in a single line, you cross-compile with one line, you have out-the-box support for differenting between development and production modes, you describe your project in a simple TOML file.. Stuff which we've started to take for granted with the likes of Node or Java with Maven or Python with its various helpers, but not stuff we're yet accustomed to seeing with languages capable of systems programming.

But this isn't supposed to be about cargo, so let's continue on!

The code

Since it's only a small amount of Rust I've managed to squeeze into a production use for now, I'll present it all here.

It's a software updater, and it's done wrong. I know that - how it should be done is as a Windows service started with admin privileges that communicates with our main software. There are lots of ways how the updater can fail.

However, we don't do end-user facing software. All this goes to only a handful of clients and we can expect that it's very unlikely for anything to go wrong. If something does, we're on the call 24/7.

Why it isn't a simple bash script - well, I want to extend it at some point to check for and download updates on its own as a background service and all that, this was simply the barest minimum I could do for now.

That out the way; here it is:

use std::process::Command;
use std::{thread, time};

fn main() {

    let iterations = 10;
    let wait_time = 500;

    // Back up old old version
    match copy_files("ues2.exe", "ues2.exe_old", "") {
        Ok(_) => println!("Succesfully backed up ues2.exe!"),
        Err(e) => println!("Error backing up ues2.exe: {:?}", e),
    }
    match copy_files("ues2_Data", "ues2_Data_old", "") {
        Ok(_) => println!("Succesfully backed up ues2_Data!"),
        Err(e) => println!("Error backing up ues2_Data: {:?}", e),
    }

    match kill_task("ues2.exe") {
        Ok(_) => println!("Succesfully killed ues2.exe!"),
        Err(e) => print!("Failed to kill ues2.exe.. {:?}", e)
    };

    for _ in 0..iterations {
        let updated_exe = match copy_files("update", ".", "ues2.exe") {
        	Ok(_) =>
            {
                // Maybe we shouldn't delete update files?
                /*
                match remove_file("update\\ues2.exe") {
                    Ok(_) => println!("Succesfully deleted ues2.exe update."),
                    Err(e) => println!("Failed to delete ues2.exe update: {:?}", e)
                };*/

                println!("Succesfully updated ues2.exe!");
                true
            }
        	Err(e) =>
            {
                println!("Error updating ues2.exe: {:?}", e);
                false
            }
        };

        let updated_dir = match copy_files("update/ues2_Data", "ues2_Data", "") {
            Ok(_) =>
            {
                // Maybe we shouldn't delete update files?
                /*match remove_dir("update\\ues2_Data") {
                    Ok(_) => println!("Succesfully deleted ues2_Data update."),
                    Err(e) => println!("Failed to delete ues2_Data update: {:?}", e)
                };*/

                println!("Succesfully updated ues2_Data!");
                true
            }
            Err(e) =>
            {
                println!("Error updating ues2_Data: {:?}", e);
                false
            }
        };

        if !updated_exe || !updated_dir
        {
            kill_task("ues2.exe");
        }

        if updated_exe && updated_dir
        {

            match copy_files("update", ".", "version.json") {
                Ok(_) => println!("Succesfully updated version.json!"),
                Err(e) => println!("Error updating version.json: {:?}", e)
            }
            break;
        }

        let sleep_ms = time::Duration::from_millis(wait_time);
        thread::sleep(sleep_ms);
    }

    Command::new("ues2.exe")
                 .spawn();
}

fn remove_file(source: &str) -> Result<bool, String>
{
    Command::new("del")
        .arg("/f")
        .arg("/q")
        .arg(source)
        .output()
        .map_err(|e| e.to_string());
    Ok(true)
}

fn remove_dir(source: &str) -> Result<bool, String>
{
    Command::new("del")
        .arg("/s")
        .arg("/q")
        .arg(source)
        .output()
        .map_err(|e| e.to_string());
    Ok(true)
}

// Robocopy is weird:
// Source and target are directory paths.
// File is the actual file to copy;
// If file argument isn't provided, Robocy assumes *.* relative to source path.
fn copy_files(source: &str, target: &str, file: &str) -> Result<bool, String> {
    if file.len() <= 0
    {
	   Command::new("robocopy")
                 .arg("/E")
                 .arg("/is")
                 .arg(source)
                 .arg(target)
                 .output()
                 .map_err(|e| e.to_string());
    }
    else {
        Command::new("robocopy")
                 .arg("/E")
                 .arg("/is")
                 .arg(source)
                 .arg(target)
                 .arg(file)
                 .output()
                 .map_err(|e| e.to_string());
    }
	Ok(true)
}

fn kill_task(task: &str) -> Result<bool, String> {
    Command::new("taskkill")
                 .arg("/F")
                 .arg("/IM")
                 .arg(task)
                 .arg("/T")
                 .output()
                 .map_err(|e| e.to_string());

    Ok(true)
}

The code has basically 3 steps;

  1. Wait for main program to shut down and try to repeatedly kill it;
  2. Make a backup of existing files;
  3. Copy update files on top of the current files.

Nothing fancy, and could be done much more reliably and better, but in this case I just wanted something that works for a while before I have the time to look into a longer-lasting solution. And I wanted to see at least a tiny bit of Rust in production!

Looking forward

One thing I will need to do at some point is to extend the updater. It should run as an actual Windows service and it could handle downloading the files for the update itself. Right now the main software downloads the update files and puts them in place and starts the above updater and closes itself down.

There are other uses at where I work for Rust as well. One thing I want to eventually replace with Rust is this audio analysis component, that listens to mic inputs and communicates with our main software over TCP. It would be more ideal use for Rust than a simple software updater, as there are realtime and performance requirements. Right now the audio analysis tool is in Python with Numpy and I find that Python gets very convoluted very quickly when a project grows in size.

So that's that. Hopefully I could offer some inspiration for picking Rust into production use. :-)