Raspberry Pi 3 возможно назвать по-настоящему универсальным компьютером. Bitcoin, конечно, на нём намайнить не получится, да и в игры с графикой консолей последних поколений поиграть не выйдет, но вот со многим остальным он хорошо справится. Ниже, в свою очередь, будет рассмотрены основные и наиболее популярные варианты применения Raspberry Pi 3.

Мультимедийные возможности Raspberry Pi 3

Возможности Raspberry Pi 3 в области мультимедиа очень велики. В частности, на основе "Малины" можно сделать мультимедийный центр, игровую консоль либо даже всё сразу. В результате с этим одноплатником можно получить на своем телевизоре с HDMI-портом доступ к следующим категориям развлечений:

  • видео в высоком разрешении на YouTube или других хостингах;
  • музыке на стриминговых сервисах;
  • игровым стримам на, например, Twitch;
  • играм, разработанным для старых консолей : NES, SNES, SEGA и др.

Чтобы просматривать и прослушивать мультимедийный контент, можно либо использовать браузер, либо, что еще более удобно - установить специальный медиаплеер. Наиболее функциональным и удобным из них является Kodi .

Для превращения "Малины" в игровую консоль нужно поставить на неё эмуляторы интересующих платформ и заказать игровые Rom-ы. Это делается за пару десятков минут. А еще проще и удобнее - инсталлировать специальный дистрибутив, например, Retro Pie или какой-то другой.

Разработка и работа с документами на RPi

Конечно, "Малина" - не самый мощный компьютер, а значит - не лучшее решение для работы. Но при желании на ней более или менее комфортно можно посмотреть/отредактировать какой-то документ или даже написать скрипт. Конечно, работать с тяжелыми IDE на ней не получится, но этого от RPi никто и не требует.

Также с помощью RPi3 можно «посерфить» в интернете или пообщаться в мессенджерах либо социальных сетях.

Сервер для любых нужд из Raspberry Pi 3

Еще один вариант, как можно использовать Raspberry Pi 3 - это сделать из него сервер. Так, достаточно поставить на него LAMP или просто Apache и Myphpadmin, после чего можно будет разрабатывать и тестировать веб-проекты в условиях достаточно ограниченных ресурсов.

Второй вариант - скачивать и раздавать с Raspberry Pi 3 torrent. Для этого, конечно, потребуется внешний жесткий диск, так как карты памяти и флэшки для данных целей не очень подходят как из-за ограничений скорости и маленького объема, так и ввиду быстрой изнашиваемости при интенсивных нагрузках.

Применение "Малины" в робототехнике и IoT

В IoT и робототехнике применение RPi практически безгранично. Из этого устройства можно сделать, например, камеру видеонаблюдения, небольшую метеостанцию, машинку с удаленным управлением и многое другое. Так, Raspberry Pi 3 находит применение в машине в виде видеорегистратора. При желании из данного одноплатника можно сделать даже мобильный телефон или смартфон. Но такое стоит делать либо ради экспериментов, либо, чтобы похвастаться перед друзьями/сообществом. Дело в том, что соответствующее устройство получится как минимум довольно громоздким.

Конечно, для данных целей понадобятся модули. Но с их покупкой проблем не должно возникнуть. В Сети существует множество магазинов, которые продают дополнительные компоненты для "Малины" по доступным ценам.

Объединение нескольких RPi 3 в кластер

Ещё один способ применения Raspberry Pi 3 - объединение нескольких таких устройств в кластер. Это довольно специфический способ использования, который подойдет далеко не каждому.

Для начала следует дать краткое и понятное объяснение, что такое кластер. В общих чертах под этим термином понимается комплекс однородного оборудования (в данном случае множество RPi), на которых параллельно выполняется какая-то задача.

Делать кластер из "Малины" для реализации чего-то серьезного практического смысла нет, так как есть более дешёвые и удобные решения. Объединение Raspberry Pi 3 в кластер целесообразно по большей части для обучения. Имея несколько одноплатников, можно разобраться с особенностями параллельных вычислений или показать как они работают ребёнку (собственно, RPi и создавался для обучения детей).

Как можно видеть, с RPi 3 можно сделать много интересных вещей. В первую очередь он полезен для изучения компьютеров. Но также он позволяет и реализовывать очень большое количество проектов, которые возможно применять для работы или отдыха.

One popular use of Raspberry Pi computers is building clusters. Raspberry Pies are small and inexpensive so it"s easier to use them to build a cluster than it would be with PCs. A cluster of Raspberry Pies would have to be quite large to compete with a single PC; you"d probably need about 20 Pies to produce a cluster with as much computing power as a PC. Although a Pi cluster may not be that powerful, it"s a great opportunity to learn about distributed computing.

There are several different types of distributed computer which can be used for different purposes. There are super computers that are used for solving mathematical problems like modelling weather conditions or simulating chemical reactions. These systems often use the Message Passing Interface (MPI). A team at the University of Southampton built a 64 node MPI based super computer . This system is used for teaching students about supercomputing.

Another technology that"s often used in distributed computing is Hadoop, which distributes data across many nodes. Hadoop is often used for processing large datasets and data mining. An engineer at Nvidia built a small Hadoop cluster using Raspberry Pies . He uses his cluster to experiment and test ideas before deploying them on more powerful systems.

Using a Raspberry Pi cluster as a web server

Clusters can be used as web servers. Many web sites get too much traffic to run on a single server, so several servers have to be used. Requests from web browsers are received by a node called a load balancer, which forwards requests to worker servers. The load balancer then forwards responses from servers back to the clients.

This site is now hosted on a Raspberry Pi cluster. The worker nodes are standard web servers that contain identical content. I just installed Apache on them and copied my site to each node.

I use an extra Raspberry Pi to host a development copy of this site, and to control the cluster. This Pi is connected to my local network via wifi, so I can access the development copy of my site from my laptop.

The extra Pi also has an ethernet connection to the Pi cluster. When I want to update my site, I can transfer changes from the development site to the live site on the cluster. Site updates are put into .tar.gz files which the worker nodes automatically download from the development site. Once downloaded, updates are then unpacked into the local file system.

Configuring the Raspberry Pi servers

All of the Pies in this system are headless. I can log into the Pi with the development site using the Remote Desktop Protocol, and from that Pi I can log into the worker Pies using SSH.

All the Pies in the cluster use a static IP address. In a larger cluster it would probably be better to set up a DHCP server on the load balancer. The IP addresses used in the cluster are on the 192.168.1.xxx subnet.

For each worker Pi, I set up a 4GB SD card using the latest version of Raspbian. In raspi-config I set the following options:

  • expand fs
  • set the hostname
  • set the password
  • set memory split to 16MB for the GPU
  • overclock the CPU to 800MHz
  • enable ssh

On each card I installed Apache and some libraries required by my CMS, libxml2 and python-libxml2. I used this command to enable mod rewrite, which is also required by my CMS:

$ sudo a2enmod rewrite

Finally, I copied some scripts onto each SD card which allow each Pi to synchronize its contents with the development Pi. In a larger cluster it would be worth creating an SD card image with all of these modifications made in advance.

Building a load balancer

The load balancer must have two network interfaces, one to receive requests from a router, and another network interface to forward requests to the server cluster. The nodes in the cluster are a on a different subnet than the rest of the network, so the IP address of the load balancer"s second interface must be on the same subnet as the rest of the cluster. The load balancer"s first interface has IP address 192.168.0.3 while the second interface"s IP address is 192.168.1.1. All the Pies in the cluster have IP addresses on the 192.168.1.xxx subnet.

I built my load balancer using an old PC with 512MB of RAM and a 2.7GHz x86 CPU. I added a second PCI ethernet card and installed Lubuntu, a lightweight version of Ubuntu. I was going to install Ubuntu, but this PC is pretty old, so Lubuntu is probably a better choice. I used a PC becasue I wasn"t sure if a single Pi would be powerful enough to act as a load balancer, and a Pi only has one ethernet connection. I want both of my load balancer"s network connections to be ethernet for improved performance and stability.

Note that IP forwarding is not enabled. The load balancer isn"t a router, it should only forward HTTP requests and not every IP packet that it receives.

Setting up the load balancer software

There are many different software implementations of load balancing. I used Apache"s load balancer module because it"s easy to set up. First I made sure my PC"s OS was up to date:

sudo apt-get update
sudo apt-get upgrade

Then I installed Apache:

sudo apt-get install apache2

These Apache modules need to be enabled:

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_balancer

The next step is to edit /etc/apache2/sites-available/default in order to configure the load balancer. The proxy module is needed for HTTP forwarding, but it"s best not to allow your server to behave as a proxy. Spammers and hackers often use other people"s proxy servers to hide their IP address, so it"s important to disable this feature by adding this line:

ProxyRequests off

Although proxy requests are disabled, the proxy module is still enabled and and acts as a reverse proxy. Next, define the cluster and its members by adding this code:

Balancer manager interface

The balancer module has a web interface that makes it possible to monitor the status of the back end servers, and configure their settings. You can enable the web interface by adding this code to /etc/apache2/sites-available/default:

It"s also necessary to instruct Apache to handle requests to the /balancer-manager page locally instead of forwarding these requests to a worker server. All other requests are forwarded to the cluster defined above.

ProxyPass /balancer-manager ! ProxyPass / balancer://rpicluster/

Once these changes have been saved, Apache should be restarted with this command:

$ sudo /etc/init.d/apache2 restart

when I open a browser and go to http://192.168.0.3 I see the front page of my web site. If I go to http://192.168.0.3/balancer-manager, I see this page in the image on the right.

The last step in getting the cluster online is adjusting the port forwarding settings in my router. I just needed to set up a rule for forwarding HTTP packets to http://192.168.0.3.

Here"s the complete /etc/apache2/sites-available/default for the load balancer:

ServerAdmin webmaster@localhost DocumentRoot /var/www Options FollowSymLinks AllowOverride All Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch AddHandler cgi-script .py Order allow,deny Allow from all ProxyRequests Off BalancerMember http://192.168.1.2:80 BalancerMember http://192.168.1.3:80 BalancerMember http://192.168.1.4:80 BalancerMember http://192.168.1.5:80 AllowOverride None Order allow,deny allow from all ProxySet lbmethod=byrequests SetHandler balancer-manager Order allow,deny allow from 192.168.0 ProxyPass /balancer-manager ! ProxyPass / balancer://rpicluster/ ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined

— миниатюрный компьютер, размером чуть больше флешки, с огромным количеством возможностей. ПК можно использовать и по прямому назначению — подключить мышь, клавиатуру, монитор и работать, как с обычным компьютером. Но возможности Raspberry гораздо шире — и эти возможности используют любители гаджетов и технологий. В сегодняшнем обзоре — 5 интереснейших проектов на основе Raspberry Pi.

Планшет

Да, если у вас нет планшета, самое время его сделать своими руками. В этом нам поможет Raspberry Pi и подробная инструкция (правда, на английском языке). Диагональ у такого планшета составляет 10 дюймов. Конфигурация же повторяет конфигурацию Raspberry Pi.

Суперкомпьютер

Сам по себе мини-компьютер не очень производительный. Но если объединить несколько десятков Raspberry в единый кластер, может получиться очень мощная система со значительными вычислительными ресурсами.

Не так давно был создан настоящий суперкомпьютер из 64 Raspberry Pi. Поскольку корпуса для таких устройств не продаются, то было решено сделать корпус самостоятельно, из кирпичиков Lego.

Как сделать нечто подобное самостоятельно? Вот подробнейшая инструкция от автора этой разработки.

Skype-телефон

Если вы регулярно общаетесь по Skype, стандартные методы общения (микрофон, ПК) могли и надоесть, как надоели они создателю следующего проекта. Для того, чтобы сделать разговоры по Skype интереснее, разработчик поместил сам Raspberry в корпус дискового телефона, подключил Сеть, и создал специальное ПО, позволяющее переводить количество прокруток диска телефона в символы.

В результате получилось интереснейшая Skype-станция. От обычного дискового телефона система отличается только тем, что сзади подключено два провода, а не один.

Фотокамера

На основе «малинки» можно сделать и мощную фотокамеру с производительной начинкой. При этом все, что нужно — светодиоды, немного оптики и 3D-принтер, чтобы распечатать корпус устройства. Конечно, нельзя забывать и о самом мини-компьютере Raspberry — именно он обеспечивает работу камеры.

Сделать такую систему самостоятельно тоже можно, хотя сделать это не так просто.

Система «свободно/занято» для офисного туалета

Работники офисов иногда теряют драгоценное время, подойдя к туалету, и увидев, что место уже занято. Неприятно, плюс утекает драгоценное рабочее время. Чтобы избежать таких случаев, можно сделать систему предупреждения, которая будет транслировать статус офисного туалета (свободно или занято) на компьютеры всех сотрудников.

Для того, чтобы определить, есть человек внутри или нет, система использует следующий алгоритм:

1. Делается снимок через приложение Streamer;
2. Анализируется яркость пикселей в определенном месте, алгоритм работает на основе PHP-GD;
3. Если яркость отличается от эталонной, система дает сигнал;
4. Пользователь получает сообщение «занято».

Сегодня речь пойдёт о замечательном инструменте, а именно о контейнерной системе развертывания приложений - Docker. Разработчиков для Raspberry Pi тема касается непосредственно. Добро пожаловать под кат.

1. Что такое Docker

Возможно не все знакомы с системами развертывания. Поэтому я поясню.

Говоря совсем простым языком, Docker - это такая система, которая позволяет один раз настроить приложение на одной машине, сохранить его окружение (не только конфигурацию, а именно и окружение тоже) и зависимости, дальше распространять его уже настроенным в виде контейнера. Т.е. для развертывания ничего не понадобится кроме образа.

Также вы можете где-нибудь увидеть слова "Docker" и "виртуализация" в одном предложении, это не значит что Docker эмулирует процессор, память, ядро ОС и т.д., виртуализация происходит на уровне ядра т.е. все "виртуализируемые" им процессы являются реальными процессами вашей ОС.

Как вы уже догадались можно придумать массу применений. Например, вы собираетесь сделать кластер Raspberry Pi, который будет майнить биткоины (кстати, это нерентабельно в наши дни) и на каждую из 1000 имеющихся в арсенале плат вы должны установить и настроить один и тот же софт. Да, можно скомпилировать свой образ ОС, но это во-первых не так быстро, во-вторых это не так гибко (конфигурация чуть-чуть поменялась и надо пересобирать весь образ ОС).

Или, например, вы хотите распространять ваше приложение под несколько модификаций одноплатных компьютеров: Rpi1, Rpi2, O-droid, Rpi3. Везде одна и та же структура приложения, один и тот же исполняемый код, но конфигурация отличается. Вы можете создать 3,4 отдельных мануала для пользователей по установке и настройке, а потом вам это надоест и вы создадите N различных, уже настроенных конфигураций вашего приложения под самые популярные платформы и будете распространять их виде контейнеров.

Это то что я придумал навскидку. На самом деле Docker это очень-очень мощный инструмент, применений ему можно найти неограниченное количество.

Самым большим плюсом является то, что развернуть контейнер можно на абсолютно любой другой машине где установлен Docker.

Ладно, вводная часть что-то слишком затянулась. Перейдем к делу.

2. Установка

Если вы устанавливаете систему с нуля, то возможно рациональнее воспользоваться уже готовым образом от команды Hypriot.

Большинство пользователей не будет переустанавливать систему из-за того что хотят попробовать Docker. Поэтому ниже будет приведен процесс установки на Raspbian.

0. Если у вас старая версия Raspbian, обновляемся до новой т.к. с версии Debian 8 появилась поддержка ядра Docker "из коробки":

$ sudo sed -i "s/wheezy/jessie/" /etc/apt/sources.list $ sudo sed -i "s/wheezy/jessie/" /etc/apt/sources.list.d/raspi.list $ sudo apt-get update && sudo apt-get -y upgrade # answer "y" to upcoming questions $ sudo sudo apt-get -y dist-upgrade # answer "y" to upcoming questions $ sudo init 6 $ sudo apt-get -y autoremove $ sudo apt-get -y purge $(dpkg -l | awk "/^rc/ { print $2 }") $ sudo init 6

1. На официальном сайте отсутствует мануал с описанием установки на Raspberry Pi, но команда Hypriotпроделала большую работу по автоматизации установки Docker на Raspberry. Воспользуемся плодами их труда:

$ git clone https://github.com/hypriot/rpi-docker-builder.git $ cd rpi-docker-builder $ sudo sh build.sh $ sudo sh run-builder.sh

После этого пакет для установки Docker вы найдете в каталоге./dist/docker-hypriot_1.10.3-1_armhf.deb. На данный момент это последняя версия.

Ленивые могут воспользоваться готовыми пакетами от Hypriot:

$ curl -sSL http://downloads.hypriot.com/docker-hypriot_1.10.3-1_armhf.deb >/tmp/docker-hypriot_1.10.3-1_armhf.deb $ sudo dpkg -i /tmp/docker-hypriot_1.10.3-1_armhf.deb $ rm -f /tmp/docker-hypriot_1.10.3-1_armhf.deb $ sudo sh -c "usermod -aG docker $SUDO_USER" $ sudo systemctl enable docker.service

2. Проверка работоспособности

Sudo docker info

Docker version

Выведет информацию о версии, количестве контейнеров, версии ядра, драйверов и т.д.

3. Теперь любое приложение, которое есть в виде docker-контейнера для ARM, можно устанавливать с помощью docker run на Raspberry Pi.

Следующая команда скачает и развернёт небольшой уже настроенный веб-сервер:

Docker run -d -p 80:80 hypriot/rpi-busybox-httpd

Список контейнеров можно посмотреть с помощью

Docker ps

3. Использование

Можно, конечно, описывать основные команды и прочее, но за этим лучше обращаться к документации.

Поэтому мы рассмотрим на примере.

Предположим мы хотим собрать контейнер в котором будет веб сервер NGinx и PHP 5.4.

В начале пишется инструкция по сборке образа. Листинг файла с комментариями приведен ниже.

src: build/backend/Dockerfile

# Используем за основу контейнера Ubuntu 14.04 LTS FROM ubuntu:14.04 # Переключаем Ubuntu в неинтерактивный режим - чтобы избежать лишних запросов ENV DEBIAN_FRONTEND noninteractive # Устанавливаем локаль RUN locale-gen ru_RU.UTF-8 && dpkg-reconfigure locales # Добавляем необходимые репозитарии и устанавливаем пакеты RUN apt-get install -y software-properties-common RUN add-apt-repository -y ppa:ondrej/php5-5.6 RUN add-apt-repository -y ppa:nginx/stable RUN sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4F4EA0AAE5267A6C RUN apt-get update RUN apt-get upgrade -y RUN apt-get install -y wget curl php5-fpm php5-mysql php5-gd php5-curl php-pear php-apc php5-mcrypt php5-imagick php5-memcache supervisor nginx # Добавляем описание виртуального хоста ADD iloverpi.ru /etc/nginx/sites-enabled/iloverpi.ru # Отключаем режим демона для Nginx (т.к. запускать будем сами) RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf # Отключаем режим демона для php-fpm RUN sed -i -e "s/;daemonize\s*=\s*yes/daemonize = no/g" /etc/php5/fpm/php-fpm.conf # Добавляем конфиг supervisor (описание процессов, которые мы хотим видеть запущенными на этом контейнере) ADD supervisord.conf /etc/supervisor/conf.d/supervisord.conf # Объявляем, какие директории мы будем подключать VOLUME ["/var/www"] # Объявляем, какой порт этот контейнер будет транслировать EXPOSE 80 # Запускаем supervisor CMD ["/usr/bin/supervisord"]

src: build/backend/supervisord.conf

Nodaemon=true loglevel=debug command=/usr/sbin/nginx autorestart=true command=/usr/sbin/php5-fpm autorestart=true

Полный список команд с пояснениями доступен по ссылке .

Теперь, используя эту инструкцию, собираем образ iloverpi.ru.

Sudo docker build -t iloverpi.ru ~/PATH_TO_DOCKERFILE_DIR

Образ iloverpi.ru надо запустить, тем самым создав контейнер. Помимо этого требуется связать 80 порт хоста с 80 портом контейнера. Для удобства и полноты примера также свяжем /var/www хоста и /var/www контейнера.

$ sudo docker run -v /var/www:/var/www -p 80:80 -м -t iloverpi.ru

Убеждаемся что контейнер запущен:

Sudo docker ps | grep "iloverpi.ru"

Имя контейнера не было указано явно, поэтому он получил автоматическое название, с помощью которого мы можем с ним взаимодействовать.

У меня вывод предыдущей команды выглядит так:

D8429cc192c0 astgo.ru/dev:latest "/usr/bin/supervisor 20 seconds ago Up 19 seconds 0.0.0.0:80->80/tcp container23

Здесь "container23" - имя контейнера.

Для взаимодействия с командной строкой контейнера существует команда

Sudo docker exec -i -t container23 bash

После этого станет доступно обычное приглашение командной строки. Это и будет консоль нашего контейнера.

Итак, мы собрали и развернули свой контейнер, научились с ним взаимодействовать.

Статья получилась длинной, но надеюсь Вам было интересно. До новых встреч.

A 4-node Raspberry Pi Cluster. The top board is an original Model B, while the three below are brand new Raspberry Pi 2 boards.

Updated: This project was originally published on 26th Aug 2015 and was then updated on the 5th Sept 2015 with additional instructions on how to add a second Ethernet adaptor to the head node, and have it serve as a DHCP server for the other nodes in the cluster.

Over the weekend I sat down and built a small Raspberry Pi cluster consisting of 4 nodes. I used three boards for compute nodes and an for the head node. I wanted the cluster - more commonly known as a ‘bramble’ - to be as compact as possible, with just two cables coming out, one for power and the other for network. I made use of a USB hub to power the boards, and a small Ethernet switch which I could hack to be also be powered from the USB hub rather from a separate wall wart.

It’s hardly the biggest cluster built from Raspberry Pi boards, as far as I know the 120 Pi cluster built by the folks at Resin.io is still the biggest built, although since it’s actually 5 independent 24-node clusters, possibly the still takes the title.

However, even with just 4 nodes my pocket cluster is big enough for what I want, which is as a testbed for some distributed computing work I’m doing. The small cluster sitting on my desk lets me test code out before deploying jobs to the much more extensive, and expensive, cluster I’m using for grunt work on the project.

The 4 board ‘dogbone’ enclosure

The enclosure I finally settled on was a four board stackable ‘dog bone’ case that I picked up on Amazon , although if you’re willing to wait a little bit there are plenty of similar cases on AliExpress that can be had for much less. It shipped overnight and I had it the next day; it was the only thing I bought to build the cluster as I had everything else on the shelf.

The 5-port USB Hub

The USB hub I used was the thing that actually inspired me to do the build in the first place: It’s a 5-port hub from Anker and has coincidentally about the same footprint as the Raspberry Pi itself. With five ports, there’s one port for each of my four Raspberry Pi boards, and a final port left over to power an Ethernet switch for the cluster.

The 5V power supply and a spare USB cable

The first step is to carefully snip off the end of the 5V supply cable, making sure to label which of the two wires corresponded to the two wires left attached to the power brick. Stripping off the ends of the wires you can plug the brick into the wall and use a volt meter to measure which of the two wires is +5V and which is GND.

The 5V supply cable (top) and the USB cable end (bottom)

Then snip off the end of the USB cable and carefully, as the wires inside the cable are small and delicate, strip back the cover to reveal the wires. You’re looking for the red and black wires, the others carry data. You can just cut them off, you won’t need them.

The internal wiring of a USB cable

Soldering the two end of the cables together - joining the +5V to +5V, and the GND to GND - and then covering each individual wire, as well as the join itself, with some shrink wrap gives me the Frankenstein cable I need to power the Ethernet switch from the last available port of my USB hub.

The Frankenstein cable

After searching through my stack of spare cables to find the shortest USB and Ethernet cables possible, sticking the cluster together at this point came down to cable ties and velcro.

The finished Raspberry Pi cluster

% sudo apt-get install autofs

and then edit the /etc/auto.master file adding

/mnt/nfs /etc/auto.nfs

at the end. Then create the /etc/auto.nfs file, adding,

Rpi0 rpi0:/mnt/usb

and restart the autofs service,

% sudo /etc/init.d/autofs restart.

if all goes well at this point if you change to the /mnt/nfs/rpi0/ directory and the disk attached to the head node should automatically mount itself. You can check,

% df -h Filesystem 1K-blocksUsed Available Use% Mounted on rootfs14984668 25132281181235618% / /dev/root 14984668 25132281181235618% / devtmpfs470416 0470416 0% /dev tmpfs94944 232 94712 1% /run tmpfs 5120 05120 0% /run/lock tmpfs 189880 0189880 0% /run/shm /dev/mmcblk0p1 57288 19448 3784034% /boot rpi0:/mnt/usb 604670086460466944 1% /mnt/nfs/rpi0

to see whether it has been automatically mounted.

Blinking Lights

Alongside the USB flash drive (since I had one lying around) I installed a Blinkstick. A single software-controllable RGB LED, the stick actually comes in rather handy for server status light. It’s hard to ignore a blinking light. After slotting the stick into the head node’s last remaining USB port, you can set up the software by,

% sudo apt-get install -y python-pip python2.7-dev % sudo pip install blinkstick % sudo blinkstick --add-udev-rule

from there it’s actually pretty easy to manipulate the RGB LED from the command line.

Or when you want to use the Blinkstick programmatically to indicate status you can use the API, and your programming language of choice .

Next Steps

I travel a lot. That means I spend a lot of time away from my home office. While I can leave the cluster up and running and just ssh into it while I’m away, I’d actually sort of like to be able to take it on the road with me to shows. So, going forward, I’d really like just to be able to pick the cluster up and dump it down on any network.

That means I’m going to have to reconfigure the networking just a little bit.

Instead of directly connecting the Ethernet switch to the external network, and having my home router allocate IP addresses for each of the nodes, as a next step I’m going to add a USB Ethernet adaptor to the head node. This will give the head node two Ethernet connections.

The first will connect to the external network, giving the head node - and hence the cluster - an ‘external’ IP address. The second will connect to the cluster’s Ethernet switch. We can then configure the head node as a DHCP server for other three ‘internal’ nodes attached to the switch, creating a second network visible only to the cluster.

In this configuration I’ll still be able to ssh into the head node, but I’ll only be able to reach the three compute nodes from the head node. There is a problem however: How will I know the external IP address of the head node?

Adding an LCD

The Blinkstick is good for simple messaging, you can actually do a lot with an RGB LED to let yourself know what’s going odd. But it’s actually pretty easy to add a simple LCD display to the head node.

After connecting the panel you’ll need to install the I2C tools and associated Python libraries

% sudo apt-get install python-smbus % sudo apt-get install i2c-tools

and to enable I2C on the head node by adding the following at the bottom of the /boot/config file,

device_tree= dtparam=spi=on dtparam=i2c1=on dtoverlay=w1-gpio-pullup,gpiopin=3,pullup=3 dtoverlay=w1-gpio-pullup,gpiopin=5,pullup=5

and adding the following modules to the /etc/modules file,

I2c_dev i2c_bcm2708

After rebooting the head node you should be able to see the panel with an I2C ID of 27,

% sudo i2cdetect -y 1 0123456789abcdef 00:-- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- UU -- -- -- -- 20: -- -- -- -- -- -- -- 27 -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- UU -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- --

You can see that eth0 has the static internal IP address we allocated to it, while eth1 has a new IP address allocated by our home router. If all goes to plan you should be able to ssh into the head node using its new external IP address, and see something like this,

% ifconfig eth0Link encap:EthernetHWaddr b8:27:eb:22:60:fb inet addr:192.168.50.1Bcast:192.168.50.255Mask:255.255.255.0 RX packets:2470 errors:0 dropped:0 overruns:0 frame:0 TX packets:2267 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:215730 (210.6 KiB)TX bytes:237032 (231.4 KiB) eth1Link encap:EthernetHWaddr ac:29:3a:da:74:37 inet addr:192.168.1.194Bcast:192.168.1.255Mask:255.255.255.0 UP BROADCAST RUNNING MULTICASTMTU:1500Metric:1 RX packets:15245 errors:0 dropped:1 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1787746 (1.7 MiB)TX bytes:283761 (277.1 KiB) loLink encap:Local Loopback inet addr:127.0.0.1Mask:255.0.0.0 UP LOOPBACK RUNNINGMTU:65536Metric:1 RX packets:4 errors:0 dropped:0 overruns:0 frame:0 TX packets:4 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:260 (260.0 B)TX bytes:260 (260.0 B)

% route -n Kernel IP routing table Destination Gateway Genmask Flags Metric RefUse Iface 0.0.0.0 192.168.1.254 0.0.0.0 UG000 eth1 192.168.1.0 0.0.0.0 255.255.255.0 U 000 eth1 192.168.50.00.0.0.0 255.255.255.0 U 000 eth0

If not everything goes to plan and you’re stuck unable to reach the head node over the network, it’s possible that you might have to dig out a HDMI monitor and a USB keyboard and connect them directly to the head node - you can temporarily yank the USB disk to give yourself and free USB port for the keyboard - so you can diagnose and fix any networking issues.

Hopefully however you can reach the head node from the external network. You should be able to ping both external hosts on the 192.168.1.* network, and internal hosts on the 192.168.50.* network.

However, at least right now, if we ssh into one of the compute nodes, while they can see the head node - and each other - they can’t yet see the outside world. We’re going to have to forward packets from the internal to the external networks before that’s possible.

On the head node go ahead and,

% sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward "

and then edit the /etc/sysctl.conf file uncommenting the line saying,

Net.ipv4.ip_forward=1

After activating forwarding we’ll need to configure iptables ,

% sudo iptables - t nat - A POSTROUTING - o eth1 - j MASQUERADE % sudo iptables - A FORWARD - i eth1 - o eth0 - m state -- state RELATED , ESTABLISHED - j ACCEPT % sudo iptables - A FORWARD - i eth0 - o eth1 - j ACCEPT % sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

and then add at the bottom of the /etc/network/interfaces file a line to load the tables on boot,

Up iptables-restore < /etc/iptables.ipv4.nat

Rebooting the head node at this point, you should now be able to ssh into any of the compute nodes from the head node and be able to ping the outside world,

% ssh rpi1 Linux rpi2 3.18.11-v7+ #781 SMP PREEMPT Tue Apr 21 18:07:59 BST 2015 armv7l The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Sat Sep5 20:49:07 2015 from rpi0 % ping 8.8.8.8 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_req=1 ttl=54 time=23.8 ms 64 bytes from 8.8.8.8: icmp_req=2 ttl=54 time=21.4 ms 64 bytes from 8.8.8.8: icmp_req=3 ttl=54 time=23.2 ms ^C --- 8.8.8.8 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2003ms rtt min/avg/max/mdev = 21.470/22.838/23.829/1.014 ms %

That’s it. We have a working cluster.

In Closing

At this point we have a cluster with two cables going into it, one for power and the other for network. You can plug into any network and the head node will report its external IP address on an LCD panel, allowing you to ssh into it, and from there you can ssh into - and between - any of the nodes in the cluster without needing a password. All the nodes also share a disk.

In other words, it’s all pretty much all working at this point. In fact, I’m currently using it as a desktop Hadoop cluster .

From here there are a couple of things we could do, the most obvious next step would be to add some SNMP monitoring, and an external facing ‘status’ dashboard on the head node to monitor the cluster health . However in the longer term, the free Ethernet port on the switch means that we can expand the cluster fairly easily by adding another rack of four compute nodes without too much extra effort.