Controlling a WSL installation of redis-server from the Windows command line

If you like using redis for web site caching and you are writing and testing code locally from Windows, you’ll want to figure out how to run a local instance of redis-server. You have a few options. You can run it from another machine that’s running something vaguely Linux-like or MacOS. You can run it from a Docker container under Windows. Or you can run it directly from Windows SubSystem (WSL) for Linux.

For the last few years, Windows (10, 11, Server 2019) comes with a compatibility layer that lets you run Linux binary executables. The current version is WSL 2, but I’m just going to refer to it as WSL.  If you don’t have installed already, just run the following command from an elevated shell (run as administrator)

wsl --install
Installing WSl via command line
Installing WSl via command line

It will install the bits that you need and then ask you to reboot your machine. For more information about installing and configuring WSL, Microsoft has some really good documentation at Install WSL.

The default Linux distribution for WSL is Ubuntu. After you reboot, you may see a Ubuntu shell for a while as Windows installs the bits that you need. It will churn for a bit and then ask you for a username and password. That password will be your sudo (user root) password. One that is done, you should see something like this.

Final step of installing WSL is configuring the default Linux distribution
Final step of installing WSL is configuring the default Linux distribution

The next thing to do is to install redis-server. We can install redis vis apt-get, but before we do that, we need to update apt-get and remove some of the new install shininess off.

sudo apt-get update
sudo apt-get upgrade

After updating apt-get, you’ll want to upgrade it. Confusing? Sort of. Update is updating the instance of apt-get, upgrade is updating all of the packages that were installed via apt-get. After that has finished, you can install redis-server

sudo apt-get install redis-server

There will be some churn and finally, it be installed. Out of the box, redis will not be running. My personal preference is to only run redis when I’m actually using it for development. So I Iike to start and stop it from the command line. Here are commands that you need to know:

sudo service redis-server status
sudo service redis-server start
sudo service redis-server stop

I’ll start up redis with the service start command, and it will come back with a message that redis is starting. And you can use the service status command to verify that it’s running. The acid test is to connect to redis and see if it’s working. You can use the redis-cli tool to set and get a cache value. You should see something like this.

Running redis-cli from the Ubuntu shell
Running redis-cli from the Ubuntu shell

So now redis-server is running. If you close the shell and open up a new one, it will still be running. If you restart WSL or Windows, then it wont be running. Now you can always pop open an Ubuntu shell and start redis-server, but you can do it from a Windows command line

wsl sudo service redis-server status
Running redis commands from PowerShell
Running redis commands from PowerShell

From the screenshot, you can see that WSL passed along the sudo service command to Ubunto. And because I used sudo, I was prompted for the root password. And it returned the same message that I would see from the Ubuntu shell. Since I only have Ubunto installed, that was the default Linux that received the command. If you have multiple distributions installed, you would use “wsl -d DistributionName”. You can get the names of the installed distributions with the “wsl -l” command. Unlike from the Linux shell, each time I invoke “sudo”, I’m prompted for the password. In the Linux shell, you are prompted just the first time you call sudo in a terminal session.

Having to use the root password over and over again can be tedious on a development box. There is a way around that. You can add a file to the /etc/sudoers.d folder in the Linux distribution and remove the root password requirement for the redis-server service. From the Linux shell do the following

cd /etc/sudoers.d
sudo sh
echo "%sudo ALL=(ALL) NOPASSWD: /usr/sbin/service redis-server *" >> allowed-services
sudo chmod 0440 allowed-services
exit

The first thing we do is make /etc/sudoers.d the current folder. Then we use “sudo sh” to gain root access. You need root access to work with this folder. The echo line basically says that you can invoke sudo with no password for redis-server and writes that setting to a file named allowed-services. The file name allowed-services is arbitrary, I picked it because it made sense to me. There is a file in the sudoers.d folder named README, it will explain what the file name restrictions are.

The chmod 0440 command sets the permissions to read-only for the root account and is required for sudoers.d. This allows us to remove the sudo password requirement for redis-server and only for redis-server. Now we can go back to the Windows shell and run the wsl commands without being prompted.

You can even run the redis-cli tool from powershell…

Redis from PowerShell, no password
Redis from PowerShell, no password

The WIndows Subsystem for Linux is one of the hidden gems for developers. And this gem sparkles…

Bonus Round!

Because I’m lazy, I created shortcuts in my PowerShell profile. I added the following functions:

function redstat {wsl sudo service redis-server status}
function redstart {wsl sudo service redis-server start}

And now I can just check the redis-server status via “redstat”

A quick PowerShell tip

I have a bunch of PowerShell functions that I stick in my $profile file. Simple stuff, things to make my day to day development work easier. With my sieve-like memory, I need a quick way to see the functions. So I wrote a script named “mine.ps1” and it’s basically a tiny help file.  It has stuff like this

write-host Commands -ForegroundColor White
write-host "get-guid-clipboard" -ForegroundColor Yellow
write-host "set-alias lsd get-by-date" -ForegroundColor Yellow
write-host "Set-Alias touch Set-FileTime" -ForegroundColor Yellow

In my $profile, I define those functions. They could (and should) be in a separate file, but I’m lazy. This is part of my PowerShell profile:

function Set-FileTime{
    param(
      [string[]]$paths,
      [bool]$only_modification = $false,
      [bool]$only_access = $false
    )
  
    begin {
      function updateFileSystemInfo([System.IO.FileSystemInfo]$fsInfo) {
        $datetime = get-date
        if ( $only_access )
        {
           $fsInfo.LastAccessTime = $datetime
        }
        elseif ( $only_modification )
        {
           $fsInfo.LastWriteTime = $datetime
        }
        else
        {
           $fsInfo.CreationTime = $datetime
           $fsInfo.LastWriteTime = $datetime
           $fsInfo.LastAccessTime = $datetime
         }
      }
     
      function touchExistingFile($arg) {
        if ($arg -is [System.IO.FileSystemInfo]) {
          updateFileSystemInfo($arg)
        }
        else {
          $resolvedPaths = resolve-path $arg
          foreach ($rpath in $resolvedPaths) {
            if (test-path -type Container $rpath) {
              $fsInfo = new-object System.IO.DirectoryInfo($rpath)
            }
            else {
              $fsInfo = new-object System.IO.FileInfo($rpath)
            }
            updateFileSystemInfo($fsInfo)
          }
        }
      }
     
      function touchNewFile([string]$path) {
        #$null > $path
        Set-Content -Path $path -value $null;
      }
    }
   
    process {
      if ($_) {
        if (test-path $_) {
          touchExistingFile($_)
        }
        else {
          touchNewFile($_)
        }
      }
    }
   
    end {
      if ($paths) {
        foreach ($path in $paths) {
          if (test-path $path) {
            touchExistingFile($path)
          }
          else {
            touchNewFile($path)
          }
        }
      }
    }
  }

function get-by-date {get-childitem | sort LastWriteTime }
function get-guid-clipboard { [guid]::NewGuid() | Set-Clipboard }
set-alias lsd get-by-date
Set-Alias touch Set-FileTime
Set-Alias -Name guidc -Value get-guid-clipboard -Description "Get a GUID and copy it to the clipboard"
function get-mine {. d:\\scripts\mine.ps1}
write-host "Type 'get-mine' for my local functions"
[System.Net.Dns]::GetHostByName($env:computerName).HostName.ToLower()

The touch functions came from the ss64.com site. I end by displaying the current machine name. When you remote into a box of boxes, it’s good to know where you currently are. Now when I fire up a new shell, I’ll see something like this:

PowerShell 7.1.3
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

Type 'get-mine' for my local functions
uberbox
Loading personal and system profiles took 929ms.

Checking Hypervisor status with PowerShell

Image courtesy of Serge Melki

I needed to find a quick way to see which hypervisor was installed.  I bounce between different development machines and some have Hyper-V enabled and some have Intel’s HAXM driver installed.  Both assist with virtual machines, but they can’t be used together.  I used to be 100% Hyper-V with running virtual machines and Android emulators.  The Microsoft Android Emulator used to be very good, but is suffering from a fair amount of bit rot.  In the meanwhile, Google’s Android Emulator has gone from being a great of sitting and watching something load very slowly to a tool that that you can use in real time.

Microsoft’s Android Emulator requires Hyper-V and Google’s Emulator really needs HAXM in order to have any level of performance.  Since I bound around from machine to machine (with the occasional repave), I wanted a quick way to see which hypervisor is installed.  Hyper-V requires a some work to turn on and off. HAXM is a kernel driver.  So I wrote a quick PowerShell script to report the status of each Hypervisor

$services = 'intelhaxm', 'vmicheartbeat'

$d = [System.ServiceProcess.ServiceController]::GetDevices() | ? {
  $services -contains $_.Name
}

$s = Get-Service | ? {
  $services -contains $_.Name
}

$d
$s

The first line just defines an array of names to match one. The next block of code uses GetDevices() to return the status of the HAXM driver. The block that follows returns the status of the Hyper-V Heartbeat Service. The last part just dumps out the results.

An alternative way is to pass the service name to Get-Service and it will return the status for the specified service. The problem is that it will error out if the specified service does not exist. And while that error message is a status report, it’s an ugly way to get that information

I named the script “hyper-stat.ps1” and when I run it on a machine with HAXM running, I get the following output

.\hyper-stat.ps1

Status   Name               DisplayName                           
------   ----               -----------                           
Running  IntelHaxm          Intel HAXM Service 

On a machine with Hyper-V and no HAXM, I get this

.\hyperv-stat.ps1

Status   Name               DisplayName                           
------   ----               -----------                           
Running  vmicheartbeat      Hyper-V Heartbeat Service    

If I disable Hyper-V, I would get the following:

.\hyperv-stat.ps1

Status   Name               DisplayName                           
------   ----               -----------                           
Stopped  vmicheartbeat      Hyper-V Heartbeat Service             

There are few ways of scripting this task. This one was simple and I have it on the machines that I use for coding.

Edit: Right after posting this, I realized it didn’t actually work. I was originally reporting on the status of vmms, the Hyper-V Virtual Machine Management Service. If Hyper-V is installed, that service will always be running, even when Hyper-V is not enabled. The Hyper-V Heartbeat service is a better test for seeing if Hyper-V is enabled.