Categories
LXC Operating Systems PHP

Linux Container API v4.0

The simple hypervisor for Linux Containers

What started out as a simple script for viewing the state of Linux containers has evolved into a powerful PHP-file running both a Web Panel and a Restful API

A Restful API

REST is acronym for REpresentational State Transfer. It is an architectural style for distributed systems.

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other

A standardised way of communication

The API receives informational requests from GET and commands from POST and replies with JSON.

Basic Auth for authentication, an array with usernames and password hashes are saved in the php file.

To query the API from a remote machine one could use curl, wget or a standard browser.

# curl -u username http://localhost:1587/api/host/info

# curl -u username -XPOST -F 'action=start' http://localhost:1587/api/container/alpine-base/

# wget -O - http://username:password@localhost:1587/api/host/info

Host commands

GET /api/host/info
GET /api/host/memory
GET /api/host/loadavg
GET /api/host/network
GET /api/host/cpu

Container commands

GET /api/container/$name/info
POST /api/container/$name action=start
POST /api/container/$name action=stop
POST /api/container/$name action=restart
POST /api/container/$name action=freeze
POST /api/container/$name action=unfreeze
POST /api/container/$name action=snapshot newname=name type=overlayfs/dir

Runtime Environment

There are multiple ways of running the API on your servers.

PHPs Built in Web Server

Execution by PHPs built in web server is preferable since it prevent conflicts with other web servers that might be running on the host.

# php -S 0.0.0.0:1587 /opt/lxc-tools/lxc-api.php

The server could also be started as a SystemD service which can be controlled by the “systemctl” command as any other Linux service.

Dependencies

PHP and LXC of course, all data is collected from the kernel or by native Linux commands.

SSL Certificate

If you want to add SSL support you’ll need to run Apache, Nginx, Lighttpd or any other PHP compatible server.

The System D way

Create a new service called “/etc/systemd/system/lxc-api.service”

[Unit]
Description=LXC-Api Server
After=network.target
ConditionPathExists=/opt/lxc-tools/lxc-api.php

[Service]
ExecStart=/usr/bin/php -S 0.0.0.0:1587 /opt/lxc-tools/lxc-api.php
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure

[Install]
WantedBy=multi-user.target

Then enable and start the service
# systemctl enable lxc-api
# systemctl start lxc-api

Web Panel

The web interface uses its own Restful API to fetch information about the host and the containers without refreshing the browser.

By Nimpen J. Nordström

System Developer and Network Security Enthusiast