Blog

Building a Static WordPress

Photo by Vidsplay from StockSnap

Now that I have Nginx in Front of WordPress, I thought the next logic step was to try and hide my WordPress even more. What exactly would this mean? In my mind, I figured that I would restrict access to all of the backend functions of my WordPress site to just my IP Addresses. From there, I would simply serve static versions of the content.

Part of the reason that I can do this is because my site is mostly static. I don’t allow comments or other dynamic plugins. The site is only used to publish my blog posts and that’s about it. I also setup WordPress to use the permalink format of /%year%/%monthnum%/%post_id%/

First Step, Mirror the Site to a Private Repo

Just as the heading states, I needed to first get all of my content available outside of WordPress. Luckily, I realized that I had a few previous blog posts:

that could help me accomplish the initial steps. I won’t completely bore you with the details contained in these posts. I’m going to assume that you can get a basic idea of how to setup the private repo using Creating a Private GitHub Repo. You can setup your repo however you like but for future planning purposes, I decided to create a html directory inside of it to house the website files. My initial repo looked like the following:

 % ls -al
 total 8
 drwxr-xr-x   5 salgatt  staff   160 Dec 31 08:46 .
 drwxr-xr-x  49 salgatt  staff  1568 Jan  7 12:32 ..
 drwxr-xr-x  15 salgatt  staff   480 Jan  7 09:05 .git
 -rw-r--r--   1 salgatt  staff    18 Dec 30 18:57 README.md
 drwxr-xr-x   4 salgatt  staff   128 Jan  5 21:31 html 

With the private repo created, I needed to get all of my content into the repo for later use by Nginx. I just did a wget to pull only the page content down. The reason I did this is because there were a number of js and css files that are required for the admin pages and possibly for other “things” that I might not use right away:

 % cd html
 % wget --mirror --follow-tags=a,img --no-parent https://blog.shellnetsecurity.com
 --2021-01-07 16:37:24--  https://blog.shellnetsecurity.com/
 Resolving blog.shellnetsecurity.com (blog.shellnetsecurity.com)... 157.230.75.245
 Connecting to blog.shellnetsecurity.com (blog.shellnetsecurity.com)|157.230.75.245|:443... connected.
 HTTP request sent, awaiting response... 200 OK
 Length: 17266 (17K) [text/html]
 Saving to: ‘blog.shellnetsecurity.com/index.html’
 

 blog.shellnetsecurity.com/index.html       100%[=======================================================================================>]  16.86K  --.-KB/s    in 0.09s   
...
 --2021-01-07 16:37:41--  https://blog.shellnetsecurity.com/author/salgatt/page/2/
 Connecting to blog.shellnetsecurity.com (blog.shellnetsecurity.com)|157.230.75.245|:443... connected.
 HTTP request sent, awaiting response... 200 OK
 Length: 41746 (41K) [text/html]
 Saving to: ‘blog.shellnetsecurity.com/author/salgatt/page/2/index.html’
 

 blog.shellnetsecurity.com/author/salgatt/p 100%[=======================================================================================>]  40.77K  --.-KB/s    in 0.1s    
 

 2021-01-07 16:37:44 (398 KB/s) - ‘blog.shellnetsecurity.com/author/salgatt/page/2/index.html’ saved [41746/41746]
 

 FINISHED --2021-01-07 16:37:44--
 Total wall clock time: 19s
 Downloaded: 56 files, 2.7M in 3.4s (821 KB/s) 

My wget command runs the –mirror command to ummm mirror the site. I do the –follow-tags=a,img so that I only nab the html plus images and follow only href tags. Finally, I want to stay within my site and not download any other sites’ content by issuing –no-parent. With that, I now have a blog.shellnetsecurity.com directory in my repo’s html directory.

 % ls -al
 total 0
 drwxr-xr-x   4 salgatt  staff  128 Jan  5 21:31 .
 drwxr-xr-x   5 salgatt  staff  160 Dec 31 08:46 ..
 drwxr-xr-x  18 salgatt  staff  576 Jan  7 08:38 blog.shellnetsecurity.com 

Now, I need to get all of my static content into the repo as well. In order to do that, I just did a simple copy of the static files from my container running wordpress using kubectl cp:

 % kubectl cp -n wordpress wordpress-85589d5658-48ncz:/opt/wordpress/wp-content ./blog.shellnetsecurity.com/wp-content
 tar: Removing leading `/' from member names
 % kubectl cp -n wordpress wordpress-85589d5658-48ncz:/opt/wordpress/wp-includes ./blog.shellnetsecurity.com/wp-includes
 tar: Removing leading `/' from member names 

These copy commands grab ALL files in these two directories. The idea is that I’m grabbing the js and css for any plugins running in my WordPress and any theme related files. Since these directories contain PHP files and other files I don’t need in my static repo, I remove them with a nice little find command:

 % find blog.shellnetsecurity.com/wp-includes -type f -not -name '*.js' -not -name '*.css' -not -name '*.jpg' -not -name '*.png' -delete
 % find blog.shellnetsecurity.com/wp-content -type f -not -name '*.js' -not -name '*.css' -not -name '*.jpg' -not -name '*.png' -delete 

At this point, I now have a repo that should have all of the content ready to go. I commit all of the changes and push the changes to main.

Serve the Static Repo

Like I said before, I’m not going to clutter this post with the details that can be found in Building a Kubernetes Container That Synchs with Private Git Repo. Assuming you have this all ready to go, I’m going to cut straight to the configuration portion. I’m assuming the nginx container is mounting the private repo at /dir/wordpress_static. I am also going to build upon the nginx configmap that was created in Adding Nginx in Front of WordPress. I’m first going to change the root directory to be the static WordPress blog:

         root /dir/wordpress_static/html/blog.shellnetsecurity.com; 

I also need to change some of my original reverse proxy mappings to serve most content from static but still leave a few requests go to my WordPress

         location /status {
                 return 200 "healthy\n";
         }
 
         location / {
                 try_files $uri $uri/ /index.html;
         }
 
         location /sitemap {
                 proxy_pass https://wordpress;
                 proxy_ssl_verify off;
                 proxy_set_header Host blog.shellnetsecurity.com;
                 proxy_set_header X-Forwarded-For $remote_addr;
         }
 
         location /wp-sitemap {
                 proxy_pass https://wordpress;
                 proxy_ssl_verify off;
                 proxy_set_header Host blog.shellnetsecurity.com;
                 proxy_set_header X-Forwarded-For $remote_addr;
         }
 
         location /wp-json {
                 allow 1.1.1.1;
                 allow 2.2.2.2;
                 deny all;
                 proxy_pass https://wordpress;
                 proxy_ssl_verify off;
                 proxy_set_header Host blog.shellnetsecurity.com;
                 proxy_set_header X-Forwarded-For $remote_addr;
         }
 
         location /wp-login {
                 allow 1.1.1.1;
                 allow 2.2.2.2;
                 deny all;
                 proxy_pass https://wordpress; 
                 proxy_ssl_verify off;
                 proxy_set_header Host blog.shellnetsecurity.com;
                 proxy_set_header X-Forwarded-For $remote_addr;
         }
 
         location /admin {
                 allow 1.1.1.1;
                 allow 2.2.2.2;
                 deny all;
                 proxy_pass https://wordpress;
                 proxy_ssl_verify off;
                 proxy_set_header Host blog.shellnetsecurity.com;
                 proxy_set_header X-Forwarded-For $remote_addr;
         }
 
         location /wp-admin {
                 allow 1.1.1.1;
                 allow 2.2.2.2;
                 deny all;
                 proxy_pass https://wordpress;
                 proxy_ssl_verify off;
                 proxy_set_header Host blog.shellnetsecurity.com;
                 proxy_set_header X-Forwarded-For $remote_addr;
         }

Through some trial and error, I found that I needed to have all of the following paths allowed for my admin functionalities:

  • /wp-admin
  • /admin
  • /wp-login
  • /wp-json

Since these are required for admin functions, I have made sure to run my IP restrictions on them and only allow my addresses to access them. For now, I am managing my sitemaps from within WordPress so I also allowed requests from any clients to go directly to my WordPress server still (something I’ll correct in a future post when I talk about automation). Aside from these exceptions, I’m using try_files to find the other content. This means that requests for any other content will be sent into the root directive, aka /dir/wordpress_static/html/blog.shellnetsecurity.com, aka the private repo! Notice the trailing /index.html on the directive? That just means that I’ll serve /index.html whenever the page isn’t found.

With that, I am now serving content from my mirrored content that is running from the private repo. I can still manage my WordPress site like I normally do from the backend and generate content and make changes and life is mostly good.

I am an idiot

Yes, you don’t need to tell me this! I know there are some obvious flaws in what I’ve setup like:

  • What happens when I post a new article?!
  • What do I do when WordPress is upgraded?
  • What happens when a plugin is upgraded?
  • Do you know that doing a wget for just pages won’t download pretty little images?
  • Did you know that serving /index.html for css/jpg/png/js files is ugly?
  • This manual process is terrible!

I know! I have already begun to tackle these and I’ll have more details on that when I write my Automating Static WordPress Updates (Currently in Draft). As a sneak peak to all of this, there’s a really cool WordPress plugin that will send various notifications to Slack. Oh the fun that we will have when talking about using Slack as a message bus and writing and app and and …. ok I’ll contain my excitement for now!

[Survey] What are Important Features for a Blog?

overexposed question mark
Photo by Emily Morter from StockSnap

When building a blog, it can be overwhelming knowing what all features are important to enable. Your blog software of choice can offer all kinds of features. Those features could overwhelm you while others could overwhelm your visitors. Given all of the options available, I thought that it would be interesting to gather personal preferences of those that read blogs.

Below is a survey hosted by SurveyLegend, that is aimed at gathering some of these details from you the reader. Please participate in this short survey by providing your personal preferences. I know some of these features are important for SEO rankings but I’m more concerned about what the reader thinks not the computer.

Kubernetes Upgrades Break My DigitalOcean LoadBalancer

Photo by Austin Neill from StockSnap

Disclosure: I have included some affiliate / referral links in this post. There’s no cost to you for accessing these links but I do indeed receive some incentive for it if you buy through them.

I’ve talked about it in previous posts about my thus far overall enjoyment running in DigitalOcean. While I had tinkered with a number of other cloud providers, I settled with them for many things. I do still run in some other providers like OVHCloud (maybe more on my project there for another day). Despite my love for DigitalOcean, I do have one complaint regarding their Kubernetes and their LoadBalancer.

The Problem: I’m Cheap

I guess thrifty sounds so much better but I’m cheap. It’s a fact. I have in fact created my own problem with DigitalOcean due to my cheapness. They do have a number of excellent integration points between their Kubernetes and other components such as storage and load balancers. I can issue Kubernetes commands to create a new LoadBalancer or PVC and boom life is good. My problem is that LoadBalancers cost money. To date, I have only been able to figure out a 1:1 mapping between the LoadBalancer and Kubernetes. This 1:1 means that I can only manage a single LoadBalancer per exposed port.

If I only ever intend to expose a single application to the world, this is great! This is not me. I run a number of different applications that I want to expose. That means I need to pay for a LoadBalancer for each application or do I? Here come the Forwarding Rules! Each LoadBalancer can be configured with a number of forwarding rules like so:

With these rules in place, I’m able to expose multiple ports/applications on the same load balancer. This is wonderful except upgrades to the Kubernetes clusters like to blow away my custom settings such as:

  • Forwarding Rules
  • SSL Redirects
  • Proxy Protocol
  • Backend Keepalive

For the longest time, I had to come back in reconfigure everything every time I did a Kubernetes cluster upgrade. Worse yet, I didn’t know things got blown away whenever the cluster upgraded automatically. I had setup port/application monitors to alert me when things when down so I could manually reconfigure them.

The Solution : DigitalOcean API

While the manual fix has always been a waste of time and has sometimes prevented me from upgrading Kubernetes (bad security d00d), I still did the upgrades and manually fixed it. I never really learned a “new thing” to try and get this fixed in a less manual manner. Today was the the day I changed all of that. I’m sure there’s some other way that I hadn’t thought of yet but we’re going with baby steps. Instead of taking manual screenshots of the configuration page for the LoadBalancer and then trying to manually go back in and change the settings to what I thought they were, I am now using the API. Some good general documentation on the DigitalOcean API can be found here:

Setting Up API Access

The first step in getting all of this working is getting an API token. There’s no sense reinventing the wheel when DigitalOcean already has something written up very well such as How to Create a Personal Access Token. This walks you through creating the token to be used with the API. It is very important to make sure you create a token that has write access.

Get Your Existing LoadBalancer Configuration

With token in hand, it is time to get a copy of your existing configuration with a curl command. First, you need to know the id of your load balancer so we just query for all load balancers:

% curl -X GET -H "Content-Type: application/json" -H "Authorization: Bearer your_api_token_here" https://api.digitalocean.com/v2/load_balancers|jq .   
 {
   "load_balancers": [
     {
       "id": "ffff-ffff-ffff-ffff-b75c",
       "name": "my-lb-01",
       "size": "lb-small",
       "algorithm": "round_robin",
       "status": "active",
       "created_at": "2019-10-25T19:56:00Z",
       "forwarding_rules": [
         {
           "entry_protocol": "tcp",
           "entry_port": 80,
           "target_protocol": "tcp",
           "target_port": 31640,
           "certificate_id": "",
           "tls_passthrough": false
         },
         {
           "entry_protocol": "tcp",
           "entry_port": 4514,
           "target_protocol": "tcp",
           "target_port": 31643,
           "certificate_id": "",
           "tls_passthrough": false
         }
       ],
       "region": {
         "name": "San Francisco 2",
         "slug": "sfo2"
       },
       "tag": "",
       "droplet_ids": [
         111,
         222,
         333
       ],
       "redirect_http_to_https": false,
       "enable_proxy_protocol": false,
       "enable_backend_keepalive": false,
     },
     {
       "id": "ffff-ffff-ffff-ffff-72a4",
       "name": "my-lb-02",
       "size": "lb-small",
       "algorithm": "round_robin",
       "status": "active",
       "created_at": "2020-12-02T07:54:13Z",
       "forwarding_rules": [
         {
           "entry_protocol": "https",
           "entry_port": 443,
           "target_protocol": "http",
           "target_port": 31645,
           "certificate_id": "aaaa-aaaa-aaaa-aaaa-bcf8",
           "tls_passthrough": false
         },
         {
           "entry_protocol": "tcp",
           "entry_port": 80,
           "target_protocol": "tcp",
           "target_port": 31645,
           "certificate_id": "",
           "tls_passthrough": false
         }
       ],
       "region": {
         "name": "San Francisco 2",
         "slug": "sfo2"
       },
       "tag": "",
       "droplet_ids": [
         111,
         222,
         333
       ],
       "redirect_http_to_https": true,
       "enable_proxy_protocol": true,
       "enable_backend_keepalive": true,
     }
   ],
   "links": {},
   "meta": {
     "total": 2
   }
 }

There are two load balancers here in this example, my-lb-01 and my-lb-02. While my-lb-01 was my original load balancer that gave me the most trouble, I’m going to focus on my-lb-02 since it has more customizations not just to the forwarding rules.

We need to first identify the configuration that we’d like to save. Then, we’ll save this configuration into it’s own json, let’s call it my-lb-02.json. Notice in the above JSON, the configurations are housed within a “loadbalancer” array? In order to create our my-lb-02.json file, we simply pull the single JSON element from the array like this:

     {
       "id": "ffff-ffff-ffff-ffff-72a4",
       "name": "my-lb-02",
       "size": "lb-small",
       "algorithm": "round_robin",
       "status": "active",
       "created_at": "2020-12-02T07:54:13Z",
       "forwarding_rules": [
         {
           "entry_protocol": "https",
           "entry_port": 443,
           "target_protocol": "http",
           "target_port": 31645,
           "certificate_id": "aaaa-aaaa-aaaa-aaaa-bcf8",
           "tls_passthrough": false
         },
         {
           "entry_protocol": "tcp",
           "entry_port": 80,
           "target_protocol": "tcp",
           "target_port": 31645,
           "certificate_id": "",
           "tls_passthrough": false
         }
       ],
       "region": {
         "name": "San Francisco 2",
         "slug": "sfo2"
       },
       "tag": "",
       "droplet_ids": [
         111,
         222,
         333
       ],
       "redirect_http_to_https": true,
       "enable_proxy_protocol": true,
       "enable_backend_keepalive": true,
     }

We need to remove a few useless items from that JSON so remove the following:

  • status
  • name
  • size
  • created_at
  • region (do remember the “slug” entry as we’ll need this to recreate the region)

As noted above, we also need to remove the existing region entry and instead replace it with the value of “slug” aka “sfo2” in this example. With those changes made, here’s our new JSON:

     {
       "id": "ffff-ffff-ffff-ffff-72a4",
       "algorithm": "round_robin",
       "forwarding_rules": [
         {
           "entry_protocol": "https",
           "entry_port": 443,
           "target_protocol": "http",
           "target_port": 31645,
           "certificate_id": "aaaa-aaaa-aaaa-aaaa-bcf8",
           "tls_passthrough": false
         },
         {
           "entry_protocol": "tcp",
           "entry_port": 80,
           "target_protocol": "tcp",
           "target_port": 31645,
           "certificate_id": "",
           "tls_passthrough": false
         }
       ],
       "region": "sfo2",
       "tag": "",
       "droplet_ids": [
         111,
         222,
         333
       ],
       "redirect_http_to_https": true,
       "enable_proxy_protocol": true,
       "enable_backend_keepalive": true,
     }

How Do I Unbreak Things in the Future?

I’m glad you asked! Now that you have your my-lb-02 JSON file ready to go, you can simply wait for the next upgrade of your Kubernetes cluster to rebuild everything. Below, you can see my-lb-02 broken in the DigitalOcean control panel:

There’s one little catch to fixing everything. You’ll need to first get the IDs of the new cluster nodes in order to be able to add them to the load balancer. Whenever the cluster is upgraded, DigitalOcean deletes the old versioned node and adds in a new versioned one. You can do this by doing a GET to one of the load balancer’s configurations:

 % curl -X GET -H "Content-Type: application/json" -H "Authorization: Bearer your_api_token_here" https://api.digitalocean.com/v2/load_balancers/ffff-ffff-ffff-ffff-72a4|jq .load_balancer.droplet_ids
 [
   123,
   456,
   789
 ] 

In order to make my life easier, I piped my results through jq and told it to only bring back the json path I cared about, load_balancer.droplet_ids. Now we see that the droplets have changed from our original list of 111, 222, 333 to 123, 456, 789. We need to make this change to our JSON

     {
       "id": "ffff-ffff-ffff-ffff-72a4",
       "algorithm": "round_robin",
       "forwarding_rules": [
         {
           "entry_protocol": "https",
           "entry_port": 443,
           "target_protocol": "http",
           "target_port": 31645,
           "certificate_id": "aaaa-aaaa-aaaa-aaaa-bcf8",
           "tls_passthrough": false
         },
         {
           "entry_protocol": "tcp",
           "entry_port": 80,
           "target_protocol": "tcp",
           "target_port": 31645,
           "certificate_id": "",
           "tls_passthrough": false
         }
       ],
       "region": "sfo2",
       "tag": "",
       "droplet_ids": [
         123,
         456,
         789
       ],
       "redirect_http_to_https": true,
       "enable_proxy_protocol": true,
       "enable_backend_keepalive": true,
     }

With the JSON updated, we now issue a PUT command to the load balancer API for the specific load balancer like so:

 % curl -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer your_api_token_here" https://api.digitalocean.com/v2/load_balancers/ffff-ffff-ffff-ffff-72a4 -d @my-lb-02.json

Now we can go look at the control panel again and confirm everything is back to normal!

Everything Works Great!

After an upgrade runs, I can simply come back through with a few minor steps and put everything back the way it should. Yes, there’s still some manual aspects to this and automating all of it shouldn’t be too terrible but I’ll save that for another time when I decide that this manual process is just too much anymore. Although, it took me nearly a year to hate the original manual process….

Adding Nginx in Front of WordPress

Photo by Lenharth Systems from StockSnap

The future is here! In my previous article, Testing Out the Digital Ocean Container Registry, I talked about using the Digital Ocean Container Registry to build a custom nginx. In that article, I talked about the future, aka a future, aka this post. When I moved to WordPress, I did so using Digital Ocean’s 1-Click install to drop WordPress into my Kubernetes cluster. This was the easy way to go for sure. I already run Kubernetes so deploying it to an existing cluster made life easier on me. Who doesn’t love it when life is made easier?

There are a few drawbacks to the 1-Click install. I’m planning to tinker with something really cool down the road to fix one of those problems (I know the future again). Luckily, I’m going to address my first initial concern in this post. What is that concern you ask? Protecting my WordPress admin of course! Sure, there are a number of WordPress vulnerabilities roaming around and talks of zero days and the sort. I make life easier on any attacker if I just leave my WordPress admin open to anyone. In this post, we look at taking my custom nginx and deploying it in front of my WordPress site to enforce IP access control to the admin page.

Setting Up the Container Registry for Kubernetes

In my Testing Out the Digital Ocean Container Registry, I explained how to get a custom nginx into the Container Registry. In order to use that container and registry with my cluster, I had to enable DigitalOcean Kubernetes integration in the settings of the registry. You can do the same by doing the following:

  1. Login to your DigitalOcean account
  2. Go to the Container Registry link
  3. Click on the Settings tab of the Container Registry
  4. Click the Edit button next to DigitalOcean Kubernetes Integration
  5. Place a check mark next to the Kubernetes clusters that you want to have access to this registry (Note, if you have multiple namespaces, this action will add access for all namespaces).

Once these steps are complete, you can confirm access by looking for a new secrets in your cluster:

# kubectl get secrets
NAME                   TYPE                                  DATA   AGE
default-token          kubernetes.io/service-account-token   3      423d
json-key               kubernetes.io/dockerconfigjson        1      396d
k8-registry            kubernetes.io/dockerconfigjson        1      18d
key-secret             Opaque                                2      419d

Notice the k8-registry secret that I now have in my secrets list? You can also see that this exists in my wordpress namespace as well:

# kubectl get secrets -n wordpress
NAME                  TYPE                                  DATA   AGE
default-token         kubernetes.io/service-account-token   3      18d
k8-registry           kubernetes.io/dockerconfigjson        1      18d
wp                    Opaque                                1      18d
wp-db                 Opaque                                2      18d

Adding Nginx to the Cluster

This should be super easy! I start by first creating configMap that stores my Nginx configuration:

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
  namespace: wordpress
  labels:
    app: nginx
    release: wordpress
data:
  siteConfig: |
    server {
        listen 8080 default_server;
        listen [::]:8080 default_server;

        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location /status {
                return 200 "healthy\n";
        }

        location / {
                proxy_pass http://wordpress;
                proxy_set_header Host blog.shellnetsecurity.com;
                proxy_set_header X-Forwarded-For $remote_addr;
        }

        location /admin {
                allow 1.1.1.1;
                allow 2.2.2.2;
                deny all;
                proxy_pass http://wordpress;
                proxy_set_header Host blog.shellnetsecurity.com;
                proxy_set_header X-Forwarded-For $remote_addr;
        }

        location /wp-admin {
                allow 1.1.1.1;
                allow 2.2.2.2;
                deny all;
                proxy_pass http://wordpress;
                proxy_set_header Host blog.shellnetsecurity.com;
                proxy_set_header X-Forwarded-For $remote_addr;
        }
    }

  serverConfig: |
    user www-data;
    worker_processes auto;
    pid /run/nginx.pid;
    include /etc/nginx/modules-enabled/*.conf;

    events {
        worker_connections 768;
    }

    http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        include /usr/local/nginx/conf/mime.types;
        default_type application/octet-stream;
        access_log /dev/stdout;
        error_log /dev/stdout;
        gzip on;
        
        include /etc/nginx/sites-enabled/*;
    }

    daemon off;

I mostly added a set of standard nginx configurations. If you look at the serverConfig closely, you’ll notice that I’ve directed the access_log and error_log to /dev/stdout. This is so all of the logs are written to stdout (duh). This also allows me to run kubectl logs -f on the created pod and see the access and error logs.

Nginx is going to be acting like a reverse proxy so I took a relatively standard default site-available configuration and added a few new location blocks. The /status block is simply for me to perform healthchecks on the running nginx instance. The other statements are proxy_pass statements to send requests to the “wordpress” pod that was installed by the 1-Click install. I’m also making sure that I send over the Host header with blog.shellnetsecurity.com. If I don’t do this, the 1-Click install will build funky URLs that don’t work. Luckily, it will read the Host header and build links based upon that. I force the host header to be what I want with this statement.

Finally, you’ll see my allow statements for 1.1.1.1 and 2.2.2.2 (not really my IPs but let’s play make believe). These are followed by deny all. This should make it so that only my 1.1.1.1 and 2.2.2.2 addresses are allowed to /admin and /wp-admin. All others will be denied.

Next, I create a Deployment yaml that tells Kubernetes what containers to build and how to use my configMap:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: wordpress
  labels:
    app: nginx
    release: wordpress
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
      release: wordpress
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: nginx
        release: wordpress
    spec:
      volumes:
      - name: siteconfig
        configMap:
          name: nginx-config
          items:
          - key: siteConfig
            path: default
      - name: serverconfig
        configMap:
          name: nginx-config
          items:
          - key: serverConfig
            path: nginx.conf
      imagePullSecrets:
      - name: k8-registry
      containers:
      - name: nginx
        image: registry.digitalocean.com/k8-registry/c-core-nginx:1.1
        ports:
        - containerPort: 8080
        volumeMounts:
        - name: siteconfig
          mountPath: /etc/nginx/sites-enabled/default
          subPath: default
        - name: serverconfig
          mountPath: /usr/local/nginx/conf/nginx.conf
          subPath: nginx.conf

Take note to the blue colored text above. I am using the imagePullSecrets configuration to tell kubernetes that it will need credentials to access the container registry where my image sits. I am also pointing it to the k8-registry credentials that were added by the DigitalOcean Kubernetes Integration change we made earlier. Finally, I am also providing the full path, version tag included, to the custom image I am hosting in the DigitalOcean registry with the image statement pointing to registry.digitalocean.com/k8-registry/c-core-nginx:1.1.

Next up, I need to add a NodePort that I can configure on the load balancer to send traffic over.

apiVersion: v1
kind: Service
metadata:
  namespace: wordpress
  name: nginx
  labels:
    app: nginx
    release: wordpress
spec:
  selector:
    app: nginx
    release: wordpress
  type: NodePort
  ports:
    - port: 8080
      nodePort: 31645

So I do a little kubectl apply -f to those yaml files I just created. Everything comes up. Next step is to setup the load balancer to forward traffic over. Since I have the nodePort configured as 31645, I just need to tell the load balancer to send traffic that I want to that port. I don’t want to mess with the existing setup so I decide to simply forward http port 8443 over to http port 31645.

Everything should be all set, so let’s open a browser and test

I am getting blocked like I expected! The problem is that I’m coming from my 2.2.2.2 address. What could be the issue? Good thing I told the logs to be sent to stdout so let’s check them for 403s:

kubectl logs -f -n wordpress nginx-9cdf87f68-tss6x|grep 403
...
10.126.32.147 - - [20/Dec/2020:13:37:33 +0000] "GET /admin HTTP/1.1" 403 187 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
...

I see the problem! That is not my 2.2.2.2 address! That was my request though. It seems that I’m not getting the real IP of the client but instead internal IPs from the load balancer.

Enter the PROXY Protocol

For access control, I didn’t want to rely on the X-Forwarded-For header since it is something that comes from the client. This means that someone could spoof the headers to get around my control. In addition to that, the DigitalOcean load balancer does not send this header so it’s a moot point. DigitalOcean does provide the PROXY Procotol in it’s load balancers but not by default. The short explanation is that this protocol will send in the IP like I want but it requires some configuration. It’s either enable PROXY protocol or not as well and there is no mixing or matching.

Enabling the PROXY Protocol on the load balancer was easy. You simply enable it in the Settings of the load balancer.

It is very important to NOT enable this until Nginx was configured. Otherwise, the site would have gone down. I explain my specific configuration below, but you are also welcome to explore the Nginx documentation on the PROXY Protocol.

Configuring Nginx

In my Testing Out the Digital Ocean Container Registry article, I built nginx with the PROXY protocol capability by enabling the ngx_http_realip module. It was like I wrote that previous article after getting this all working….? With the module already enabled, it was pretty easy to simply update the configuration and go. I added the following line to my sever block:

        set_real_ip_from 10.126.32.0/24;

Just like that, I was good to go so I thought. I was now getting denied only sometimes. I checked the logs again to find out why:

kubectl logs -f -n wordpress nginx-9cdf87f68-tss6x
...
10.126.32.147 - - [20/Dec/2020:13:37:33 +0000] "GET /admin HTTP/1.1" 403 187 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
2.2.2.2 - - [20/Dec/2020:18:35:49 +0000] "POST /admin HTTP/1.1" 200 98 "https://blog.shellnetsecurity.com/wp-admin/post.php?post=93&action=edit" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
3.3.3.3 - - [20/Dec/2020:13:37:33 +0000] "GET /admin HTTP/1.1" 403 187 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
...

Let’s chat about the set_real_ip_from statement. We need to add this statement for all potential IP addresses that we trust to provide us with the real client IP. In my case, it turned out that 10.126.32.0/24 was not a large enough block for the internal IP addresses so I needed to change that to a /16. Also, notice the 3.3.3.3 address? That’s the external IP of one of nodes in the kubernetes cluster. Armed with that knowledge, I expanded my server block to include multiple set_real_ip_from statements:

        set_real_ip_from 10.126.32.0/16;
        set_real_ip_from 3.3.3.3;
        set_real_ip_from 4.4.4.4;
        set_real_ip_from 5.5.5.5;

I reloaded everything and tested again and success every time! I got denied when I wasn’t on my 1.1.1.1 or 2.2.2.2 address. I also see others getting denied as well. When I’m sitting on 1.1.1.1 or 2.2.2.2, I’m able to get into my WordPress admin!

Testing Out the Digital Ocean Container Registry

Disclosure: I have included some affiliate / referral links in this post. There’s no cost to you for accessing these links but I do indeed receive some incentive for it if you buy through them.

Photo by Guillaume Bolduc from StockSnap

The house use to be full of random computers and networking gear but I’ve reduced the home presence over the years. I’ve messed with a number of cloud providers both inexpensive and expensive. My base for the majority of my toys reside in Digital Ocean. I’ve really liked what they’ve done over the years. Recently, they announced a Container Registry. If you follow this blog, then you remember my post, Posting a Custom Image to Docker Hub. In that post, I explained how to build an image and push it up Docker Hub. Some images might not need to be public for whatever the reason. Needless to say, Digital Ocean’s Container Registry announcement, intrigued me. With the move to WordPress, I figured that I should also build a custom nginx build to run in my Kubernetes cluster on Digital Ocean.

Building the Custom Nginx

This part was pretty easy. I simply created a Dockerfile for the build.

FROM ubuntu

ENV DEBIAN_FRONTEND noninteractive

MAINTAINER Scott Algatt

RUN apt-get update \
    && apt-get install -y libjansson-dev libcurl4-openssl-dev libapr1-dev libaprutil1-dev libssl-dev build-essential devscripts libtool m4 automake pkg-config libpcre3-dev zlib1g-dev\
    && apt -y upgrade \
    && apt -y autoremove \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* \
    && curl -o /tmp/nginx.tgz http://nginx.org/download/nginx-1.18.0.tar.gz

WORKDIR /tmp

RUN tar zxf nginx.tgz \
    && cd nginx-1.18.0 \
    && ./configure --with-http_realip_module\
    && make \
    && make install

EXPOSE 80
CMD ["/usr/local/nginx/sbin/nginx"]

As you can see from the Dockerfile, this is a really super simple build. It is also not very custom aside from my compile command where I’ve added –with-http_realip_module. This little addition is something that I will use later in a future post (I know everything will be in the future) but you can see what it does by visiting the nginx documentation. Anyhow, there you go. Aside from the configure command, I’m just setting up ubuntu to compile code and I download nginx and compile it. Then expose port 80 and run nginx.

Once you have created the Dockerfile, you can run a build to generate your docker image. You’ll see that my build command tags the build with a name, c-core-nginx, and specific version, 1.1. I would suggest doing this to help keep versions straight in your repository.

% docker build -t c-core-nginx:1.1 .
Sending build context to Docker daemon  21.72MB
Step 1/9 : FROM ubuntu
 ---> 4e2eef94cd6b
Step 2/9 : ENV DEBIAN_FRONTEND noninteractive
 ---> Using cache
 ---> decc285ce9e4
Step 3/9 : MAINTAINER Scott Algatt
 ---> Using cache
 ---> 197e4c81b654
Step 4/9 : RUN apt-get update     && apt-get install -y libjansson-dev libcurl4-openssl-dev libapr1-dev libaprutil1-dev libssl-dev build-essential devscripts libtool m4 automake pkg-config libpcre3-dev zlib1g-dev    && apt -y upgrade     && apt -y autoremove     && apt-get clean     && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*     && curl -o /tmp/nginx.tgz http://nginx.org/download/nginx-1.18.0.tar.gz
 ---> Using cache
 ---> d5c8a70c412f
Step 5/9 : COPY ./perimeterx-c-core /tmp/perimeterx-c-core
 ---> Using cache
 ---> d325026c19b6
Step 6/9 : WORKDIR /tmp
 ---> Using cache
 ---> 8fb23db246a3
Step 7/9 : RUN tar zxf nginx.tgz     && cd nginx-1.18.0     && ./configure --add-module=/tmp/perimeterx-c-core/modules/nginx --with-threads --with-http_realip_module    && make     && make install
 ---> Using cache
 ---> 25af69d04a9f
Step 8/9 : EXPOSE 80
 ---> Using cache
 ---> e74b4cc64160
Step 9/9 : CMD ["/usr/local/nginx/sbin/nginx"]
 ---> Using cache
 ---> 6f10e3bebefc
Successfully built 6f10e3bebefc
Successfully tagged c-core-nginx:1.1

After the build completes, you can confirm that your image is listed on your local docker repo

% docker images c-core-nginx
REPOSITORY     TAG       IMAGE ID       CREATED       SIZE
c-core-nginx   1.1       6f10e3bebefc   2 weeks ago   584MB
c-core-nginx   1.0       b3673b4bf518   2 weeks ago   584MB

Pushing Your Image to the Container Registry

I’m not going to spend a ton of effort in this section because the Digital Ocean Container Registry announcement I posted above explains the setup really well. At a high level, you simply complete the following steps:

  1. Install and configure doctl (assuming you had never done this like me)
  2. Login into your Digital Ocean account
  3. Go to the Container Registry link
  4. Create the Container Registry
  5. Login to your registry using the doctl command
  6. Push your desired container(s) to the registry

The below image shows a screenshot of my c-core-nginx images that I uploaded to my Container Registry.

Notice something really cool? The size of those images in my local registry is 584MB but they are roughly 194MB when uploaded. They are being compressed in the registry. This is a really nice feature since the initial free tier of Digital Ocean’s Container Registry is a single repo of 500MB.

In the future, you will see how I actually used this new feature for fun and zero profit.

Making the Lights Dance

My previous post, Making the Little Lights Twinkle, covered my coding of the NodeJS server that could take simply relay numbers and command (on|off) and put them to use. Now that I have a server/service up and running, it was time for me to be able to control the lights. I removed my Orchestra of Lights and put my new Raspberry Pi hardware device in its place. The only downside is that my setup has 8 outlets and the Orchestra of Lights only had 6. As I built out some of my light sequences, I noticed there’s a delay due to relays 7 and 8 being triggered but nothing being connected to them. Maybe that’s something I can do for next year. I’ll plan for 8 lighting areas instead of just 6.

In addition to needing to be able to plan for two more strands of lights, I still hadn’t figured out my audio configuration yet. I’ve only had the time to focus on the lights themselves. For the time being, I’ve got a weatherproof bluetooth speaker outside that I sync my iPad to for music. I just tell my iPad to loop through a playlist that my wonderful wife has put together. Thank you deer!

The Initial Script

While I still struggled to find some time to continue to research making the lights dance to music, I figured it was a really good idea to get something up and running. I thought randomness was key. I wanted it to be random because I was sick of the Orchestra of lights running through the same/similar light pattern over and over and over and over…..and over. With that, I built the initial script control my lights:

#!/bin/bash

COMMANDS=("off" "on")
i=0

trap exitout SIGINT

exitout() {
  echo "We Are Done Here!"
  exit
}

while :
do
  CMD=$(( ${RANDOM} % 2 ))
  RELAY=$(( ${RANDOM} % 8 + 1 ))
  curl 127.0.0.1:8080/light/$RELAY/${COMMANDS[$CMD]}
  echo $RELAY ${COMMANDS[$CMD]}
  sleep 0.2
done

Obviously, this is a really quick hack of a script but it works. It’s also obvious that it is a simple shell script. I created the array “COMMANDS” with two elements “off” and “on”. I ended up not using “i” but oh well it’s still here. I have the script setup to exit “cleanly” by calling exitout whenever someone presses CTRL+C on the keyboard. You need this because as you can tell the script is created with a while loop that never exits.

Let’s talk about what is going on inside that while loop. With each iteration, I’m setting CMD to a random number modulo 2 which gives us either 0 or 1. I’m also setting RELAY to a random number modulo 8 which gives us something 0 – 7 on each iteration. You’ll notice I add +1 so that I actually make RELAY be 1 – 8. Next, I run a curl command with my relay number and the element 0 or 1 aka off on from the COMMANDS array. From there, I just echo out what I sent to the server and then sleep for 0.2 seconds. This loop runs forever until something crashes or the user does CTRL+C.

Oh My Goodness This is Ok

The above simple script did the trick. This made my lights randomly turn on and off. I was quite happy with the results we got with this. I had light strands turning on and off. Sometimes, the lights were doing something that appeared like it was in tune with the music. There was one little flaw in this. The flaw was that because it was random, you could have the same relay being given the same command or the randomness would focus on a single light strand turning on and off.

Ultimately, my major concern was that we had too many lights out at the same time. So, this was a really good initial step and worked well for my immediate wants and needs. I wanted more. I got bored with random and put a little time into something a little more.

Building the More Interesting Client

Ok like I said before, I was getting bored with the original client script. I wanted to be able to do just a little bit more. I built a script that does a few sequences as you can see below.

#!/bin/bash

COMMANDS=("blinkUp" "blinkDown" "danceUp" "danceDown" "blinkAll" "crazyRun")
i=0

trap exitout SIGINT

exitout() {
  echo "We Are Done Here!"
  exit
}

allLights() {
  a=1
  while [ $a -le 8 ]
  do
    curl 127.0.0.1:8080/light/$a/$1
    echo ""
    a=$(( a + 1 ))
  done 
}

blinkUp() {
  echo "Blinking Up"
  allLights on
  a=1
  while [ $a -le 8 ]
  do
    curl 127.0.0.1:8080/lights/$a/off
    echo ""
    sleep 0.5
    curl 127.0.0.1:8080/lights/$a/on
    echo ""
    sleep 1
    a=$(( a + 1 ))
  done
}

blinkDown() {
  echo "Blinking Down"
  allLights on
  a=8
  while [ $a -ge 1 ]
  do
    curl 127.0.0.1:8080/lights/$a/off
    echo ""
    sleep 0.5
    curl 127.0.0.1:8080/lights/$a/on
    echo ""
    sleep 1
    a=$(( a - 1 ))
  done
}

danceUp() {
  echo "Dancing Up"
  allLights off
  a=1
  while [ $a -le 8 ]
  do
    curl 127.0.0.1:8080/lights/$a/on
    echo ""
    sleep 0.5
    curl 127.0.0.1:8080/lights/$a/off
    echo ""
    a=$(( a + 1 ))
  done
}

danceDown() {
  echo "Dancing Down"
  allLights off
  a=8
  while [ $a -ge 1 ]
  do
    curl 127.0.0.1:8080/lights/$a/on
    echo ""
    sleep 0.5
    curl 127.0.0.1:8080/lights/$a/off
    echo ""
    a=$(( a - 1 ))
  done
}

blinkAll() {
  echo "Blinking All"
  allLights on
  allLights off
  allLights on
  allLights off
  allLights on
  allLights off
}

crazyRun() {
  echo "Doing Crazy Shit"
  danceUp
  danceDown
  allLights off
  sleep 0.5
  allLights on
  sleep 0.5
  danceDown
  danceUp
  blinkAll
  danceUp
  danceDown
  danceUp
  danceDown
}

while :
do
  CMD=$(( ${RANDOM} % 6 ))
  ${COMMANDS[$CMD]}
  sleep 0.2
done

I’ve added a bunch of different functions to this new script:

allLightsThis function takes an argument of “on” or “off”. When called, it will either turn on or off all of the lights by issuing curl commands for all relays and either on or off.
blinkUpThis function starts by turning on all of the lights and then every 0.5 seconds it turns off and then on a light staying at 1 and continuing through 8.
blinkDownThis function is similar to blinkUp but it just works backwards from 8 through 1.
danceUpThis function starts by turning all of the lights off and then works its way up from 1 through to 8. It works up by turning each light on and then off.
danceDownThis function is similar to danceUp but it just works backwards starting at 8 and continuing through to 1.
blinkAllThis function just flashes all of the lights on and off.
crazyRunThis function just takes each of the above options and runs them all as a sequence that I’ve picked out.

Finally, the while statement in this script is now being used to randomly select one of the predefined sequences. So now I’ve got something a little more sophisticated to run my light show. I still want to up the game on this to sequence on its own to music and add more lights. Here’s an example below.

This got us through this Christmas season so more upgrades for next year and I can’t wait!

Making the Little Lights Twinkle

My previous post, Building the RaspberryPi Christmas Light Box, explained at a hight level building out the hardware. That step was a little scary than I think it should be but it all worked out just fine in the end. Now that I had everything put together and powered on, I was stuck here:

pi@raspberrypi:~ $ 

What are the next steps? I’ve got this box all wired up and ready to go but now I’m just sitting at a prompt waiting. As I mentioned before, I broke this down into a few parts to make my life easier and not get overwhelmed. After doing some more and more reading, I figured I had two options. I could program everything in Python or I could program everything in NodeJS.

I’m comfortable either language and no matter how hard I tried I kept going in circles. Something told me that I should write it in NodeJS because I felt that I should consider a client-server model. There were TONS of examples of people that had written all kinds of programs and libraries for handling sound and music and lights and GPIOs. I ended up throwing myself a curve ball. I decided that the client-server model was indeed what I should consider for future expansion of my new found hobby of Christmas tree lighting so I decided on NodeJS.

Well Folks, Here’s the Start of the Code

It all started pretty easy. I wanted to first make sure I had all of my GPIOs hooked up correctly. I wanted to make sure things blinked on and off like I expect. It seems that the only thing I needed to make NodeJS work was the onoff package. I popped into a directory on my Pi and installed it:

npm install onoff --save

Great! I guess the next step was to steal one of the sample JS scripts that gives you an example of how to make a relay turn on and off (my blink.js is born):

var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO
var LED = new Gpio(23, 'out'); //use GPIO pin 23, and specify that it is output
var blinkInterval = setInterval(blinkLED, 250); //run the blinkLED function every 250ms

function blinkLED() { //function to start blinking
  if (LED.readSync() === 0) { //check the pin state, if the state is 0 (or off)
    LED.writeSync(1); //set pin state to 1 (turn LED on)
  } else {
    LED.writeSync(0); //set pin state to 0 (turn LED off)
  }
}

function endBlink() { //function to stop blinking
  clearInterval(blinkInterval); // Stop blink intervals
  LED.writeSync(0); // Turn LED off
  LED.unexport(); // Unexport GPIO to free resources
}

setTimeout(endBlink, 5000); //stop blinking after 5 seconds

That seemed to work just wonderfully so I wanted to make sure that I could get all of the relays to go click click for me so enter the flowled.js (This is a great way to annoy ANYONE within ear shot. Remember from my previous post that I have the analog relays so they go *click click* when they turn on and off). While my wife was excited at the thoughts of our new Christmas lighting show, she was getting annoyed of the various clicking combinations that I came up. Thank you for your patience and appearing to be just as excited as I was deer!:

var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO
var RELAY01 = new Gpio(24, 'out'), //use declare variables for all the GPIO output pins
  RELAY02 = new Gpio(25, 'out'),
  RELAY03 = new Gpio(23, 'out'),
  RELAY04 = new Gpio(22, 'out'),
  RELAY05 = new Gpio(12, 'out'),
  RELAY06 = new Gpio(13, 'out'),
  RELAY07 = new Gpio(16, 'out'),
  RELAY08 = new Gpio(26, 'out');

//Put all the RELAY variables in an array
var leds = [RELAY01, RELAY02, RELAY03, RELAY04, RELAY05, RELAY06, RELAY07, RELAY08];
var indexCount = 0; //a counter
dir = "up"; //variable for flowing direction

var flowInterval = setInterval(flowingLeds, 100); //run the flowingLeds function every 100ms

function flowingLeds() { //function for flowing Leds
  leds.forEach(function(currentValue) { //for each item in array
    currentValue.writeSync(0); //turn off RELAY
  });
  if (indexCount == 0) dir = "up"; //set flow direction to "up" if the count reaches zero
  if (indexCount >= leds.length) dir = "down"; //set flow direction to "down" if the count reaches 7
  if (dir == "down") indexCount--; //count downwards if direction is down
  leds[indexCount].writeSync(1); //turn on RELAY that where array index matches count
  if (dir == "up") indexCount++ //count upwards if direction is up
};

function unexportOnClose() { //function to run when exiting program
  clearInterval(flowInterval); //stop flow interwal
  leds.forEach(function(currentValue) { //for each RELAY
    currentValue.writeSync(0); //turn off RELAY
    currentValue.unexport(); //unexport GPIO
  });
};

process.on('SIGINT', unexportOnClose); //function to run when user closes using ctrl+c

Time to Build the REST API!

Now that I had sufficiently annoyed everyone in the house by showing them the little LED on the relays blink and click, I think it was time to actually put this to work for me. All good client server models work via APIs, right? I had dreams of multiple Pis being setup around the yard and house being controlled by a central Pi that played the music and made all of the magical lighting happen. This will indeed be the case in a few years I’m sure. But we’re crawling before we can dead sprint. With that, I added http to my project with a little:

npm install http --save

So now I had onoff and http installed and saved to my package.json. With onoff and http ready to go, it was time for me to create the REST API server. I started with a few constants:

var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO
var RELAY1 = new Gpio(24, 'out'), //use declare variables for all the GPIO output pins
  RELAY2 = new Gpio(25, 'out'),
  RELAY3 = new Gpio(23, 'out'),
  RELAY4 = new Gpio(22, 'out'),
  RELAY5 = new Gpio(12, 'out'),
  RELAY6 = new Gpio(13, 'out'),
  RELAY7 = new Gpio(16, 'out'),
  RELAY8 = new Gpio(26, 'out');

const NUM_RELAYS = 8;
const RELAYS = [RELAY1, RELAY2, RELAY3, RELAY4, RELAY5, RELAY6, RELAY7, RELAY8];

const COMMANDS = [ 'on', 'off' ];

const PORT = process.env.PORT || 8080

Of course, the first var is to bring in the GPIO control and then I mapped the various RELAY vars to the appropriate gpios that I was using on my Pi. I have a total of 8 relays to choose from and then I also created two arrays, RELAYS and COMMANDS. These will make more sense later. Finally, I’m defining a default port for my API server to run on:

var http = require('http').createServer(handler); //require http server, and create server with function handler()

console.log(`Server Running on ${PORT}`);
http.listen(PORT);

Then we fire up the http server with my “handler” middleware. The handler function is below:

function handler (req, res) { //create server
  if (req.url.startsWith('/light') && req.method == 'GET') {
    getCommands(req.url, (err, commands) => {
      if(err) {
        var message = `{"test": "Failed","message": "${err}"}`;
      } else {
        var message = doCommand(commands.relay, commands.command);
      }
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      res.end(message);
    })
  } else if ( req.url == '/status' && req.method == 'GET' ) {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end('{"status": 200, "message": "test ok"}');
  } else {
    //Set the response HTTP header with HTTP status and Content type
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end('{"status": 200, "message": "ok"}');
  }
}

I setup handler to push two routes that will accept GET requests, /light and /status. The /light route is where everything happens and /status was future proofing to make sure that we could possibly check the status of the server when we build the monolithic light show like Clark W! Of course, the final “else” is my garbage eat all where I just return “ok” to any request.

For those that don’t know, I’m a security geek so I built my getCommands function into the /light route:

function getCommands(string, cb) {

  var data = string.split('/');

  if(data.length != 4) {
    return cb('Wrong Number of Arguments Provided');
  }

  if(!COMMANDS.includes(data[3])) {
    return cb('Unsupported Command');
  }

  if(data[2] > NUM_RELAYS || data[2] < 1) {
    return cb('Sorry We Cannot Control That One');
  }

  result = {
    "relay" : data[2],
    "command" : data[3]
  }

  return cb(null, result);
}

The purpose of this function is to make sure we’re not fed garbage by anyone. I’m checking to make sure we get the right number of items in the request path (aka /light/<RELAY #>/<COMMAND>). If these fail, then I fail the request and do nothing. Assuming we pass validation, we get to the work horse, doCommand:

function doCommand(relay, command) {
  var myIndex = relay - 1;
  try {
    RELAYS[myIndex].writeSync(COMMANDS.indexOf(command));
    var message = 'OMG This is Great!';
  } catch (e) {
    var message = e;
  }
  var resp = `{"status": "Ok", "message": "${message}"}`

  return resp;
}

This function just takes the received command (on or off) and runs it against the specified relay (1 – 8). In curl the command would look a little something like this to turn on relay 4:

$ curl localhost:8080/light/4/on
{"status": "Ok", "message": "OMG This is Great!"}

To turn off the same relay, we would issue:

$ curl localhost:8080/light/4/off
{"status": "Ok", "message": "OMG This is Great!"}

Now I have a NodeJS server that can handle REST API calls to be able to turn on and off certain relays. What an accomplishment! Next post will cover how I put this all together to at least do some crappy light shows.

Building the RaspberryPi Christmas Light Box

Disclosure: I have included some affiliate / referral links in this post. There’s no cost to you for accessing these links but I do indeed receive some incentive for it if you buy through them.

Let’s Cover Some Background Here

I have always enjoyed Christmas lights. For quite some time, I was very intrigued at the notion of putting the lights to music or at least making them dance in motion. About 3 years ago, my wife and I bought a string of lights that had a mind of their own. It was neat to watch it random go through the different patterns of blinking, dancing, and chasing. Last year was the year that we got the really neat ones. They were icicles that changed colors AND danced and chased and more.

All of this was great but I wanted more this year. I wanted to be able to set the lights to music just like the fancy light shows you go to see. I figured the easiest way to do this was to just simply buy something at the store, right? So that’s what we did. We ended up buying an Orchestra of Lights (sure a plug for them yaay). The concept is really cool. We bought the speak box that comes with 6 outlets that are all controlled by the wifi hub. We’ll just say that if you’d like to buy one of these, ask me about purchasing a barely used one for a deep discount.

As part of a little additional background, I’ve always wanted to get my hands on a Pi or Arduino but I could never justify buying one. I could never figure out what legitimate project to apply such an amazing device. Enter the friend….

The Friend Made Me Do It

This is what friends are for right? As we were stringing up all of the lights outside, a friend of ours stopped by who is also a geek. I explained what we were doing and he very promptly asked if I was using a Raspberry Pi to do all of it. As the gears began to turn in my head, I know my face gave it all away. We weren’t doing it at the time, but we would be in just about a week!

The Planning Phase

I’m an over planning and over thinker so I was looking everywhere for what I needed how I needed to do it and what I should do next. My end goal was to be able build a device I could put outside that would play music and control the lights automatically to whatever little tune was playing at the time. This turned out to be a little more difficult than I bargained for but not a big deal. I looked at a bunch of sites and decided that I should probably break this project down into parts.

  1. Build out the hardware
  2. Make it do “something”
  3. Look at how I could possibly get the music to control the action

During this planning phase, I happened upon a really great article that gave amazing details on hooking up the hardware (https://system76.com/weekend-project/holiday-light-show). I mostly ignored everything but the pretty pictures. This site along with a bunch of other sites helped me put together my shopping list.

The Shopping List

Now remember that I said I had already ordered the Pi but let’s still list it here so that you know what I had coming:

This would be the very the basic shopping list. I also bought some little connectors and such so that I could conduit all of the metal pieces together. I also bought some tiny screws and bushings so that I could install the Pi and relay into the breaker box.

Putting it all Together

I lined up the Pi and Relay and marked my holes. I drilled them out. I added my bushings. I mounted everything and was quite proud of it all. Next steps were to wire everything up. Ok why reinvent the wheel here. As I noted before, I basically did exactly what was done in Steps C – K in here. This was a really great write up on how to wire everything.

After everything was done I had me a nice little system. This would be a GREAT spot to add a picture but I already have it hooked up on the porch, plugged in, and nicely hidden away so the neighbors can’t see it. I’ll remember to take some pictures next time.

Next, I’ll go through the code that I put together to get the thing clicking like crazy!

The Move to WordPress

I think I stopped blogging because I just wasn’t quite sure I liked the blogger platform. I guess WordPress is the place to be in the blogging world. After agonizing for a very long time, it seems that it was not time to make the big switch. Turns out, it wasn’t that hard at all. The best thing is that my hosting provider made it totally easy to integrate into my existing infrastructure. On top of that, WordPress has a nice little utility that can migrate your blogger blog write into WordPress. Fancy that!

In case you wanted to learn more about this migration, you can read about it on the WordPress support site here.

Now that I’m onto a platform that seems to be a little more friendly, I hope that I can find some time to write about my latest challenge, my Raspberry Pi 4!

Stay tuned for the next set of posts where I walk through my first project with a Pi in hand.

Automatically Rebuild Image on Docker Hub

This post focuses on me being lazy. In the previous post, I talked about building a custom image and posting it to the Docker Hub. I have also talked about creating a Git repo and storing everything in it thus far. What if we could make a commit rebuild our image for us? As luck would have it, you can do this!

This post is going to focus on making that very simple change to your Docker Hub repository so that every commit causes the image to be rebuilt to the latest. How fun!

Connecting Docker Hub to Your Git Account

The major thing to accomplish here is configuring Docker Hub to monitor Git. In order to do that, you’ll need to first sign into your Docker Hub account. This should bring you to the main page where you see the list of repos you maintain:

From there, click on the repo that you plan to configure. In my case, it’s the testnginximage repo. On the resulting screen, click on the Builds link to reveal the below page:

Click on the Link to GitHub button, to open your preferences to configure linked accounts.

Click the Connect link on this screen, to link to your GitHub account. If you are already signed into GitHub, Docker Hub will automatically connect to whatever account you are signed in with. If you are not already signed into GitHub, you’ll see the below login to GitHub screen:

Login to the GitHub account you used to store your Dockerfile we created in the previous post. Once connected, you’ll return to your Docker Hub profile with your GitHub account connected and the account name used listed:

At this point, you now have your Docker Hub and GitHub accounts connected. The next step will be to enable automatic builds.

Enabling Automatic Builds in Docker Hub

With Docker Hub and GitHub connected, the next step is to tell Docker Hub which repo to use and where the Dockerfile is located. In order to do that, go back to your repo and once again, click on the Build link. Within the Build screen, again, click on the Link to GitHub button. This time, the button should say “Connected” on it as shown below:

On the resulting page, configure the username and repo you would like to use as your source. Since I have been building everything in my mysamplerepo repo, I’m choosing this from the drop down:

In my prior examples, I created the Dockerfile in the nginxdocker directory within my mysamplerepo. Assuming you have done the same, scroll down the page and set the Build Context to be the nginxdocker in the Build Rules. This Build Context would be the path from the root of your repo that contains the Dockerfile. If you’ve placed your Dockerfile in a different path within your repo, make sure you have Build Context configured for that particular path.

Once you have this all configured, click on the Save and Build button at the bottom of the page. This should take you back to the Build page where you can monitor the status of the build.

Monitor the progress to make sure everything builds correctly. Once done, you should see a success status for the build.

Use a Commit to Generate a Build

Now that we have everything connected and working, let’s see if we can do a commit to our repo and confirm that the commit makes a build trigger. Let’s just make a simple change and no longer expose port 443 from for the image:

FROM ubuntu
  
 MAINTAINER Scott Algatt
  
 RUN apt-get update 
     && apt-get install -y nginx libnginx-mod-http-lua libnginx-mod-http-subs-filter software-properties-common
     && add-apt-repository -y universe 
     && add-apt-repository -y ppa:certbot/certbot 
     && apt-get update 
     && apt-get -y install certbot python-certbot-nginx 
     && apt-get clean 
     && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
 COPY ./conf/nginx.conf /etc/nginx/nginx.conf
 COPY ./conf/site.conf /etc/nginx/sites-available/default
  
 EXPOSE 80
 CMD ["nginx"]

With that change, let’s do a commit and push:

$ git commit -a
 [master 0e01193] Removing port 443
  Committer: Scott <scott@iMacs-iMac.local>
  
  2 files changed, 2 deletions(-)
$ git push origin master
 Counting objects: 6, done.
 Delta compression using up to 4 threads.
 Compressing objects: 100% (6/6), done.
 Writing objects: 100% (6/6), 499 bytes | 499.00 KiB/s, done.
 Total 6 (delta 3), reused 0 (delta 0)
 remote: Resolving deltas: 100% (3/3), completed with 3 local objects.
 To github.com:algattsm/mysamplerepo.git
    1d4d448..0e01193  master -> master

After performing the commit, refresh your Build page in Docker Hub and you should see a build trigger:

This means that you’ll be able to simply use your GitHub to generate a new image anytime you like! This also means that with every commit, you’ll be exposing the latest version of your image on Docker Hub.

Referenced File

In case you want to make sure you have the correct file, here would be the only file I referenced in this post: