Post

Server programming and Docker containers

Server programming and Docker containers

Compared to network clients, server programming presents different properties and challenges. Typically a server needs to run in the background for long times without interruption and it needs to respond to connections from multiple clients efficiently and manage the client sessions in parallel. Handling this concurrency while taking care of other application logic is one of the main difficulties in developing an efficient server. Because server need to run long times (even weeks) without user interaction, and do it efficiently, memory safety is essential. Careless memory management has caused many security vulnerabilities some of which have gone unnoticed for long times, and memory leaks eventually cause the server performance to collapse. This is one reason why Rust has recently gained popularity among developers of network software.

In the latter part of this module we look into Docker that is a common technology to package deploy servers in a scalable and portable way. We use Docker to deploy student server programs into course’s server host, so that they are accessible for testing. From this point on, the following assignments are designed to contribute to a network project that expands into full network application by the end of the course.

Objectives for this module:

  • You will learn the fundamentals of passive server sockets and how they are operated.

  • You will learn to implement an iterative, single-threaded server that can take care of multiple parallel clients using non-blocking sockets.

  • You will understand the basics of container technology

  • You will learn to build a Docker image that runs server software built from Rust source code.

Passive and active sockets

When a connection-oriented client socket is opened for communication, it is called an active socket. An active socket can be used for both sending and receiving data, and it is bound to both a local and remote IP address and transport-layer port.

In contrast, a server application initially opens a socket in passive mode. A passive socket is not yet associated with a remote endpoint. It is bound only to the local IP address and port on which the server listens for incoming connection requests. This address needs to be known by the client so that it can connect the server. A passive socket cannot be used to send or receive data.

In Rust, the bind call is used by the server to choose the IP address and port, and open a socket in passive mode. In modern systems it is common that a host has multiple IP addresses in use at the same time for different network interfaces. For example, a laptop has the loopback address 127.0.0.1 for host-local communication, and it can have WiFi and wired LAN interfaces, both with different IP address. Commonly the IP address is bound to “any” address, i.e., 0.0.0.0 in the case of IPv4. This means that incoming connections are taken from any network interface. On the other hand, if an application wants to limit to a particular interface it accepts connections from, the address needs to be bound accordingly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use std::io;
use std::net::TcpListener;

fn main() -> io::Result<()> {
    // Bind to TCP port 1234 on all local IPv4 network interfaces.
    let listener = TcpListener::bind("0.0.0.0:1234")?;
    println!("Server listening on 0.0.0.0:1234");

    // Wait until one client connects.
    let (stream, address) = listener.accept()?;
    println!("Accepted connection from {address}");

    // 'stream' is now an active socket to the newly connected client.
    // 'address' contains the IP address and port of the other end.
    // You can start sending and receiving from it normally.

    Ok(())
}

When a new connection request comes in at the server, it needs to accept the connection request using accept call. This creates a new active socket for communication with the incoming client. This socket has both endpoint addresses defined, and it can be used for sending and receiving data. After this the operation of the socket becomes symmetric: both ends can send and receive data as they wish, but typically based on some defined protocol. Over time, there may be multiple active sockets open as new clients arrive, and the server needs to apply some strategy how to manage the concurrent clients in timely way, remembering that by default read and write calls may block program execution indefinitely, unless concurrency and non-blocking operation is taken care of appropriately.

Different server approaches

There are different ways of designing server implementation, depending on the application needs and scalability requirements. For example, the following are some common approaches:

  • The simplest form is a single-threaded iterative server that processes client connections one at a time without any concurrency. This may be applicable for very small tasks and small tests, but otherwise not very good option for server design.

  • We can apply non-blocking sockets and I/O multiplexing using OS mechanisms that allow waiting for events from multiple input sources, where multiple clients can be handled concurrently (but not in parallel) in a single thread. Limitation of single-threaded approach is, that it only uses single CPU core, and therefore may not leverage the full processing capacity that typically is available in a multi-core server.

  • Is is possible to spawn a separate thread for each incoming client. With multiple threads multiple CPU cores can be used, but spawning a new thread is somewhat costly operation for the operating system.

  • We can use a preallocated thread pool, and assign new client connections as a thread becomes available in a pool.

  • Asynchronous I/O is a programming model based on async/await primitives, where operations are distributed to tasks that are managed by a runtime environment running in the application process context as provided by a software library. The runtime can run in a single thread, or it can leverage multiple threads for better parallelism by the available CPU cores.

  • Sometimes it makes sense to spawn a separate operating system process to run the client session. This is an heavy operation for the operating system, but allows good isolation between client sessions, and is applicable, for example, to implement remote shell sessions, such as SSH.

These approaches are not exclusive. Production systems often combine different approaches for their needs. We will discuss the first two in this module, and return to multithreading and asynchronous I/O a little later.

Simple server

We will now take a look at simple-server example in our GitHub repository, probably the simplest server implementation possible. This program accepts incoming connections one at the time, reads any data sent by the accepted client, and then echoes the data back. After this the connection is closed and the server starts to wait for the next client. The server takes the IP address and transport port to bind to as command line argument. If you use “0.0.0.0” (assuming IPv4) as the IP address, connections are accepted from all network interfaces. If you use 0 as transport port, system will pick an available port for you. In practice this is inconvenient, because then the client applications would not know which port to connect to.

First you need to start the server by something like:

1
cargo run -- 0.0.0.0:2000

and then on another terminal window you can use netcat to test it, and typing some message:

1
nc 127.0.0.1 2000

You can also use the simple-client example on the other terminal window to send the message using the localhost address (running this on the simple-client directory of the repository):

1
cargo run -- 127.0.0.1:2000 Hello

Creating socket and binding to local address

The simple server starts by creating a passive server socket and binding it to the address given as command line argument. Variable server is the passive server socket listening for connections. If bind() call fails, for example due to invalid parameters, or because port was already in use, we may as well exit the server.

1
let server = TcpListener::bind(&args[1])?;

Accepting incoming connection

Then it starts a loop that starts by waiting for the next incoming client. The accept() call may block the execution for a long time.

1
2
3
4
5
6
7
8
9
let (mut socket, address) = match server.accept() {
    Ok((socket, address)) => (socket, address),
    Err(e) if e.kind() == ErrorKind::ConnectionAborted => {
        eprintln!("Client aborted connection: {e}");
        continue;
    }
    Err(e) => return Err(e),
};
println!("Accepting connection from {}", address.to_string());

When the call completes, we will get the active socket representing the connected client, and address of the client (IP address and TCP port), that will be printed on the terminal.

In server programming it is important to process the errors properly, because we want our server to run for a long time without human interaction. In the case of accept we distinguish two kinds of errors: it is possible that error happens if system runs out of resources, for example out of file descriptors used for the socket. In this case we determine it is not useful to continue execution, because the condition may be more persisting. On the other hand, client may have aborted the connection while waiting to be accepted. In that case we should continue with the next client.

Reading data from socket

After this, the server will read some data from the active client socket, assuming that client knows that it is expected to write something. If the client did not write anything, but would rather wait some input from elsewhere, the read call would block for a long time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let mut buf: [u8; 160] = [0; 160];
let readn = match socket.read(&mut buf) {
    Ok(readn) => {
        if readn == 0 {
            println!("Client closed connection");
            continue;
        }
        readn
    }
    Err(e) => {
        eprintln!("Error reading socket: {e}");
        continue;
    }
};

The read call returns a Result type variable as most socket options. In successful case it the number of bytes actually read, or 0 which means that the other end has closed the socket, in which case we can move to process the next incoming client. Typically it is important to handle this case, if the server has some state associated with the client that needs to be cleaned up. It is also possible that there is some sort of error with the read call, in which case we will also move to process the next client.

Note the way how the readn variable is assigned from the result of the match statement. This is common style in Rust. Because the error branch does not return value, but jumps to the next iteration of the loop, and the Ok variant of read() call returns usize-type unsigned integer, we know that as a result readn is unsigned integer representing the number of bytes read.

Echoing data back

Finally, the server echoes the data that was read back to the client, and closes the socket, as the lifetime of the local socket variable ends at the end of the loop. Note the slice syntax in write argument: because it is possible (and common), that we didn’t read the full allocated buffer from client, we will only write the number of bytes actually read. This way we tell that we operate only on a part of the buffer. Again, we need to process errors separately, to keep the server running.

1
2
3
4
5
6
7
let writen = match socket.write(&buf[..readn]) {
    Ok(writen) => writen,
    Err(e) => {
        eprintln!("Write error: {e}");
        continue;
    }
};

If we were not interested in the return value of the write() call, for example when using write_all(), we can still test whether the operation succeeded or returned error, for example in the following way:

1
2
3
4
if let Err(error) = socket.write_all(&buf[..readn]) {
    println!("Failed to write to {}: {}", address, error);
    continue;
}

If the Result return value from write_all() is of Err variant, the if let condition is true and the branch is taken, with the contents of the Err variant bound to error variable. If the call succeeded, the condition is false, and processing moves forward.

I/O multiplexing and non-blocking sockets

By default a socket is opened in blocking mode, i.e., function calls such as read and write can block the execution of the program until it becomes possible to read or write. When a program needs to react to other inputs timely, i.e. user interaction or multiple clients connected to server concurrently, such blocking behavior causes problems.

Sockets can be can be configured into a non-blocking mode, in which case the calls return immediately. In this case, if for example the read function did not have any data to read, and it would have therefore stopped the execution in the normal blocking mode, the non-blocking version of the call returns a specific WouldBlock “error” (that is not actually an error, but just tells there was nothing to read). A naive implementation would be to build a loop in the server that reads all sockets in this way. However, this would create a busy loop that would unnecessarily load the CPU, even if no data is coming from any of the clients.

To avoid unnecessary CPU load with non-blocking sockets, the Posix API has a poll operation that can be used to wait multiple I/O events simultaneously from sockets and other I/O sources. The operation blocks until at least one of the registered event sources is available. Then from the return value the application knows which sockets and other information sources can be processed.

In Rust, mio is a library (or “crate” in Rust terminology) that encapsulates the non-blocking socket operation into convenient set of functions. The iterative-server example demonstrates the use of mio (you may want to open the code in a separate window while reading this section). The server just reads incoming data from socket and echoes it back, like the previous example. Differing from the earlier example, the server does not close the socket after writing data, but after responding to client, it continues waiting for more data, until the client closes the connection. Therefore the server needs to be able to handle multiple client sockets simultaneously.

The first lines of the main function are similar to previous example, reading the binding address from command line arguments. Then we set up Mio’s poll service and container for the Mio events. Each possible event source is assigned an unique “Token” that identifies the event source (bascially just encapsulating an integer), We implement a small “TokenManager” for easier allocation and release of unique tokens in a separate file, tokenmanager.rs.

First we add just the passive listening socket as event source (line 60). Note that with Mio the TcpStream and TcpListener implementations are different than the standard implementations of the same types (see the use statements in the beginning of the program). These are compatible with Mio and implement non-blocking operation.

The heart of the main event loop is Mio’s poll function (line 71) that stops until at least one event is available. After poll completes, there may be multiple events available, so we need to handle all of them iteratively. If there is an event on the listening socket, we know that we can call accept safely without blocking the program. We have a small Client structure that contains the socket and address of an client. All active clients are stored in a HashMap container, where the Mio token is used as the key. If there was any more complicated application logic, the Client structure could contain also other client-specific information for the use of the application. When a new client is accepted, a new token is allocated for it and registered to Mio as an interesting event source.

Mio has separate event types for situations when socket is readable, and for situations when socket is writable without blocking the execution. If we wanted a proper implementation, we should also handle the write() calls through an event processing loop, but in this case we skip it for simplicity (and perhaps laziness). On the other hand, we write a maximum of 160 bytes, and the operating system socket buffers are usually at least tens of kilobytes, so having write() call to block because of full socket buffer, is quite unlikely.

After client connections are opened, also the possible client socket events are checked in separate if branch. Here one should note handling of the read call return values, and the use of Result: Ok response is returned when read is successful. In the case of Ok, the return value will indicate the number of bytes read. If the return value is 0, the client has closed the socket, and therefore we should clean up: release the Mio event token, and remove the client from the HashMap. This also causes the lifetime of the socket to end, so it will be cleaned up also from our end. Err response means that error occurred in read. Also in this case we clean up the client socket, but do not terminate the operation of the main server loop. Earlier we have mostly used the ? operator that propagates the possible error up in the call stack, which would have caused termination of the program.

The write call shows another way of checking for an error outcome, in case we are not interested in the exact Ok return value. A better alternative, in addition to handling the write call through the writable event, would be to check how many bytes were actually written, and prepare for the case when only part of the data was written.

You can test the program by first starting the server in the same way as before:

1
cargo run -- 0.0.0.0:2000

Then, open more than one terminal windows where you start a netcat session in each, opening multiple connections to server:

1
nc 127.0.0.1 2000

Try typing different things to different client terminal windows, closing netcat in some windows by Ctrl-D (Hang-up of connection) or Ctrl-C (Interrupt netcat), and then restarting netcat, to see how the server reacts.

A benefit of a single-threaded, event-driven server design is that it is lightweight and behaves predictably (as long as the operations are not blocking), as it avoids thread management overhead and synchronization. On the other hand, just using a single thread may not efficiently use the available resources at a server with multiple CPUs.

Docker basics

Docker provides a way to package an application together with its runtime environment so that it can run consistently across different machines. Docker containers use Linux OS mechanisms such as namespaces and cgroups to isolate application processes and control their access to resources, filesystems, and networks. A Docker image contains the filesystem and configuration needed to create and run a container. Docker is often used to deploy network services, for example inside datacenters, where an orchestration system can dynamically distribute, manage and scale containers across multiple servers.

On this course we will use Docker to deploy the server implementations between your local machines to the course servers hosted by the university. Docker allows you to test the application first locally and then move it to a server where everyone can access it.

First, one produces a Docker image that contains the filesystem and needed metadata for the application. Dockerfile specifies the recipe for building an image. Docker images consists of filesystem layers, typically extending a base image (for example one that contains the basic Linux tools). Layers can be cached and shared between images, reducing build time and storage use.

Docker container is a running instance of a image. On large services, Docker is used to dynamically replicate and scale services into multiple, typically distributed containers.

Often Docker images are deployed in registry (such as docker.io), where they can be found and used by anyone needing them. On this course we are not using a registry, but the course server builds Docker images based on student git repositories, and then runs them on the server, so that they are accessible by client implementations.

The below image shows the Docker setup we are applying at our course server, and how a request to run-docker API first takes a git clone from the student repository, then build the Docker images based on the Dockerfile in the repository and then runs the container. More detailed description of the API is in the Assignment description at the end.

Docker setup at course server

On most systems, easiest way to get Docker in a local system is to install Docker Desktop that is available in Windows, Mac OS and Linux. Docker desktop provides a graphical user interface for managing the containers in the local desktop system, but also comes with the command line tools discussed below.

Building a Docker image

Below is an example of a Dockerfile that has the builder part for building a binary server application from a Rust source code, and runtime part that runs the binary server application, opening TCP port 1234 for connections from the outside world. You should be able to adapt it quite easily to fit your project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Build the Rust server application.
FROM rust:1.96 AS builder

# Set the working directory inside the container.
WORKDIR /usr/src/my-server-app

# Copy the source code from local machine to the container.
COPY ./ ./

# Build the server in release mode for better performance (inside the container).
# In this case, the server is located in a separate 'server' package under
# the Rust workspace. We do not need to include the client in the container.
RUN cargo build -p server --release


# Run the compiled server from a smaller runtime image.
FROM debian:bookworm-slim AS runtime

WORKDIR /usr/local/bin

# Copy the compiled server binary from the builder stage to the runtime stage.
COPY --from=builder /usr/src/pronets-demo-chat/target/release/server ./server

# Expose the port that the server will listen on.
EXPOSE 1234

# Set the command to run the server when the container starts.
CMD ["./server", "--port", "1234"]

The builder part of the Dockerfile can be run, for example, with the following command on the command line.

1
docker build -t my-server-app .

The -t my-server option gives the built image a local name. The final . tells Docker to use the current directory as the build context.

After this the container can be executes as follows:

1
docker run -d -p 1234:1234 --name my-server-app my-server-app:latest

The -d option causes the server to be run in the background. To keep it on the terminal foreground (e.g. for development and debugging), you can leave the -d option out. The -p 1234:1234 causes TCP port 1234 from the container to be exposed at the host machine, so that it can be connected from outside applications.

Using Docker

Even though Docker Desktop offers a graphical user interface for operating containers in the local system, below are shortly described the most important command line operations you might find useful.

To list all currently running containers:

1
docker ps

In the container list you can see the container ID and container name that can be used to address different container operations.

To see the container logs:

1
docker logs container-name

The logs show the output the program(s) inside the container have printed to standard output. In a long-running server implementation, the length of the logs grows over time. Therefore, especially for interactive debugging the following can be useful:

1
docker logs --tail 100 -f container-name

This shows only the last 100 lines of the output, after which the terminal stays following the output stream until interrupted with Ctrl-C.

To stop a running container:

1
docker stop container-name

Another useful way to analyze container behavior and state in more detail is to execute commands inside a running container in the following way, e.g. for listing the current filesystem contents:

1
docker exec container-name ls /app-dir

You could even start an interactive shell inside the container for more detailed analysis:

1
docker exec -it container-name /bin/sh

The -i option keeps the container’s standard input open, i.e., you can type input to it. The -t option allocates a pseudo-terminal for the container, making the session behave like an interactive terminal.

Rust project organization and workspaces

Previous course section already briefly mentioned the concept of modules and packages in a Rust project. In the following we will discuss (and propose) a structure for organizing a client/server Rust project as two packages in a shared workspace in a single git repository. Each package has a separate Cargo.toml file, and builds into a separate binary. For example, in some projects there could be packages for the libraries needed as part of a larger software, and other packages for binaries using these libraries.

Proposed workspace structure

For a client-server project, we have example “project-template” presenting this setup that you can use as a basis for your work, if you so wish. The project template refers to concepts we have not yet discussed, such as threads and the tokio library, but don’t worry too much about those yet. For this week assignment’s client part you can also implement a simple command line-based version of the client, or alternatively modify the client example.

Even though our course project will be fairly small, there are some good reasons to make the client and server implementations two separate packages in the same workspace, especially if one wants to create a graphical client. Our example uses the Slint GUI framework for the user interface, and the needed crates (libraries) need to be included as dependencies for the client implementation in its Cargo.toml. However these crates would be useless at the server, and therefore do not need built as part of the server binary (and the docker image on our server). Similarly, the server package may need some crates that are not needed at the client. On the other hand, having the two related applications in the same workspace connects them together, and allows sharing some common code, e.g. for message parsing in the same git repository.

The client example also shows how a package can include external crates/libraries in the Cargo.toml file, so that they are automatically fetches from the Rust crate registry (“crates.io”). Usually you should specify the version to use. Some larger libraries are divided into specific selectable “features” that help in reducing the final binary size for features not needed.

Assignment #3

We now start developing network software project in the git repository created in the beginning of the course. It is recommended that you include the client and server implementations in the same repository and same Rust project workspace, as separate packages as described above.

You create the Rust workspace in your existing git repository in the following way, for example:

  1. Create the workspace-level Cargo.toml file at the root of the repository with the following content:
1
2
3
[workspace]
members = ["client", "server"]
resolver = "2"
  1. Create client and server packages each in their own directories using cargo new command:
1
2
cargo new client
cargo new server

Part 1: Implement a simple server that listens to incoming connections at the port assigned for you. At this point the server recognizes only one type of message: Test message “TST” that can be used to test that the server is alive and responsive.

Our message structure, that also the TST message applies is as follows:

  • The message starts by an 32-bit unsigned integer that indicates the message length. The integer must be in big-endian network byte order (see previous module how to do this). The length covers whe length of the whole message, including the length field itself and the identifier number.

  • Then there should be another 32-bit unsigned integer that is the message identifier, in network byte order. Later on, this can be used to identify responses to the corresponding request messages.

  • After this there is message type “TST” followed by space and arbitrary content.

When server receives this message, it must echo the same message back to the client, using the same length and message identifier.

Below is an illustration of the message format, along with an example (including the message as bytes).

Message format

Part 2: Implement also a client application that sends a TST message, so that you can test the server.

Part 3: Add Dockerfile to your project that builds the server and starts it. The Dockerfile should be at the root of your git repository, and be named “Dockerfile” so that our course server can find it for building the image at the server.

After the Dockerfile is created and you have tested that the server works locally, e.g. using Docker Desktop, it is time to push your work to your git server repository.

Part 4: The server should be registered to course server by using a HTTP POST request to pronets1.dice.aalto.fi, port 80. The exact HTTP endpoint is POST /run-docker. The body of the POST request must be JSON encoded and have the following fields:

  • “name”: The username you want to use with the server. This should be the username you declared earlier.
  • “git-repo”: The URL of the Git repository you are using for your course assignments and project.
  • “ports”: The port number(s) that the server listens for connections. For now there is only one port in string format.
  • “protocol”: The protocol identifier and protocol. This should be now “base-1”. We will explain the protocols a bit more in next module.

Note that the structure is same as with the “/fetch-git” endpoint developed in last assignment, with couple of additional fields. You can extend the previous code to implement the run-docker request.

Implement a program that sends the HTTP request (or it could be part of your client code, for example) and waits for response. When the server receives the request, it fetches your code from git, and uses your Dockerfile to build and run your server. Note that this takes time (could be even minutes), but if everything goes well and you eventually receive “OK” response, your server code should be running in pronets1.dice.aalto.fi, listening to connections at the port you have given.

The main course “master server” sends the TST message every 60 seconds to all containers that have been started. You can see all the registered servers, along with their ports, and the outcome of the latest TST message at https://pronets1.dice.aalto.fi/

Write a short report where you document the progress going forward with the above steps. Start the report by giving your project name. For each step, tell shortly how did you approach the problem, what difficulties you encountered, and how did your solve them. Can you find your container in the server containers view, and does it show “OK” for your container? As before, include also the following information:

  • How much time did you use for this assignment?
  • What was easy or difficult in the assignment?
  • What tools or other information sources did you use? In particular, if you used AI assistants, tell how did you use them and if they were helpful.