charlesreid1.com blog

Applied Gitflow

Posted in Git

permalink

This is a retroactive blog post. This post was authored in February 2022, using material authored in July 2020.

The most up-to-date version of this content is here: https://charlesreid1.com/wiki/Applied_Gitflow

How We Apply Gitflow

In some prior blog posts, we've covered a few patterns that we use for software development, including:

In this post, we'll get into some details about how we manage software in git repositories.

Specifically, we want to provide some details about how gitflow looks when it's being used to manage software with different versions, and when that software is being deployed in multiple environments.

The original gitflow pattern doesn't talk much about how software deployments in multiple environments fits in with the gitflow model, or even if it fits in the gitflow model.

With a few adjustments and patterns, gitflow can easily handle both. In this post we'll share patterns we have found useful when using gitflow to manage both deployments and releases.

The Tools

The main tool for this writeup is git, used for version control of the repository. GitHub and Gitea provide an interface to manage the git repository and to collaborate/review code. We use the gitflow model for managing branches and code, so we'll summarize it, and provide a link with the details.

We are also using a cloud provider where we upload the code to the cloud, and the code is run there. (Think AWS lambda function.) That code is separate from the git repository, so we need a way to track what code is in what environment. We'll cover how we do that, too.

Recap of Gitflow

Since this post is talking about how to apply Gitflow, let's go through a quick recap of how it works.

Gitflow requires that a few branches be created, but let's assume you're working in a repo already set up with Gitflow. In that case, regular development work looks like thi:

  • The develop branch is where the newest version is being worked on
  • Specific fixes or features go into their own feature branch
  • Feature branches are reviewed/tested before being merged into develop
  • When it is time for a new version, the accumulated features on develop are put into a new branch for the new version.
  • When the new version is ready, the main branch is updated to point to the new version branch. A new release is made from the main branch.

There is also a workflow for bug fixes for versions that have already been released:

  • A new hotfix branch is created from the version branch (which is also what the main branch is pointing to)
  • The changes are added to the hotfix branch
  • The hotfix branch is merged back into the version branch, the version number is bumped, and a new release is cut.
  • The hotfix branch is also merged into the develop branch, so that it will make it into future releases.

Deploying and Releasing

As the original author himself says on the page describing Gitflow, this model doesn't say much about how to handle deployments into multiple cloud environments.

There are two main actions that an operator can take, using the system we have devised:

  • deploy code (upload the code to a cloud stage, and have that version of the code running in the cloud)
  • release code (update which version of the code is considered the "latest version")

Additionally, the actions the operator can take will require certain variables to be defined - the location of the source code, and which cloud environment (development, integration, production) we're deploying to, for example. Those variables are defined using environment variables, so that we can use scripts to do deploy or release actions.

Environment File

Before covering the deploy and release scripts, here is an example environment file. The example release script below refers to these variables. The deploy script (no example provided, since it will inevitably be case-specific) also uses these environment variables. More environment variables can be added as needed, to grow with the complexity of the software and deployment process.

#!/bin/bash

export PROJECTNAME_PACKAGENAME_HOME="${HOME}/path/to/package"
export PROJECTNAME_PACKAGENAME_STAGE="dev"

Deploy Action

The deploy action is the action that takes the code in its current state and uploads it to the cloud. That can take many forms depending on the cloud service being used, but for example deploying an AWS lambda function would mean creating a new .zip file from the lambda function code, and uploading that zip file to the corresponding lambda function using the AWS CLI.

The deploy action is a script that is run. It deploys the code in its current state in the repository. Environment variables are used to parameterize the script. There are environment variables to specify the repository location on disk, to specify the deployment stage, and any others that are needed.

The deploy script is also the place to assert certain conditions are true before the deploy action is taken. We keep it simple, but these can be expanded on:

  • Check various environment variables are set
  • Check environment variable values

These can be done in the deploy script directly, if the checks are simple, or they can be moved to an entire separate script like a hypothetical check_env.sh, which would be run before the deploy script (using a make rule dependency).

(Note that if checks are TOO strict, they can interfere with deployment, so they should be adjusted accordingly.)

Another step the deployment action might have before the actual deployment is to assemble any deployment configuration files. For example, if the deployment process requires a JSON file that is dynamically assembled from other bits of information, that could go in its own script that would be run before the deploy script (using a make rule dependency).

For this writeup, we keep things simple and do all the checks in the deploy script.

Release Action

The release action can be thought of as a git repository operation.

When does a release happen?

When using gitflow, features and bugfixes will accumulate in the develop branch. Eventually the time for a new release will come (scheduled, or because enough changes have accumulated). A new branch will be created that will "freeze" the code in whatever state the develop branch is in. (Freeze is in quotes, because there are small changes that need to be made to that "frozen" code before a release happens, but those are changes like bumping the version number - no core changes.)

Where does the release script come in?

Once the code in the release branch is ready to go, the release script is run. The script will create a git tag, reset the head of the branch corresponding to the release (the "stable release" branch, usually main) to the head of the pre-release branch - whatever branch you're on when the release script is being run. Using our convention, we name this branch release/v1 (prefixed with release/ and a v plus the major version number only).

What does the release script do?

The release script starts by running some checks to make sure the code is in a state that's ready to release. There must be no uncommitted files in the repo, there must be no changes to tracked files, and there must be no unpushed changes in the repository (local commits that haven't been pushed to the remote).

If those conditions are met, then the release script proceeds. The release script will start by creating a git tag, which records the date, time, and branch being released to. Next, the head of the branch to release to (usually main) will be reset to the head of the branch to release from (the "frozen" code that's all fixed up for the release). Finally, the release script will push the results of the reset operation, and the new tag, to the remote.

To keep it more general, the release script uses the concept of a "source" and "destination" branch - the source is the branch to release from, the destination is the branch to release to. The destination branch is the one whose head is reset to the source branch's head. (That should help clarify the script below a bit more.)

Also, the Makefile (which we cover below) will take care of providing the right destination and source branch names.

Release Script

Here is an example release script, which we would add to our repository at scripts/release.sh:

#!/bin/bash
set -euo pipefail
set -x

REMOTE="origin"

# Check that environment file has been sourced
if [ -z "${PROJECTNAME_PACKAGENAME_HOME}" ]; then
    echo 'You must set the $PROJECTNAME_PACKAGENAME_HOME environment variable to proceed.'
    exit 1
fi

# Check the script is being called correctly
if [[ $# != 2 ]]; then
    echo "Given a source (pre-release) branch and a destination (release) branch,"
    echo "this script does the following:"
    echo " - create a git tag"
    echo " - reset head of destination branch to head of source branch"
    echo " - push result to git repo"
    echo
    echo "Usage: $(basename $0) source_branch dest_branch"
    echo "Example: $(basename $0) release/v2 main"
    exit 1
fi

# Check that all changes are committed
if ! git diff-index --quiet HEAD --; then
    echo "You have uncommitted files in your Git repository. Please commit or stash them."
    exit 1
fi

export PROMOTE_FROM_BRANCH=$1 PROMOTE_DEST_BRANCH=$2

# Check that there are no local commits that haven't been pushed yet
if [[ "$(git log ${REMOTE}/${PROMOTE_FROM_BRANCH}..${PROMOTE_FROM_BRANCH})" ]]; then
    echo "You have unpushed changes on your promote from branch ${PROMOTE_FROM_BRANCH}! Aborting."
    exit 1
fi

RELEASE_TAG=$(date -u +"%Y-%m-%d-%H-%M-%S")-${PROMOTE_DEST_BRANCH}.release

# Check whether there are commits on the destination branch that aren't on the source branch (changes would be thrown away)
if [[ "$(git --no-pager log --graph --abbrev-commit --pretty=oneline --no-merges -- $PROMOTE_DEST_BRANCH ^$PROMOTE_FROM_BRANCH)" != "" ]]; then
    echo "Warning: The following commits are present on $PROMOTE_DEST_BRANCH but not on $PROMOTE_FROM_BRANCH"
    git --no-pager log --graph --abbrev-commit --pretty=oneline --no-merges $PROMOTE_DEST_BRANCH ^$PROMOTE_FROM_BRANCH
    echo -e "\nYou must transfer them, or overwrite and discard them, from branch $PROMOTE_DEST_BRANCH."
    exit 1
fi

# Check that untracked files are not present
if ! git --no-pager diff --ignore-submodules=untracked --exit-code; then
    echo "Working tree contains changes to tracked files. Please commit or discard your changes and try again."
    exit 1
fi

# Perform the actual release operations
git fetch --all
git -c advice.detachedHead=false checkout ${REMOTE}/$PROMOTE_FROM_BRANCH
git checkout -B $PROMOTE_DEST_BRANCH
git tag $RELEASE_TAG
git push --force $REMOTE $PROMOTE_DEST_BRANCH
git push --tags $REMOTE

Breaking It Down

Let's break down the essential commands, starting with the checks:

git diff-index --quiet HEAD --

git log ${REMOTE}/${PROMOTE_FROM_BRANCH}..${PROMOTE_FROM_BRANCH}

  • Checks the difference between the remote and local versions of the promote from branch
  • If this command turns up any commits, those are all local, unpushed commits

RELEASE_TAG=$(date -u +"%Y-%m-%d-%H-%M-%S")-${PROMOTE_DEST_BRANCH}.release

  • Creates a name for the git tag with the date and time, and branch being released to
  • This stores the release history in git tags

git --no-pager log --graph --abbrev-commit --pretty=oneline --no-merges -- $PROMOTE_DEST_BRANCH ^$PROMOTE_FROM_BRANCH)

  • This command checks for any commits that are on the destination branch and not on the source branch
  • Because the destination branch's head will be reset, commits on the destination branch but not on the source branch would be lost
  • (This script could optionally add a --force flag, to power through the release even if this check fails)

git --no-pager diff --ignore-submodules=untracked --exit-code

  • Checks if there are any untracked changes in the working tree
  • If there are, the release can't proceed

Now here's a breakdown of the release process commands:

git fetch --all

  • Ensures we have an up-to-date picture of where the remotes are at

git -c advice.detachedHead=false checkout ${REMOTE}/$PROMOTE_FROM_BRANCH

  • Checks out the source branch from the remote
  • This command is the reason why we have to make sure all local commits are pushed to the remote
  • The release process uses the remote version of the source/destination branches

git checkout -B $PROMOTE_DEST_BRANCH

  • This step forces the destination branch to be the same as the source branch.

git tag $RELEASE_TAG

  • Creates a record of what was released and when via a git tag

git push --force $REMOTE $PROMOTE_DEST_BRANCH

git push --tags $REMOTE

  • Pushes the results of the operations to the remote

Makefile

Now we add a Makefile with rules for releasing and deploying.

The first rule is the release rule - run this when the current branch is release/vX and it's ready for it's final release.

CB := $(shell git branch --show-current)

release_mainx:
    @echo "Releasing current branch $(CB) to mainx"
    scripts/release.sh $(CB) mainx

The $(CB) is short for current branch.

Now on to the deploy rule.

Because we might want to deploy the code in an arbitrary state (temporarily deploying a feature branch to the development stage, for example), the deploy script and deploy rule are intended to deploy the code in its current state, and don't have the same kinds of checks as the release script.

deploy:
    scripts/deploy.sh

As mentioned above, the deploy script will be case-specific so we don't provide an example.

How does the deploy script know which environment to deploy to? It depends on the environment file that was sourced, and the value of the PROJECTNAME_PACKAGENAME_STAGE variable. The deploy script should be checking that that environment variable is set to a valid value before proceeding with the deploy.

More Details

For more details, see the full writeup on our wiki here: https://charlesreid1.com/wiki/Applied_Gitflow

Tags:    git    github    programming    gitflow    hubflow    patterns   

A Singleton Configuration Class in Python

Posted in Python

permalink

Overview

In this post we cover a strategy for managing configurations for programs using a Singleton pattern to create a static Config class.

This allows the user to create an instance of the Config class, pointing it to a specific config file, which it loads into memory.

The Config class provides several static methods for accessing configuration options from the config file. Here's an example of its usage:

Config('/path/to/config.json')

if Config.get_foo() == "bar":
    do_stuff()

The principle is to define one configuration file location, and be done with it. The configuration file is JSON formatted, but the pattern can be adapted to use any format.

The Config class can also be used to wrap and process both variables in the configuration file and environment variables.

The Config class implements a separation of concerns by only processing top-level configuration variable options, and leaving more detailed configuration file parsing to the classes that need it. This allows for more flexible config files.

The Singleton Pattern

The Singleton pattern involves the use of instance variables, which the variables _CONFIG_FILE and _CONFIG are. These are shared across all instances of class Config and can be accessed via Config._CONFIG_FILE, etc.

The location of the config file can be set in the constructor, or can be provided via the CONFIG_FILE environment variable. The config class also provides a method for accessing environment variables that are required by the Config class, and raising a custom exception if it is not present.

The constructor starts by checking that the configuration file exists, then loads the configuration file into memory (at Config._CONFIG as a dictionary):

class Config(object):

    #########################
    # Begin Singleton Section
    #########################

    _CONFIG_FILE: typing.Optional[str] = None
    _CONFIG: typing.Optional[dict] = None

    def __init__(self, config_file = None):
        if config_file is None:
            config_file = Config.get_required_env_var("CONFIG_FILE")

        # Check that specified config file exists
        assert os.path.exists(config_file)

        # Use singleton pattern to store config file location/load config once
        Config._CONFIG_FILE = config_file
        with open(config_file, 'r') as f:
            Config._CONFIG = json.load(f)

    @staticmethod
    def get_config_file() -> str:
        return Config._CONFIG_FILE

    @staticmethod
    def get_required_env_var(envvar: str) -> str:
        if envvar not in os.environ:
            raise ConfigException(f"Please set the {envvar} environment variable")
        return os.environ[envvar]

Aside from the constructor, every method in the Config class is a @staticmethod or a @classmethod.

Get Variable Functions

We add two additional methods to get configuration variables: one to get variables from the config file, one to get environment variables. Here they are:

class Config(object):

    ...

    @staticmethod
    def get_required_env_var(envvar: str) -> str:
        if envvar not in os.environ:
            raise Exception("Please set the {envvar} environment variable")
        return os.environ[envvar]

    @staticmethod
    def get_required_config_var(configvar: str) -> str:
        assert Config._CONFIG
        if configvar not in Config._CONFIG:
            raise Exception(f"Please set the {configvar} variable in the config file {Config._CONFIG_FILE}")
        return Config._CONFIG[configvar]

We saw the get_required_env_var()function in action in the constructor. Theget_required_config_var()` can be useful for config variables that are dependent on other config variables.

Config Functions

Continuing with the Config class defined above, we now define methods that implement logic for specific configuration variables.

Here are two example config variables.

The variable foo is set using the configuration file. The configuration file is a dictionary, meaning it consists of key-value pairs, so the variable foo is set by the value corresponding to the foo key in the config file.

For example, using the following simple configuration file:

{
    "foo": "hello world"
}

if the Config class is initialized with that configuration file, Config.get_foo_var() will return the string hello world.

Similarly, the barvariable is set using the environment variable BAR. If the BAR variable is not set, the program will raise an exception when Config.get_bar_var() is called.

class Config(object):

    ...see singleton section above...

    #############################
    # Begin Configuration Section
    #############################

    _FOO: typing.Optional[str] = None
    _BAR: typing.Optional[str] = None

    @classmethod
    def get_foo_var(cls) -> str:
        """Example variable that is set in the config file (preferred)"""
        if cls._FOO is None:
            cls._FOO = Config.get_required_config_var('foo')
        return cls._FOO

    @classmethod
    def get_bar_var(cls) -> str:
        """Example variable that is set via env var (not preferred)"""
        if cls._BAR is None:
            cls._BAR = Config.get_required_env_var('BAR')
        return cls._BAR

    @classmethod
    def get_wuz(cls) -> str:
        if cls._WUZ is None:
            if 'wuz' not in cls._CONFIG:
                cls._WUZ = Config.get_required_env_var('WUZ')
            else:
                cls._WUZ = cls._CONFIG['wuz']
        if not os.path.isdir(cls._WUZ):
            raise Exception(f"Error: Path {cls._WUZ} is not a directory")
        return cls._WUZ

The wuz variable, in this example, is a variable that can be set with a config file variable, or (if it is not present in the config file) with an environment variable. The wuz variable msut also be a path, so there is logic for checking whether the path exists.

Reset method

It can be useful to clear out an existing config file in order to load a new config file - specifically, when testing. Here we define a reset() method that clears out variable values. We will show an example of how to use the reset() method below.

    @classmethod
    def reset(cls) -> None:
        cls._CONFIG_FILE = None
        cls._CONFIG = None
        cls._FOO = None
        cls._BAR = None
        cls._WUZ = None

This could be done more gracefully by iterating over each attribute of the Config class and only nullifying those attributes whose variable name matches the given pattern (start with an underscore, only contain capital letters and underscores) using a regular expression.

Creating a configuration context manager

To make tests more convenient, we define a context manager that takes a dictionary as an input. The context manager creates a temporary file with the contents of that dictionary, and resets the Config class using the temporary file as the new config file. This allows tests to be written using different configurations on the fly, very useful when testing different configuration options:

cfg = {"peanut_butter": "jelly"}
with TempConfig(cfg) as config_file:
    print(f"Temporary configuration file is at {config_file}")
    val = Config.get_required_config_var("peanut_butter")
    assert val=="jelly"

Here is the context manager class to temporarily replace the configuration wrapped by the Config class:

class TempConfig(object):
    """
    Temporarily patch the Config class to use the config
    dictionary specified in the constructor.
    """

    def __init__(self, config_dict, *args, **kwargs):
        """This is the step that's run when object constructed"""
        super().__init__()
        # This is the temp configuration the user specified
        self.config_dict = config_dict
        # Make a temp dir for our temp config file
        self.temp_dir = tempfile.mkdtemp()
        # Make a temp config file
        _, self.temp_json = tempfile.mkstemp(suffix=".json", dir=self.temp_dir)
        # Set the wuz variable to the temporary directory
        self.config_dict['wuz'] = self.temp_dir

    def __enter__(self, *args, **kwargs):
        """This is what's returned to the "as X" portion of the context manager"""
        self._write_config(self.temp_json, json.dumps(self.config_dict))
        # Re-init Config with new config file
        Config(self.temp_json)
        return self.temp_json

    def __exit__(self, *args, **kwargs):
        """
        Close the context and clean up; the *args are needed in case there is
        an exception (we don't deal with those here)
        """
        # Delete temp file
        os.unlink(self.temp_json)
        # Delete temp dir
        shutil.rmtree(self.temp_dir)
        # Reset all config variables
        Config.reset()

    def _write_config(self, target: str, contents: str):
        """Utility method: write string contents to config file"""
        with open(target, "w") as f:
            f.write(contents)

Next steps

That's it for now. This singleton configuration class is being written into a new version of centillion, which will be centillion version 2.0. This is still a pull request in a centillion fork, though, so it's a work in progress. Stay tuned!

Tags:    python    programming    patterns    design patterns    registry    computer science   

Using Mock API Servers

Posted in Python

permalink

Summary

In a prior post, we covered how to write a mock API server that stored a thread as a class attribute and used it to run the server in the background by starting a thread.

However, we neglected to cover how to actually use the mock API server. So here we include some examples of how you can use the mock API server to write better tests for components that require interacting with APIs.

The MockAPIServer Class

Let's start with a recap of the mock API server class. Major features included:

  • Inheriting from the base HTTP server class in Python, to take advantage of the methods available through it

  • Using a singleton design pattern to start and stop the fake API server

Basically we create the server, call start_serving(), and that starts the server on a thread in the background.

Here is the source code:

class MockAPIServer(BaseHTTPRequestHandler):
    _server = None
    _thread = None

    @staticmethod
    def get_addr_port():
        addr = "127.0.0.1"
        port = "9876"
        return addr, port

    @classmethod
    def start_serving(cls):
        # Get the bind address and port
        cls._addr, cls._port = cls.get_addr_port()

        # Create an HTTP server
        cls._server = HTTPServer((cls._addr, cls._port), cls)

        # Create a thread to run the server
        cls._thread = threading.Thread(target=cls._server.serve_forever)

        # Start the server
        cls._thread.start()

    @classmethod
    def stop_serving(cls):
        # Shut down the server
        if cls._server is not None:
            cls._server.shutdown()

        # Let the thread rejoin the worker pool
        cls._thread.join(timeout=10)
        assert not cls._thread.is_alive()

    def do_POST(self):
        ctype, pdict = cgi.parse_header(self.headers.get("content-type"))
        # Enforce rule: JSON only
        if ctype != "application/json":
            self.send_response(400)
            self.end_headers()
            return
        # Convert received JSON to dict
        length = int(self.headers.get("content-length"))
        message = json.loads(self.rfile.read(length))

        # Process the json

        # Send a response
        response = bytes(json.dumps(message), "utf8")
        self._set_headers()
        self.wfile.write(response)

    def _set_headers(self):
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()

A Basic Unit Test with MockAPIServer

Let's make a basic test that uses the MockAPIServer class. We'll use unittest for simplicity, other testing frameworks offer similar functionality.

Before testing our code, we'll need to make sure the API URL is configurable, sicne we will need to get the mock API server's bind address and port and use those to instruct our code where to find the API server.

Here is a short example function that we'll test:

foobar.py:

import urllib.parse

def make_api_call(api_url)
    """
    A simple function that gets an API endpoint
    and returns if no problems raised.
    """
    # Assemble our API call
    endpoint = '/hello/world'
    url = urllib.parse.urljoin(api_url, endpoint)
    params = dict(message='hello world')

    # The basic mock server will just echo our request back
    data = requests.get(url, params=params)
    data = resp.json()
    return

Now we write a short test for our foobar script:

test_foobar.py:

from foobar import make_api_call
import unittest

class TestAPICalls(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.app = MockAPIServer()
        cls.app.start_serving()

    def test_api_call():
        addr, port = self.app
        api_url = urllib.parse.urljoin(
            'http://', addr, port
        )
        make_api_cal(api_url)

    @classmethod
    def tearDownClass(cls):
        cls.app.stop_serving()

We can run the test like so:

python test_foobar.py

Here's what happens when we run the test:

  • The setUpClass() method is called, which creates a mock API server that starts on localhost on port 9876 and runs the server on a thread.
  • The test_api_call() method is run, which makes the API call to the mock API server. (Nothing interesting is happening on either end, right now, but stay tuned for more examples.)
  • The tearDownClass() method is called, which stops the mock API server and returns the thread worker to the pool of workers.

Stay tuned for more complicated examples in the future - we are currently working on extending this mock API server to mock calls to the Github API.

Tags:    http    server    python    mock    mocking    api    flask    web server   

November 2026

Baby Mac Crypto

March 2022

How to Read Ulysses

July 2020

Applied Gitflow

September 2019

Mocking AWS in Unit Tests

November 2017

A Hard(y) Math Problem