Caddy Server and WordPress (PHP-FPM)

Caddy LogoRecently I discovered an amazing open source project: Caddy, a fully functional HTTP/2 webserver, written in Go.

Caddy is a lightweight, general-purpose web server for Windows, Mac, Linux, BSD, and Android. It is a capable alternative to other popular and easy to use web servers.

The most notable features are HTTP/2, Virtual Hosts, TLS + SNI, and easy configuration with a Caddyfile. Usually, you have one Caddyfile per site. Most directives for the Caddyfile invoke a layer of middleware which can be used in your own Go programs.

In this tutorial I will explain how to run WordPress with Caddy server (on Ubuntu), using Caddy’s FastCGI support and PHP-FPM (i.e. PHP FastCGI Process Manager). Of course you also need MySQL/MariaDB to run WordPress.

MySQL

I assume that you have a MySQL server up and running (or that you have the knowledge to do so) .

PHP

Install PHP-FPM:

$ sudo apt-get install php5-fpm

PHP-FPM listens to FastCGI requests on a unix socket by default (on Ubuntu and Arch Linux): unix:/var/run/php5-fpm.sock. So we’ll have to tell the webserver to pass the PHP requests to it.

You could also use a regular UDP socket if you want: change listen in /etc/php5/fpm/pool.d/www.conf to 127.0.0.1:9000. On some operating systems (e.g. FreeBSD), PHP-FPM listens on this UDP socket by default.

Caddyfile

Now we need to configure Caddy so it will use PHP-FPM. We also need to specify virtual hosts for the domain(s) we will be using.

The following Caddyfile contains everything you need to run WordPress with PHP-FPM on HTTP/2.

http://my-wordpress-blog.com {
    redir https://my-wordpress-blog.com
}

https://my-wordpress-blog.com {
    root wordpress
    tls server.crt server.key
    log access.log
    
    # PHP-FPM with Unix socket
    fastcgi / /var/run/php5-fpm.sock php
    
    # PHP-FPM with regular udp socket
    # fastcgi / 127.0.0.1:9000 php
}

Caddy will use the wordpress folder as document root, and will pass all PHP requests to a FastCGI process (which is the PHP-FPM process).

The Caddy documentation contains more detailed information on the available directives. Checkout my other blogposts if you need help Running Caddy Server as a service or Creating a self-signed certificate.

WordPress

Now it’s time to install WordPress. Simple download WordPress and copy the files to the wordpress folder. To install WordPress you can just follow the steps on the screen like any other easy WordPress configuration.

If you want to use HTTP/2, you should configure WordPress with HTTPS enabled. You can do this in Settings, General: change http in the urls to https.
Most browsers only speak HTTP/2 when using TLS. Although TLS only is not marked as mandatory in the RFC 7540, Firefox and Chrome development teams have no actual intents to implement HTTP/2 without TLS.

Creating a self-signed SSL certificate on Linux

The exact commands for generating a self-signed SSL certificate on Linux is something I always forget, so here they are:

Generating a private key

First you need to generate a private key. This private key will be the only key that can decrypt your SSL traffic.

$ openssl genrsa -des3 -passout pass:x -out server.pass.key 2048
$ openssl rsa -passin pass:x -in server.pass.key -out server.key
$ rm server.pass.key

Generating a CSR (Certificate Signing Request)

Using the private key you’ve generated seconds ago, you must now create a CSR (Certificate Signing Request). In most cases you can just use the default values for everything except the common name. The common name is usually the domain of your website.

$ openssl req -new -key server.key -out server.csr

Signing the certificate

Normally you would pass the CSR to a CA (Certificate Authority) who would sign it for you. But using the following command you sign the certificate yourself.

$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Running Caddy Server as a service

Recently I discovered a very promising webserver (written in Go) called Caddy.

Now, Caddy is just an executable, which I wanted to turn into a service on my Ubuntu server.

Upstart

Running any executable as a service can be done using Upstart. Once you’ve created a config file in /etc/init/my_service.conf, you can use some simple commands like service my_service start, service my_service stop, … and the service will run at boot time.

The output of the program will be logged to /var/log/upstart/my_service.log.

Config file

My configuration file looks like this:

description "Caddy Server startup script"
author "Mathias Beke"

start on runlevel [2345]
stop on runlevel [016]


setuid some-caddy-user
setgid some-caddy-group

respawn
respawn limit 10 5

script
    cd /home/mathias/
    exec ./caddy
end script

Explanation of the commands:

  • start on runlevel [2245] specifies the job needs to be started after the basic facilities are up.
  • stop on runlevel [016] is used for a normal shutdown.
  • setuid and setgid can be used to run the job under a specific user account. Set this to an account that is less privileged than the root user. You don’t want to run a webserver with root access!
  • respawn will automatically restart (well… ‘respawn’) the process when it stops for any reason.
  • respawn limit COUNT INTERVAL | unlimited specifies a limit for the automatic respawn of the process.

    Respawning is subject to a limit. If the job is respawned more than COUNT times in INTERVAL seconds, it will be considered to be having deeper problems and will be stopped. Default COUNT is 10. Default INTERVAL is 5 seconds.

    To have the job respawn indefinitely, specify an argument of “unlimited”. However, care should be taken using this option: does your service really stop that frequently? Should it?

     Upstart Cookbook

  • exec executes the actual command.

Swift/iOS: Moving objects with device motion (tilt screen)

One of the cool things of games on smartphones, is that you can control objects using the device motion. But how do you move an object using device tilt (using Swift 2)?

To do so you need to use the CMMotionManager (which is part of Apple’s CoreMotion framework). So don’t forget to include the framework at the top of your code: import CoreMotion.

You must also create one (single) CMMotionManager instance.

let motionManager: CMMotionManager = CMMotionManager()

And start the motion manager in the didMoveToView() function:

motionManager.startAccelerometerUpdates()

Once the motion manager is up and running, we can retrieve motion data from it using the accelerometerData member.

// Get node of object to move
let paddle = childNodeWithName(PaddleCategoryName) as! SKSpriteNode

// Get MotionManager data
if let data = motionManager.accelerometerData {
    
    // Only get use data if it is "tilt enough"
    if (fabs(data.acceleration.x) > 0.2) {
        
        // Apply force to the moving object
        paddle.physicsBody!.applyForce(CGVectorMake(40.0 * CGFloat(data.acceleration.x), 0))
        
    }
}

If you want to actually move the object, you need to make sure that the object has some physical properties:

// Rectangular physics body around the object
paddle.physicsBody = SKPhysicsBody(rectangleOfSize: paddle.frame.size)
 
// Make it dynamic
paddle.physicsBody!.dynamic = true
 
// We don't want the object to fall of the screen
paddle.physicsBody!.affectedByGravity = false
 
// Add some mass to it
paddle.physicsBody!.mass = 0.02

The data.acceleration member is a struct of type CMAcceleration which contains the acceleration along the x-, y- and z-axis.

struct CMAcceleration {
    var x: Double
    var y: Double
    var z: Double
}

The following image (source) explains the orientation of those axes.

CoreMotion CMAcceleration axes

Atelier Vidéo Virton 1 2015: Les maffiantômes de Virton

Naar jaarlijkse gewoonte ben ik weer een maand op taalkamp geweest als monitor. Zie hier het resultaat van een workshop ‘Vidéo’ na 12 dagen Roeland kamp in Virton.

Comme d’habitude j’ai fait un mois de camp de langue. Voila le résultat de 12 jours à Roeland. Un atelier Vidéo réalisé par 11 jeunes à Virton.

Creating a first iPhone app: Liveblog in Swift

Apple announced that Swift would become open source at the WWDC keynote (earlier this week). The perfect moment for me to create my very first iOS app (in the newly released Swift 2 and Xcode 7 beta). So I spent a few hours yesterday and created a real-time live blog app as a front-end for the WebSocket Liveblog back-end I’ve written in Go.

Xcode project

First I downloaded the new Xcode 7 beta, and created a new application. File, New, Project. Select iOS, Single View Application. Fill in the needed information (make sure the select Swift as programming language and not Objective-C) and create the project.

Xcode create Swift Single View app

CocoaPods

Since I didn’t really figured out how to import external modules from Github (and didn’t want to lose time on doing so) I used the CocoaPods tool. This handy tool manages the dependencies for you. (Comparable to Composer for PHP)

Installing CocoaPods is very simple using the Terminal:

$ sudo gem install cocoapods

In Terminal navigate to your project folder and execute pod init (This will create the Podfile file in the root directory of your project), and append the following content the Podfile:

use_frameworks!

target 'Liveblog' do
	pod 'Starscream', '~> 0.9'
end

Now open the Liveblog.xcworkspace Workspace in Xcode. Since Starscream isn’t yet coded in Swift 2, Xcode 7 will ask the convert the code to Swift 2. After the automatic conversion, there will still be some compile errors to fix. You can fix them with auto-fix in Xcode.

Creating the user interface

Next step is designing our iPhone app. (I’m not a designer, nor an UX expert, so I’ll keep it simple, KISS). All of this happens in the Main.storyboard file.

At the bottom of the right sidebar, there are some switches with pre-made things you can include into your project (including code snippets, or creating new files). We need the third tab of that panel, i.e. the panel with UX elements.

View

Our storyboard will already consist of a View, which we can style. I chose to give the main view a sea green background.

Label

Now it’s time to create a title at the top of the view. Drag a label from the right bottom UX panel to the view. Again you can do some styling at the right panel. (I increased the font size a lot, and opted for a white font)

Now we want to center the label on all screen sizes. Therefor you can add ‘responsive’ constraints to your storyboard elements. At the right bottom corner of the storyboard panel, there are 4 buttons. Click on the second button to add aligning constraints: select the horizontal constraint and click on “Add 1 constraint”.

Xcode storyboard center responsive

 

Text View

The same steps need to be followed to create a Text View on the storyboard. Drag the Text View element from the right bottom panel to the storyboard and resize it so it fills the whole view (except the top bar). Again, we want this UI element to fit all screen sizes, so we must add some constraints so it will always cover the whole screen.

Click on the red dashed lines in the constraints panel to ‘enable’ the constraints, and then click on “Add 4 constraints”.

Xcode storyboard responsive constraints textview

 

Now launch the app in the iOS simulator and make sure everything is responsive. If  everything looks fine, you can remove the sample text from the TextView (since we will load WebSocket data in it)

Add referencing outlet

If we want to actually do something with the TextView, we need to create a referencing outlet for it in the ViewController.swift file. In the right top navigation click on the editor icon (the two overlapping rings). This will open a second, split view with the code of the ViewController. Now press the ctrl key and drag the TextView into the code at the right side and give the outlet a name.

Xcode add referencing outlet Xcode outlet name

 

If completed successfully, your ViewController class will look like this:

class ViewController: UIViewController {


    @IBOutlet weak var textView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Adding the WebSockets in Swift

Now we can finally implement the actual WebSockets for our app. Well, not really implementing, because we will be using Starscream’s WebSocket client (as mentioned above in the section of the CocoaPods)

First thing to do is import Starscream above the ViewController class. Next add WebSocketDelegate in the class declaration line to indicate we are implementing the Starscream WebSocketDelegate interface (so we can delegate the WebSocket to the ViewController).

class ViewController: UIViewController, WebSocketDelegate  {
    // ... 
}

Since we defined that ViewController implements the WebSocketDelegate interface, you need to add the functions of that interface to the ViewController:

// websocketDidConnect is called as soon as the client connects to the server.
func websocketDidConnect(socket: WebSocket) {
    println("websocket is connected")
}

// websocketDidDisconnect is called as soon as the client is disconnected from the server.
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
    println("websocket is disconnected: \(error!.localizedDescription)")
}


// websocketDidReceiveMessage is called when the client gets a text frame from the connection.
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
    println("got some text: \(text)")
}

// websocketDidReceiveData is called when the client gets a binary frame from the connection.
func websocketDidReceiveData(socket: WebSocket, data: NSData) {
    println("got some data: \(data.length)")
}

Next create the websocket client with the url and the port of your back-end. Append the following code to the viewDidLoad function:

let socket = WebSocket(url: NSURL(scheme: "ws", host: "labs.denbeke.be:1234", path: "/")!)
socket.delegate = self
socket.connect()

At this stage we have everything in place to actually handle the incoming WebSocket messages, which are marshalled in the following JSON format:

{
    "Content":"But even cooler, a native iPhone app written in Swift!",
    "Time":1433942629
}

To do this you need to implement the websocketDidReceiveMessage function:

func websocketDidReceiveMessage(ws: WebSocket, text: String) {

    let json: NSDictionary
    do {
        // Parse JSON request
        try json = NSJSONSerialization.JSONObjectWithData(text.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        
        // Do something with the parsed JSON data
        if (json["Content"] != nil) {
            textView.text = (json["Content"] as! String) + "\n\n" + textView.text
        }
        
    }
    catch {
        print("Could not parse json message")
    }

    
    print("Received text: \(text)")
}

The above snippet will try to parse the JSON request into a Swift dictionary/map. If this goes without any error, the content of the message will be prepended in the TextView we created earlier.

All together your ViewController should look like this:

import UIKit
import Starscream

class ViewController: UIViewController, WebSocketDelegate  {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        // padding of TextView: top, left, bottom, right
        textView.textContainerInset = UIEdgeInsetsMake(8,8,4,8);

        // Setup WebSocket
        let socket = WebSocket(url: NSURL(scheme: "ws", host: "denbeke.be:1234", path: "/")!)
        socket.delegate = self
        socket.connect()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // Interface for WebSockets

    func websocketDidConnect(ws: WebSocket) {
        print("websocket is connected")
    }

    func websocketDidDisconnect(ws: WebSocket, error: NSError?) {
        if let e = error {
            print("websocket is disconnected: \(e.localizedDescription)")
        }
    }

    func websocketDidReceiveMessage(ws: WebSocket, text: String) {

        let json: NSDictionary
        do {
            // Parse JSON request
            try json = NSJSONSerialization.JSONObjectWithData(text.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

            // Do something with the parsed JSON data
            if (json["Content"] != nil) {
                textView.text = (json["Content"] as! String) + "\n\n" + textView.text
            }

        }
        catch {
            print("Could not parse json message")
        }


        print("Received text: \(text)")
    }

    func websocketDidReceiveData(ws: WebSocket, data: NSData) {
        print("Received data: \(data.length)")
    }



}

The complete iPhone app should look like this:

Liveblog iOS iPhone app screenshot

 

I have uploaded the source code of the app to Github: Liveblog-iOS-App

Simple Liveblog to demonstrate WebSockets in Go

Yesterday I had some time left and thought it was the perfect moment to write a very simple live blog to learn more about WebSockets (in Go).

Go

WebSockets are actually very easy in Go, they work just like the http handler. The required websocket package is not installed by default, but you can easily install the (by Go maintained) package: go get code.google.com/p/go.net/websocket.

Time to create a websocket handler:

func main() {
    http.Handle("/", websocket.Handler(HandleSocket))

    if err := http.ListenAndServe(":1234", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

In the above snippet, HandleSocket is the name of your own defined handler function. In this easy example I created a handler function that will just send all received message on a socket back:

func HandleSocket(ws *websocket.Conn) {

    // Wait for incoming websocket messages
    for {
        var reply string

        if err := websocket.Message.Receive(ws, &reply); err != nil {
            log.Println("Can't receive from socket:", err)
            break
        }

        log.Println("Received back from client: " + reply)

        msg := "Received:  " + reply
        log.Println("Sending to client: " + msg)

        if err := websocket.Message.Send(ws, msg); err != nil {
            log.Println("Can't send to socket:", err)
            break
        }
    }
}

Of course I enhanced this Go code to create an actual liveblog demo.

Javascript

Now we have our websocket, we must actually do something with it in Javascript. The most simple implementation will prepend any new message to an html list with id messages:

var sock = null;
var wsuri = "ws://localhost:1234";

window.onload = function() {

    sock = new WebSocket(wsuri);

    sock.onopen = function() {
        console.log("connected to " + wsuri);
    }

    sock.onclose = function(e) {
        console.log("connection closed (" + e.code + ")");
    }

    sock.onmessage = function(e) {
        $('<li>' + e.data '</li>').hide().prependTo('#messages').fadeIn(1000);
    }
};

We must also be able to send messages from an admin panel:

function send() {
    var msg = document.getElementById('new_message').value;
    document.getElementById('new_message').value = '';
    sock.send(msg);
};

Liveblog

I combined the above little pieces to create a simple liveblog. The blog has an admin page on which someone can add messages, which are then broadcasted to all the other sockets.

 

Simple admin page

Simple admin page

The source code of the demo is available on Github: github.com/DenBeke/Liveblog

Antwerpen vanaf Panorama van KBC Boerentoren

Deze week de kans gekregen om wat foto’s te nemen vanop de hoogste verdieping van de KBC Boerentoren.

Het resultaat: een aantal mooie panorama foto’s van Antwerpen…

Zicht op de kathedraal van Antwerpen en de Schelde. Rechts van de kathedraal zie je het Vleeshuis, en uiterst rechts staat de Sint-Pauluskerk. In de verte zie je de koeltorens van Doel. Foto werd genomen van op het panorama in de KBC Boerentoren.

Zicht op de kathedraal van Antwerpen en de Schelde. Rechts van de kathedraal zie je het Vleeshuis, en uiterst rechts staat de Sint-Pauluskerk.
In de verte zie je de koeltorens van Doel.

Bocht van de schelde, met op de voorgrond de Sint-Pauluskerk, rechts het MAS. In de verte op linkeroever valt nog een glimp op te vangen van Oosterweel. Links vooraan zie je ook het Vleeshuis.

Bocht van de schelde, met op de voorgrond de Sint-Pauluskerk, rechts het MAS.
In de verte op linkeroever valt nog een glimp op te vangen van Oosterweel.
Links vooraan zie je ook het Vleeshuis.

Zicht op de Schelde met centraal in beeld de Sint-Andrieskerk

Zicht op de Schelde met centraal in beeld de Sint-Andrieskerk

Politietoren "Den Oudaan" met rechts ernaast de Sint-Augustinuskerk en verderop het nieuwe justitiepaleis op de achtergrond

Politietoren “Den Oudaan” met rechts ernaast de Sint-Augustinuskerk en verderop het nieuwe justitiepaleis op de achtergrond

Van links naar rechts Sint-Antonius en het Sportpaleis (beide in de verte), Sint-Jacobskerk, Theater Building, Antwerp Tower en uiterst rechts Antwerpen-Centraal

Van links naar rechts Sint-Antonius en het Sportpaleis (beide in de verte), Sint-Jacobskerk, Theater Building, Antwerp Tower en uiterst rechts Antwerpen-Centraal

LaTeX and Fuzzy Logics

Fuzzy logics (especially fuzzy numbers and fuzzy intervals) can be beautifully plotted on a graph, …. aaaand of course, you can also do this using LaTeX and pgfplots!

\begin{tikzpicture}
        \begin{axis}[
            height=3.5cm,
            width=\textwidth/2,
            ytick={0,1},
            xtick={4,6},
            area style,
            xlabel={$$},
            xmin=0,xmax=10,
            axis x line=bottom,
            axis y line=left,
            %ylabel={$$},
            enlarge x limits=false
            ]

            \addplot[fill, red, opacity=0.2] coordinates
                {(2.5,0)(4,1)(6,1)(7.5,0)}
                \closedcycle;
                \addplot [red, mark = none, nodes near coords=\textbf{Fuzzy interval},every node near coord/.style={anchor=90,rotate=0,anchor=south,align=center}] coordinates {( 5, 1.1)};

        \end{axis}
\end{tikzpicture}

 

Fuzzy interval

Fuzzy interval plotted with pgfplots in LaTeX