Full text
DEVELOPMENT OF MULTIDOMAINS FOR THE OPENHUACA CLOUD PLATFORM A Degree Thesis Submitted to the Faculty of the Escola Tècnica d'Enginyeria de Telecomunicació de Barcelona Universitat Politècnica de Catalunya by DANI CAPDEVILA ROCA In partial fulfilment of the requirements for the degree in NETWORK ENGINEERING Advisor: JOSE LUIS MUÑOZ TAPIA Barcelona, July 2018
OpenHuaca Cloud Platform Abstract This project is a collaboration in the development of the OpenHuaca platform, a tool that allows its users the possibility of creating and managing several virtual containers in an easy and convenient way. The OpenHuaca Cloud Platform was born with the idea of becoming a solution that unifies and manages the creation of these different types of virtual machines, as well as their resources and distribution in the system on which it is executed. The main objective has been to design new modules and implement improvements in the existing ones, adding new functionalities in the software; in addition to converting it to Python code. Therefore, the work has focused on learning the different technologies involved; the definition and programming of the Bases structure, on which the virtual containers are built; in the integration and use of Ansible as a provisioning system for virtual machines and in documenting and defining in detail the operation of this platform. 2
OpenHuaca Cloud Platform Resum Aquest projecte és una col·laboració en el desenvolupament de la plataforma OpenHuaca, una eina que permet als seus usuaris la possibilitat de crear i gestionar diversos contenidors virtuals d’una forma fàcil i còmoda. La Plataforma Cloud OpenHuaca va néixer amb la idea de convertir-se en una solució que unifica i regula la creació d’aquests diferents tipus de màquines virtuals, així com els seus recursos i distribució en el sistema sobre el que s’executa. El principal objectiu ha estat el de dissenyar nous mòduls i implementar millores en els existents, afegint noves funcionalitats en el programari; a més de convertir-lo a codi Python. Per tant, el treball s'ha centrat en l'aprenentatge de les diferents tecnologies involucrades; la definició i programació de l'estructura de Bases, sobre les quals es construeixen els contenidors virtuals; en la integració i ús de Ansible com a sistema d'aprovisionament de les màquines virtuals i en documentar i definir en detall el funcionament d’aquesta solució. 3
OpenHuaca Cloud Platform Resumen Este proyecto es una colaboración en el desarrollo de la plataforma OpenHuaca, una herramienta que permite a sus usuarios la posibilidad de crear y gestionar varios contenedores virtuales de una forma fácil y cómoda. La Plataforma Cloud OpenHuaca nació con la idea de convertirse en una solución que unifica y regula la creación de estos diferentes tipos de máquinas virtuales, así como sus recursos y distribución en el sistema sobre el que se ejecuta. El principal objetivo ha sido el de diseñar nuevos módulos e implementar mejoras en los existentes, añadiendo nuevas funcionalidades en el software; además de convertirlo a código Python. Por lo tanto, el trabajo se ha centrado en el aprendizaje de las diferentes tecnologías involucradas; la definición y programación de la estructura de Bases, sobre las que se construyen los contenedores virtuales; en la integración y uso de Ansible como sistema de aprovisionamiento de las máquinas virtuales y en documentar y definir en detalle el funcionamiento de esta plataforma. 4
OpenHuaca Cloud Platform Acknowledgements First, I would like to thank Jose Luis Muñoz. He has given me the opportunity to participate in this project and thanks to him I have learned a lot. In addition, I would also like to remind my teammates, with whom we have given a hand whenever possible. In the second place I would like to thank Claudia. He has supported me and encouraged me in this work, and with her, it has been easier to face the obligations I had for the past months. Per últim, però no menys important, he de donar les gràcies als meus pares. Vosaltres sou els que m’heu donat suport, no només econòmic, que també; sinó els ànims i la comprensió davant del estudis que he estat cursant a la UPC. Una abraçada. 5
OpenHuaca Cloud Platform Revision history and approval record Revision Date Purpose 0 05/05/2018 Document creation 1 20/05/2018 General Revision of certain sections. 2 05/06/2018 General revision 3 24/06/2018 Revision of the Networking and adding Provisioning explanations. 4 24/06/2018 Revision of the Bases and architecture, among others. 6 26/06/2018 General revision of the document contents with corrections. 7 27/06/2018 Conclusions, corrected Introduction, State of the art modified. 8 29/06/2018 Overall revision by my Advisor. Format. 9 30/06/2018 General Revision 9 02/07/2018 Final Revision DOCUMENT DISTRIBUTION LIST Name e-mail Daniel Capdevila Roca [email protected] Jose Luis Muñoz Tapia [email protected]du Rafa Genés Durán [email protected] Daniel Campos Gómez [email protected] Jorge Eduardo Buzzio García [email protected] 6
OpenHuaca Cloud Platform WRITTEN BY: DANI CAPDEVILA ROCA REVIEWED AND APPROVED BY: JOSE LUIS MUÑOZ TAPIA Date 02/07/2018 Date 02/07/2018 Name Dani Capdevila Roca Name Jose Luis Muñoz Tapia Position Project author Position Project Supervisor 7
OpenHuaca Cloud Platform Table of contents Abstract......................................................................................................................................................2 Resum.........................................................................................................................................................3 Resumen.....................................................................................................................................................4 Acknowledgements....................................................................................................................................5 Revision history and approval record........................................................................................................6 Table of contents........................................................................................................................................8 List of Figures..........................................................................................................................................10 List of Tables............................................................................................................................................11 1. Introduction..........................................................................................................................................12 1.1. Statement of purpose....................................................................................................................12 1.2. Requirements and specifications..................................................................................................13 1.3. The heritage of a biggest project..................................................................................................14 1.4. Work Plan.....................................................................................................................................15 1.4.1. Work Packages.....................................................................................................................15 1.4.2. Grant Diagram......................................................................................................................17 1.5. Plan Evolution and Changes.........................................................................................................17 2. State of the art of the virtual machines.................................................................................................18 2.1. Virtual Machines..........................................................................................................................18 2.2. Linux Containers (LXC)..............................................................................................................19 2.3. Kernel-based Virtual Machines (KVM).......................................................................................20 2.4. Docker..........................................................................................................................................20 2.5. VMware........................................................................................................................................20 2.6. ProxMox.......................................................................................................................................21 3. OpenHuaca Cloud Platform.................................................................................................................23 3.1. Organization and Research...........................................................................................................23 3.2. About OpenHuaca........................................................................................................................24 3.3. Architecture..................................................................................................................................24 3.3.1. Typical usage scenario........................................................................................................24 3.3.2. Software Architecture and Virtual Machines......................................................................26 3.3.3. The file system....................................................................................................................27 3.3.4. System resources.................................................................................................................28 3.3.5. The Bases............................................................................................................................29 Core Bases.................................................................................................................................30 Baked Bases..............................................................................................................................30 3.3.6. Containers Organization......................................................................................................31 3.3.6.1. What is exactly a domain, in OpenHuaca?.................................................................31 3.3.6.2. How does a domain work behind the scenes?.............................................................32 8
OpenHuaca Cloud Platform 3.3.6.3. How are the hosts connected?.....................................................................................34 3.3.7. Secure Access......................................................................................................................36 3.3.8. Provisioning........................................................................................................................37 3.3.8.1. Why do we need it........................................................................................................37 3.3.8.2. Ansible.........................................................................................................................38 3.3.8.3. How we use it in OpenHuaca.......................................................................................38 PLAYBOOKS......................................................................................................................39 ROLES.................................................................................................................................40 How do we prepare the containers to provision them..........................................................40 4. Objectives achieved.............................................................................................................................43 5. Budget..................................................................................................................................................44 6. Conclusions and future development...................................................................................................45 6.1. Conclusions..................................................................................................................................45 6.2. Future Developments...................................................................................................................45 Bibliography.............................................................................................................................................47 Appendix..................................................................................................................................................48 Ansible Guide of use, for OpenHuaca.................................................................................................48 1. Installation..................................................................................................................................48 2. About the virtual machines........................................................................................................48 3. Basic SSH Keys usage...............................................................................................................49 4. Inventory....................................................................................................................................50 5. Playbooks...................................................................................................................................51 6. Modules......................................................................................................................................55 OpenHuaca: Commands......................................................................................................................60 OpenHuaca: Software Structure..........................................................................................................63 1. Python Utilities and Modules....................................................................................................63 2. Directories.................................................................................................................................64 Glossary...................................................................................................................................................65 9
OpenHuaca Cloud Platform Project: Development of Multidomains for the Open Huaca Cloud Platform WP ref: (WP2) Major constituent: COMPONENTS DESIGN Definition of the software core functionalities to ensure a good final version. Planned start date: 04/03/18 Planned end date: 20/03/18 Start event: 04/03/18 End event: 14/04/18 Internal task T1: Python Learning and studying the actual Implementations Internal task T2: Design of containers management logistics Internal task T3: First code implementations and tweaks Internal task T4: Define clear goals to achieve in the new version Internal task T5: Report Deliverables: Dates: Project: Development of Multidomains for the Open Huaca Cloud Platform WP ref: (WP3) Major constituent: DEVELOPMENT Implementation of the designed functions and other interesting add-ons. Test every module while coding to ensure its consistence. Planned start date: 20/03/18 Planned end date: 27/05/18 Start event: 15/04/18 End event: 20/06/18 Internal task T1: Development of multi-domain for Open Huaca. Implementing in Python. Internal task T2: Improvement of existing functionalities. Internal task T3: Development of containers management Internal task T4: Development of the bases code Internal task T5: Testing of the new implemented functionalities Internal task T6: Reports Deliverables: Dates: Project: Development of Multidomains for the Open Huaca Cloud Platform WP ref: (WP4) Major constituent: TESTING AND IMPROVEMENT Final Tests and evaluation of the behavior of the implementation, conclusions and evaluation of future extensions. Planned start date: 27/05/18 Planned end date: 02/07/18 Start event: 20/06/18 End event: 02/07/18 Internal task T1: Defining the Ansible Integration Internal task T2: Test of the main Development Internal task T3: Suggest of future improvements Internal task T4: Evaluate of behavior in different situations Internal task T5: Manuals Internal task T6: Reports Deliverables: Dates: 16
OpenHuaca Cloud Platform 1.4.2. Grant Diagram Figure 1: The grant diagram 1.5. Plan Evolution and Changes We started studying the old code, the translated one and getting inside the application. The first steps were to implement some basic functions in Python as the creation of the containers, destroy them, or copy the existing ones as snapshots, implementing the official dependence that LXC provides on its resources. That introduction in the application was slower than expected at first. More or less halfway through the project, we started to implement the new functionalities so that the virtual containers were built on other base containers (the details are explained in the technical part). Once this part was implemented, we started with the provisioning study and documentation. With limited time and with Jorge, we decided to improve the existing implementations with commentaries in the code and to define the application as best as possible. One of the impediments has been caused by trying to provision with Ansible via SSH. It was tried to solve for several weeks and was a part that delayed the implementations. 17
OpenHuaca Cloud Platform 2. State of the art of the virtual machines 2.1. Virtual Machines If we want to understand a little bit more about what the containers are, we have to consider that there are different types, and in different levels. All container types are super useful. Containers are a way of organizing stuff that is running on a machine. The difference is that depending on what we need to run, some containers are more useful than others for our purposes. Figure 2: The different types of containers[14] VIRTUAL MACHINES These are the most typical VMs, those that run entire operating systems. These works just like real machines, and typically demand more resources. Anyway, in some cases it is needed to run a certain complete OS, maybe to run a program permanently of for compatibility reasons. MACHINE CONTAINERS Machine containers were the first step on the containers technologies. 18
OpenHuaca Cloud Platform The big change on containers was these are more scalable and powerful than a typical virtual machine. Here is where we locate the main purpose of OpenHuaca, using the LXC that linux provide us. 1. The kernel has no idea about an LXC container or any other one. 2. In the Linux kernel there is no such thing as the list of containers. So then, Kernel doesn’t know anything about the containers. PROCESS CONTAINERS Process virtual machines are designed to execute computer programs in an independent platform environment, that abstracts away details of the underlying hardware or operating system and allows a program to execute in the same way on any platform. This type of VM has become popular with the Java programming language, which is implemented using the Java virtual machine.[5] At the end, containers are just a way to isolate processes, and how to make them believe they're on a particular environment (in our case, inside of an Operative System). We are going to gossip about the interesting technologies that exist today in the market: 2.2. Linux Containers (LXC) LXC is a non-graphical and lightweight software build in the Kernel Linux to run multiple virtual Linux units simultaneously on a single control host. Containers are isolated with Kernel Control Groups (as known as cgroups) and Kernel Namespaces. This is, creating diverse types of Linux distributions to assigning limited resources to each one. But unlike Openhuaca, it does not have user management, nor allow a user to manage the domains or any kind of modification of the network. It only generates a bridge on the host and binds all containers with VETH level 2 links. So, all the containers are generated in the same network and these are connected each other. Also it should be noted that Openhuaca prepares the containers to accept SSH connections and orchestrates the certification authorities and their certificates. LXC provides an operating system-level virtualization where the Kernel controls the isolated containers with the limitation of there is not a method that has direct hardware access, so, you cannot run near-real-time-requirements for applications. 19
OpenHuaca Cloud Platform We can not have a huge amount of containers because they share the same kernel. This ends up increasing the latency. Another restraint is that with this technique you cannot virtualize any OS since it is based on OS-level virtualization technology that allows creation and running of multiple isolated Linux environments (also called VE). [3] 2.3. Kernel-based Virtual Machines (KVM) KVM is a virtualization solution based on the Linux Kernel. It allows to implement a complete virtualization with that Linux architecture. Since Linux version 2.6.20, this module is included in the Linux kernel. KVM uses raw OS disk images. In this way, every machine has its self-virtualized hardware, its NIC, its hard disks, its graphical card, etc. Another remarkable feature of KVM is that, by means of raw image we can run any virtual Windows or Linux OS.[2] Implementation of KVM in Openhuaca will offer to users a very simple way to manage, create and delete VMs. It is not going to be my purpose on the project, but this container technology will be implemented in OpenHuaca by my project mate Daniel Campos. 2.4. Docker Docker[1] has also started from the LXC libraries, but has specialized in creating containers focused to execute a single process, while OpenHuaca virtualizes an entire operating system. Docker manages all domains, interfaces and even has a large repository where you can find a large number of specific containers. The big difference is that all these containers only execute a single process, so this makes the big difference against OpenHuaca. Docker is designed to run from a host and create different services, so it performs container virtualization, but is not intended to manage an entire computer environment. However, it is a really useful tool; Docker simply does not target the same audience that OpenHuaca aims for, allowing our project to move towards a different market. As a summary, Docker is a very complete and improved tool from LXC, but is focused on virtualizing processes and not to the entire operating systems as OpenHuaca does and how it differs. 2.5. VMware Currently VMware has become a big company that presents different virtualization tools and multi-vendor hybrid cloud platforms, among other products and a large IT services variety.[21] 20
OpenHuaca Cloud Platform VMware offers solutions focused on business sector and also integrates its proprietary software.[19] It is true that they offer a free solution for desks (VMware Workstation), but it does not pretend to act as a cloud platform would and its focused on a different target. We are going to overview their main VMM solutions. VMware vSphere (previously known as ESX)[22] is an enterprise solution hypervisor for deploying and serving virtual computers. This one is not a software application installed on an operating system; it includes and integrates vital OS components, such as a kernel. This is called a Type-1 hypervisor. So this one is a really deeper to the hardware solution that differs too much from OpenHuaca. VMware vRealize is its automation solution, for provisioning, automate and manage infrastructures, an application or any custom IT services (XaaS). At the end VMware is focused on a different market on that OpenHuaca is not targeting at this time. 2.6. ProxMox The last one remarkable to analize is ProxMox[1]. This one is an open source container virtualization program, that works with both LXC and KVM container types. It also has a great control of domains and has a very comfortable web interface where it is possible to monitor and manage the containers. It works on GNU/Linux distributions (Type-2 hypervisor, host over an OS). This program is the most similar to OpenHuaca but has two major differences that can be considered large enough to think that OpenHuaca has a potentially different audience beside Proxmox. The first difference is how to distribute and install the software: In ProxMox the user needs a cluster of machines to install an ISO file, which means that to carry out any test you will need to invest in a minimum of 3 hardware equipment, in order to realize all the configurations to link them and finally to be able to create your first container. As opposite, OpenHuaca is distributed as a Debian installable package, so in any Linux distribution the user will be able to create containers in a matter of seconds. The other big difference is that ProxMox is intended for large environments. As we just commented, the installation needs at least a cluster of 3 nodes. It’s true that with an environment like this you gain reliability in your machines, but for small environments usually a user doesn’t have 3 or 5 hardware equipments. 21
OpenHuaca Cloud Platform OpenHuaca offers the user the facility of being installed itself in a single system and launching its own virtual environment. Shortly, ProxMox is the most similar tool to our solution, but there are two key differences between this and our solution, which distinguish one target from the other. Proxmox is distributed in ISO files, so the user has to install their own operating system while OpenHuaca distributes Debian packages (DEB), which allows to be installed in any Linux distribution. The other difference is that ProxMox is designed for large stages, what means the user needs to make a much greater initial investment in hardware against OpenHuaca. 22
OpenHuaca Cloud Platform 3. OpenHuaca Cloud Platform It is time to start defining how OpenHuaca is structured, how has been developed, and to describe and show a snapshot of how it has been organized after the project. 3.1. Organization and Research First we are going to tell how we had been organizing to develop and define the different components of the project. Meetings The supervisor Jose, as Rafa and Jorge, has a clear point of view of how OpenHuaca had to grow. They knew what it was necessary to focus efforts on and Jose guided us during the project in that direction. Each week we had meetings in Jitsi platform, among others, to organize ourselves and share our progress. The work plan (1.4. Work Plan) specifies how we have organized these four months the different tasks. Efforts have focused on defining the structure of the bases, and defining the integration of the provision techniques in the software, while we have improved the whole code. Platforms To share our resources and program different parts in parallel, we had been using a common server with different virtual machines that Rafa started for us. The server (j3o.upc.edu) was given to us by the university and had been useful to test the code on its virtual machines and it has been our common space to share the documentation. We had been using git-hub as our version control support. Working with branches in different tasks has been useful to integrate more easily the different blocks of code. Anyway, at this point, is important to say that, as the big amount of code is inside a unique file, sometimes was hard to merge the parallel modifications, and can be profitable to the nearest future to try to disaggregate it consciously. 23
OpenHuaca Cloud Platform 3.2. About OpenHuaca OpenHuaca is a cloud platform developed to let its users manage different types of OS containers with a unique solution. These containers will actually be different isolated virtual machines, running in the same kernel of a unique physical machine. Technically our software creates virtual machines and machine containers. OpenHuaca allows the user to manage all the VMs defined inside different domains, with the idea of not necessarily having any knowledge of their IPs or passwords, because of the auto-configured DNS, DHCP and the usage of SSH technologies. The user only needs to know the machines username, its name and in which domain where launched. In addition, the supervisor will receive its own certificates in order to be able to access to his containers more easily. Apart from that, OpenHuaca also takes care of all the details in order to facilitate the job of the network administrator. This program is distributed as a Debian installable package, so with a simple command OpenHuaca can be installed in any Linux distribution with Debian support. Besides, this product will integrate an accurate monitoring of resources, at the same time that allows to dynamically personalizing the services destined to each container. A good way to see the potential of this project will be to show you a clear example based on a real environment. This example is described in “3.3.1. Typical usage scenario” section. More information will be available in our official website www.openhuaca.com . 3.3. Architecture In this section we will define the architecture of the application and how it is designed in each of its parts. 3.3.1. Typical usage scenario To better understand the skills of our solution, we are going to watch a setup in which OpenHuaca would be useful. 24
OpenHuaca Cloud Platform The typical usage scenario for OpenHuaca is in a classroom. We need to imagine the professor (hypervisor) and its students (hosts). Also understand that a professor impart several subjects. Each subject maybe requires a specific user access and a selection of software installed, but also there is a shared common base. Perhaps a large part of the installed software will be common in all subjects and the teacher decides to use a single Linux distribution as “Ubuntu Mate”. So, what if all this common data and software shared by all the students is a shared disk space, in a single machine? As you see, the idea that we propose is to has a common base file system which also can be easily updated. These updates affect simultaneously all the hosts that were built on top of our common base. “OpenHuaca aims to unify different technologies to turn this task into a mere procedure” As said before, the professor can has a basic image for all its classrooms. From this base he could mount the different subjects (environments) that he will teach. Some of them can have a specific root file system, others can dispose of different enabled users or some specific software… Any structure that may have any system. It will depend on the preferences of the administrator. Now, the virtual created hosts from a subject can be grouped in the same domain. Also, the user “Professor” will has access to all the containers (hosts) of each domain, so if he has any doubts about what their students are doing, he can access any machine with a single command to see what they are doing (the students, sure). On the other hand, when a student arrives to his workstation, has to indicate its user and subject, so it does not matter where he has sat or if there was another subject in that student computer before. At that moment the container of the student will be loaded so all the files will be placed how where left by the student on its last session. Finally, in our case the administrator can be the manager of the laboratory; he can monitor with a single command the consumption of resources of all machines in real time, so if he need to modify the able resources for a container, he will be able to modify it in a simple way. 25
OpenHuaca Cloud Platform Figure 5: Representation of a domains distribution 3.3.6.2. How does a domain work behind the scenes? The domains are defined in the directory /etc/openhuaca/domain-available/ where the file DOMAIN_NAME specifies its new network IP and MAC . BRIDGE We start defining every created domain with an unique bridge that connects all its containers, and which we call “H_DOMAIN_NAME” in /sys/class/net/. The hypervisor has also its own bridge “lxcbr0”, where all the domains are connected to. 32
OpenHuaca Cloud Platform Figure 6: Representation of a connected domain The bridge is necessary to connect the domain hosts themselves, and can be used to go through it to the hypervisor or to the Internet. We start defining this bridge with an able IP of the assigned range. DNS and DHCP (dnsmasq) It is necessary to set-up a caching DNS. For that issue we will use dnsmasq, an easy and lightweight program to administrate private servers, manage DNS (Domain Name Server) and DHCP (Dynamic Host Configuration Protocol) servers, among other functions. Is widely available and it is included in almost all Linux distributions. After the bridge creation, its dnsmasq gives a domain name to the hosts. Dnsmasq is used as a DHCP to give a default route on its domain. After the steps defined, the connection is done. The following configuration is done on the hypervisor: •Main configuration file: /etc/dnsmasq.conf 33
OpenHuaca Cloud Platform log-facility=/var/log/dnsmasq.log #Specifies a log file server=/domini1/172.20.1.1 #In this file we are defining our non-public servers (of our server=/domini2/172.20.0.1 # domains) with its assigned IP direction related. server=/domini90/172.20.2.1 … •Configuration of the lxc domain: /etc/dnsmasq.d/lxc bind-interfaces #Forces resolve all the interfaces dnsmasq is listening except-interface=lxcbr0 #Except this one server=/lxc/172.30.3.1 The system dnsmasq is used as external DNS, and identifies the domain routes. As we told before, the python source code has comments about added attributes and modified files. In this description we focus on the most important configurations. 3.3.6.3. How are the hosts connected? The DHCP help us giving a domain name to the virtual machines. The domains dnsmasq save a range of private addresses for all its VMs (hosts) and also assigns the default routes to these hosts. This is how it is configured [16]: “ dnsmasq - - / / - -s lxc S lxc u lxc dnsmasq -- - -- -strict order bind interfaces -- - =/ / / _ .pid fle run openhuaca H BRIDGE pid -- - _ -- - _ _listen address H ADDR dhcp range H DHCP RANGE -- - - = _ _ -- - -dhcp lease max H DHCP MAX dhcp no override -- - = -- = _except interface lo interface H BRIDGE -- - =/ / / . _ .dhcp leasefle var lib misc dnsmasq H BRIDGE leases -- - _ 6_dhcp authoritative H IPV ARG ” 34
OpenHuaca Cloud Platform --dhcp-range <start-addr> Enable the DHCP server. -s lxc Specifies DNS domains for the DHCP server. -S /lxc/ Specify IP address of upstream servers directly. If one or more optional domains are given, that server is used only for those domains and they are queried only using the specified server. This is intended for private nameservers. We define it to point directly to our DNS server what we call ‘lxc’. -u User id to which dnsmasq will change after startup. Dnsmasq must normally be started as root, but it will drop root privileges after startup by changing id to another user. --strict-order Forces dnsmasq to try each query with each server strictly in the order they appear in /etc/resolv.conf . Because by default dnsmasq will send quaries to any of the upstream servers it knows about and tries to favour server that are known to be up. --bind-interfaces On systems which support it, dnsmasq binds the wildcard address, even when it is listening on only some interfaces. It then discards requests that it shouldn't reply to. This has the advantage of working even when interfaces come and go and change address. This option forces dnsmasq to really bind only the interfaces it is listening on. About the only time when this is useful is when running another nameserver (or another instance of dnsmasq) on the same machine. Setting this option also enables multiple instances of dnsmasq which provide DHCP service to run in the same machine. --pid-file Alternate path for dnsmasq to record its process-id in. --listen-address Listen on the given IP address(es). --dhcp-lease-max Limits dnsmasq to the specified maximum number of DHCP leases. The default is 1000. This limit is to prevent DoS attacks from hosts which create thousands of leases and use lots of memory in the dnsmasq process. --dhcp-no-override This flag forces "simple and safe" behaviour to avoid problems in such a case. --interface Listen only on the specified interface(s). --except-interface Do not listen on the specified interface. (that is listened by default) --dhcp-leasefile Use the specified file to store DHCP lease information. --dhcp-authoritative Should be set when dnsmasq is definitely the only DHCP server on a network. For DHCPv4 it changes the behaviour, so that DHCP requests on unknown leases from unknown hosts are not ignored. This allows new hosts to get a lease without a tedious timeout under all circumstances. It also allows dnsmasq to rebuild its lease database without each client needing to reacquire a lease, if the 35
OpenHuaca Cloud Platform database is lost. For DHCPv6 it sets the priority in replies to 255 (the maximum) instead of 0 (the minimum). You can check the official dnsmasq documentation to know more about all its options and configurations. At this point we understand that our virtual machines network has a tree structure. 3.3.7. Secure Access The most secure method to grant access to all our virtual machines is using SSH keys. SSH Credentials In order to connect and grant access to the different virtual machines through ssh, it is needed to generate an SSH certificate. That has to be done by the administrator of the environment. It is necessary to create a certification authority for each domain, what is necessary to get those containers isolated. When a certificate is created, 3 files are generated: the public key, the private key and the certificate itself. With these 3 files, that are delivered to the system users, it will be possible to access the different virtual machines during the specified time, those that contain the specified user inside the certificate. To do that automation in OpenHuaca, a certification authority has to be generated for each domain. Then, the VMs are configured to accept the CA only from their domain. To sum up, the certificates must be generated from a specific CA, for a unique user and for a limited time. How to create a Certification Authority A pair of asymmetric RSA keys are generated, and on that action we get a couple of keys: the public key to be sent and the private one. We want to underline that all passwords (private keys) are saved on the hypervisor and must be protected by the administrator. The public key has to be distributed to all the containers. Apart from that, it is necessary to add the public key as a trusted CA to the file /etc/ssh/sshd_config , a file that provides defaults for 36
OpenHuaca Cloud Platform users. At this point the CA configuration of the domains is finished. The user can start generating certificates. Starting on it, it is necessary to specify the domain, user and the limit time. The user has also to know the CA password. The services has been configured to add an ID of 8 hexadecimal characters for each certificate. This identifier is useful to issuing several certificates for a single user. Having different certificates is helpful to allow access in a set of different dates. Figure 7: Certifications examples All this details, as SSH, grants a good security shield for our virtual network. 3.3.8. Provisioning 3.3.8.1. Why do we need it It has been decided looking for a solution so that the supply of our containers becomes a fast and descriptive process. This has been thought for two reasons. 37
OpenHuaca Cloud Platform On the one hand, so that the supply of our machines can be faster. Once we have a configuration created, it can be applied to new containers regardless of their version of operating system or distribution. On the other hand, we will use it as control of changes and optimization of the system. For example, we perceive that several hosts have installed the same software and, therefore, this is replicated in the file system. The administrator could install that same software on the base system to make it available for all virtual containers. The second issue, would be implemented in a next version. Valuing the different alternatives (as SaltStack, Puppet, Chef, Terraform …), we finally decided to use Ansible for its simplicity and community behind. Having a simple, structured supply system, with a large community behind, were also good reasons that led us to trust on it. 3.3.8.2. Ansible Ansible is a really easy and open source IT configuration management, deployment, and orchestration tool.[9] Is Designed for multi-tier deployments and let us manage many systems at once. It is easy to deploy and most important thing is that it uses a very simple language (YAML, in the form of Ansible Playbooks) that allow you to describe your automation jobs in a way that approaches plain English. Ansible works by connecting to our nodes and pushing out small programs (called “Ansible modules”) to them. These programs are written to be resource models of the desired state of the system. It then executes these modules, and removes them when finished. To connect to the machines to provision, it uses SSH keys by default, as it supports passwords too. Also let us login as any user, and then sudo if we need to. 3.3.8.3. How we use it in OpenHuaca Lets focus on what is the main provisioning method that Ansible uses, and what we are going to use. 38
OpenHuaca Cloud Platform There is a large set of details about the configuration and understanding of Ansible that I have attached in the appendix "Ansible Guide of use". To be more descriptive at this point, we are going to define Playbooks and Roles, two essential parts of this provisioning software. We want to focus on that Ansible is able to detect on a fast way which OS is running in every host, and that our Playbooks, defined below, doesn’t need to be written in different ways, because Ansible ensures its execution regardless of the operating system. PLAYBOOKS Playbooks are our instruction manuals. At a basic level, playbooks can be used to manage configurations of and deployments to remote machines. Also are designed to be human-readable and are writen in a basic text called YAML, that is a declarative programming language. In fact this is what makes Ansible so friendly. --- # sudo apt install apache2 # sudo service apache2 start - hosts: all remote_user: root tasks: - name: Ensure Apache is at the latest version apt: name=apache2 state=latest - name: Ensure Apache is running service: name=apache2 state=started enabled=yes ... This is how the easiest playbook can look like. It is used to install and start Apache to all hosts. --- # This playbook deploys a simple standalone Tomcat 7 server. - hosts: tomcat-servers remote_user: root become: yes become_method: sudo roles: - selinux - tomcat ... 39
OpenHuaca Cloud Platform Here you can see what a playbook looks like, that calls a couple of roles. ROLES What If we want to reuse pre-defined playbooks? The idea behind Includes or Imports is to try to reuse code as much as posible writed plays. On this way we decide to adapt the community suggestions for a consistent and more practical management of our supplies. Roles are well organized packets of configurations to be reused in any host. We talk about vitamined includes, and a good way to well structure and organize the different instructions. The Roles have different benefits. Working with them we can detect the host OS, create and use different variables, templates, files, load scripts … The Roles are the way on how the community can share their provisioning configurations with another users. The source galaxy.ansible.com was created for this purpose: Has a common space to upload your own roles and to find another interesting pre-cooked ones. How do we prepare the containers to provision them 1. We Start our host to get its IP. This is done when creating the container. When it is fully created, we automatically start the container. When It is started, through lxc-info with the params -i (what returns IP) and -H (to not humanize it). 2. Add our host to the Ansible Inventory (recognized Ansible Hosts). When we have the IP, is time to go to ansible/hosts file, and insert it under the [huaca_CONTAINER] where it belongs. 3. Configuring a secure access. This can be done in two different ways. By coping the secure key to the destiny host, or by adding the keys to the Ansible Vault. 40
OpenHuaca Cloud Platform •SSH The way forward is to copy our secure key to the new host. The certificates will be generated with OpenHuaca, what calls to ssh-keygen -t rsa Now we copy the generated key to the host (with its IP address): ssh-copy-id [email protected] We defined this process in “3.3.7. Secure Access” section. If ssh-credentials does not work properly, is needed to add our credentials manually: •Ansible Vault “Vault” is a feature of Ansible that allows keeping sensitive data such as passwords or keys in encrypted files, rather than as plain text in your playbooks or roles. The Ansible Vault can keep our passwords secured.[23] To encrypt a string provided by the user, ansible-vault encrypt_string --vault-id a_password_file 'foobar' --name 'the_secret' To use a vault where there is the password stored, ansible-playbook --vault-id /path/to/my/vault-password-file site.yml For example, to use a password file dev-password for the vault-id ‘dev’: ansible-playbook --vault-id dev@dev-password site.yml 4. Ensure python is installed on the host. Now, on the first early connection to the new container, is important to remember to install python on it. Python is required to provision through Ansible. It can be also done without direct connection to the container. 41
OpenHuaca Cloud Platform Appendix Ansible Guide of use, for OpenHuaca 1. Installation Ubuntu builds are available in a PPA at this link. We always recommend to use the last Ansible version available because of the different security patches that this one receives periodically. To configure the PPA on your machine and install Ansible you have to run the following commands: sudo apt-get update sudo apt-get install software-properties-common sudo apt-add-repository ppa:ansible/ansible sudo apt-get update sudo apt-get install ansible Useful: How to Connect via SSH to a LXC container: ssh [email protected] To connect via OpenHuaca to one of our containers, it is done as follows, 2. About the virtual machines Firstly is important to be sure your destination environments had Python installed. As Ansible is build with it, we need python 3.X installed at all our servers/hosts. If it is not installed, a connection error will appear during the provisioning attempts. It is also important to secure our hosts and connections properly. 48 “ openhuaca console - n CONTAINER - d DOMAIN ”
OpenHuaca Cloud Platform 3. Basic SSH Keys usage •Ansible uses by default a SFTP (Secure File Transfer Protocol). It is available in Ubuntu but if is used in another OS where not, this protocol can be changed for SCP in the configuration file (ansible.cfg) •We can connect to our container via SSH, as we can connect directly as Root. SSH Configuration We can configure the destination hosts to allow or deny some features of the ssh service. Inside the destination container, edit /etc/ssh/sshd_config, and comment out the following line to disable the password authentication for root: #PermitRootLogin without-password Just below it, add the following one to allow root login only with public key authentication: PermitRootLogin yes The PermitRootLogin arguments are yes, no, without-password and force-commands-only. If this last one is set, root login with public key authentication will be allowed, but only if the command option has been specified. Then restart SSH: service ssh restart We should remember to assign a new root password before, by: ~# passwd •To connect to our container without password, adding the RSA key: To create a new key: ssh-keygen -t rsa Now, to copy our new key to the destination machine, when this one is an LXC container: ssh-copy-id [email protected] 49
OpenHuaca Cloud Platform If we are experimenting any problem while connecting to provision the hosts, some configurations can be modified on the Ansible configuration file /etc/ansible/ansible.cfg : Temporal solution for this problem message: “Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host.” This can be solved by adding this to /etc/ansible/ansible.cfg [defaults] host_key_checking = false 4. Inventory Located at /etc/ansible/hosts file, stores the different ips of the permited hosts we are going to orchestrate. Different hosts files can be used and called through Ansible CLI if we want to, but the Ansible documentation recommends to use the defined in its root directory. Anyway, can be interesting for us to build our own directories to have complete control of them. Lets see how an inventory file looks like: mail.example.com [webservers] foo.example.com ansible_connection=ssh ansible_user=username ... bar.example.com [dbservers] one.example.com two.example.com three.example.com Also we can use regex syntax like [01:50] to index 50 different servers like www[01:50].example.com , and the alphanumerics are accepted too. 50
OpenHuaca Cloud Platform There’s a way to use variables in your inventory, as follows: [atlanta] host1 host2 [atlanta:vars] ntp_server=ntp.atlanta.example.com proxy=proxy.atlanta.example.com When on a playbook we are referencing to certain groups, we can use also the default groups, which always exist: all and ungrouped Ad-hoc commands/tasks (declarative): These are single-use commands which call modules or easy instructions, for testing or practicing, or to complete specific tasks: ansible 10.0.3.30 -m ping --ask-pass 5. Playbooks Playbooks are the way we keep a list of tasks to be executed later in a group of containers. In fact, we can directly affect to a specific container, all of them or differentiate the containers in different groups (what is directly done in OpenHuaca with “domains”). The Ansible playbooks are writed in YAML (.yml) language, what is a fancy and easy to understood lenguage by everyone. BASICS The next one is an easier to read playbook, just to start understanding how it is built. This playbook will affect all containers (hosts) we configured on the inventory. Remember that OpenHuaca does it automatically on the creation of your virtual machines. Every play has a sort of tasks. Tasks are executed in order, one at a time. It is important to understand that, within a play, all hosts are going to get the same task directives. It is the purpose of a play to map a selection of hosts to tasks. 51
OpenHuaca Cloud Platform apt, shell, yum or template are different used modules in the following playbooks: --- - hosts: all tasks: - name: Install vim apt: name=vim state=present - name: Hang shell: echo ’Hola’ is ‘hello’ in spanish … Under tasks: there are inserted the different modules in different lines. The - name describes the task, and this name will be printed as an output help. In this another playbook, there is one play. Plays group an amount of task instructions wich point to a specific group or hosts. Plays, like tasks, run in the order specified in the playbook: from top to bottom. --- - hosts: webservers remote_user: root vars: http_port: 80 max_cliets: 200 tasks: - name: Ensure Apache is at the latest version yum: name: httpd state: latest remote_user: ubuntu - name: Write apache config file template: src: /srv/httpd.j2 dest: /etc/httpd.conf notify: - restart apache - name: Ensure apache is running (and enable it at boot) service: name: httpd state: started enabled: yes handlers: - name: restart apache service: name: httpd state: restarted ... 52
OpenHuaca Cloud Platform USERS AND PRIVILEGE ESCALATION You can see we can execute different tasks by different remote users. Our last play was executed by root, but the task “Ensure Apache is at the latest version” was executed on the remote system by the user ubuntu. You can login as a normal user (your_user), and then become a root or just another one. This is known as privilege escalation. The way to activate privilege escalation is to set become: yes on the host level. You can also use become in a particular task instead of the whole play. The directive become_user is set as root by default. The parameters and variables can be assigned for a group of hosts at the same time or these can be saved in the same inventory directory level, in different files those Ansible will use by default. HANDLERS Handlers are just executed once, independently of how many calls has a playbook to these handlers. At the end of the Task “Write apache config file” the handler ‘restart apache’ will be executed. tasks: - name: Write apache config file template: src: /srv/httpd.j2 dest: /etc/httpd.conf notify: - restart apache - name: Ensure apache is running (and enable it at boot) service: name: httpd state: started enabled: yes handlers: - name: restart apache service: name: httpd state: restarted ... 53
OpenHuaca Cloud Platform Handlers also can be controlled by calling them through listen attribute on every handler, as shown here: tasks: - name: Ensure apache is running (and enable it at boot) service: name=httpd state=started enabled=yes notify: “restart apache server” handlers: - name: restart apache listen: “restart apache server” service: name=httpd state=restarted - name: run command listen: “restart apache server” shell: ifconfig ... VARIABLES Variables are also helpful. While automation makes it easier on the creation of repeated tasks, our systems will need to set some behaviors or configurations slightly different from each others. Variables can be used in playbooks as imports or direct declarations, but for more complex situations Jinja2 templating system is great to use. For example as variable substitution, My amp goes to {{ max_amp_value }} This can be used in any place inside a play, as with includes bellow. INCLUDES AND IMPORTS ansible-playbook.yml --- - hosts: all remote_user: root tasks: - include: apache-playbook.yml param={{ item }} with_items: - 1 - 2 - 3 handlers: - include: apache-handlers.yml ... 54
OpenHuaca Cloud Platform apache-playbook.yml --- - name: Ensure Apache is instaled at the latest version apt: name=apache2 state=latest notify: - restart apache with_items: - 1 - 2 - 3 handlers: - include: apache-handlers.yml ... The last one was an example of how includes are implemented to literally call another YAML file that will run in the called order. There exist imports also. Includes and imports statements are very similar. Are used to include or import tasks files or variables. tasks: - import_tasks: common_tasks.yml vars: wp_user: timmy # or - include_tasks: common_tasks.yml vars: wp_user: timmy There exist some technical differentiations, but on essence are the same. 6. Modules Modules are discrete units of code that can be used from the command line or in a playbook task, and are used to interact with different components and programs on the hosts. These are also idempotents. This means that several executions of the same module emit the same output. We are going to pay attention to some of the ones those seems more interesting for us: apt Manages apt packages (such as for Debian/Ubuntu). https://docs.ansible.com/ansible/latest/modules/apt_module.html#apt-module 55
OpenHuaca Cloud Platform service Controls services on remote hosts. Can also control services in Windows OS with win_service. https://docs.ansible.com/ansible/latest/modules/service_module.html#service-module command The command module takes the command name followed by a list of spacedelimited arguments. For Windows targets, use the win_command https://docs.ansible.com/ansible/latest/modules/command_module.html#command-module shell It also execute commands in nodes. shell: ifconfig https://docs.ansible.com/ansible/latest/modules/shell_module.html#shell-module group/user Manage user accounts. user: name=dani group=admin create_home=yes https://docs.ansible.com/ansible/latest/modules/user_module.html#user-module stat Retrieve file or file system status. https://docs.ansible.com/ansible/latest/modules/stat_module.html#stat-module copy Copies files to remote locations. copy: src=origin.txt dest=/tmp/desty.txt https://docs.ansible.com/ansible/latest/modules/copy_module.html#copy-module fetch Fetches (download) a file from remote nodes. fetch: src=/ dest=/tmp/file.txt https://docs.ansible.com/ansible/latest/modules/fetch_module.html#fetch-module file Sets attributes of files. file: dest=/tmp/test (creates a path) file: dest=/tmp/fileTest.txt state=touch (to create a file) file: dest=/tmp/fileTest.txt state=absent (to delete a file) https://docs.ansible.com/ansible/latest/modules/file_module.html#file-module cron Manage cron.d and crontab entries. https://docs.ansible.com/ansible/latest/modules/cron_module.html#cron-module template Templates a file out to a remote server. template: src=template.j2 dest=/etc/file.conf https://docs.ansible.com/ansible/latest/modules/template_module.html#template-module 56
OpenHuaca Cloud Platform The complete collection of modules, as its functionality and arguments are in the official Ansible documentation. How a Role is built Ansible will search for roles on the roles/ directory, relative to the playbook file. We locate it at the level of group_vars and host_vars directories. To get well structured roles, this is the working tree we are using in OpenHuaca: site.yml webservers.yml fooservers.yml roles/ common/ tasks/ handlers/ files/ templates/ vars/ defaults/ meta/ webservers/ tasks/ defaults/ meta/ The original way to use a role is via roles: option inside a play. --- - hosts: webservers roles: - common - webservers Since Ansible 2.4, it is possible to import_role or include_role in-line with another tasks, 57 tasks - Contains the main list of tasks to be executed by the role. handlers - Contains handlers, which may be used by this role or even anywhere outside this role. defaults - Default variables for the role can be placed in defaults/main.yml vars - Other variables for the role files - Contains files which can be deployed via this role. Those can be controllers, nodes, config files ... templates - Contains templates which can be deployed via this role. meta - Defines some meta data for this role. It’s used mainly to add role dependencies in meta/main.yml
OpenHuaca Cloud Platform 2. Directories 'inifile': '/etc/openhuaca/openhuaca.ini', 'domain': 'openhuaca', 'H_CONF_DIR': '/etc/huaca', 'H_CONTAINERS_DIR': '/var/lib/huaca', 'H_BASES_DIR': '/zfspool1/huaca/', 'H_LOGFILE': '/var/log/huaca.log', 'H_DOMAIN_AVAILABLE_DIR': '/etc/huaca/domain-available', 'H_DOMAIN_ENABLED_DIR': '/etc/huaca/domain-enabled', 'H_ANSIBLE_INVENTORY': '/etc/ansible/hosts', 'H_DNSMASQ_DIR': '/etc/dnsmasq.d/', 'H_DNSMASQ_CONF': '/etc/dnsmasq.conf', 'H_RUN_DIR': '/run/huaca', 'H_LIB_DIR': '/var/lib', 'H_NET': '172.20.0.0', 'H_lstmp': '/tmp/huaca_ls.tmp', 'H_CA_DIR': '/etc/huaca/certification/CAs', 'H_CERT_DIR': '/etc/huaca/certification/certs', 'LOCKFILE': '/var/lock/huaca_iptables.lock', 'PUBLIC_IP': '147.83.39.231', 'COMMAND_PIPE': '/var/tmp/huaca_nat_cmd', 'HOSTUP': '/usr/local/bin/HUACA_hostconf_up', 'HOSTDOWN': '/usr/local/bin/HUACA_hostconf_down' Installation path of the main code: /usr/local/bin/ LOCAL LOG ABOUT THE AUTHENTICATIONS: /var/log/auth.log 64
OpenHuaca Cloud Platform Glossary VM – Virtual Machine (VMs to refer to the plural form) SVM – System Virtual Machine VMM – Virtual Machine Monitor, also known as “hypervisor” LXC – LinuX Containers KVM – Kernel-based Virtual Machine DHCP – Dynamic Host Configuration Protocol DNS – Domain Name Server RSA – Rivest–Shamir–Adleman (is one of the first public-key cryptosystems) SSH – Secure Shell CA – Certification Authority CLI – Command line interface NIC – Network Interface Card MVP – Minimum Viable Product XaaS – Everything as a service, also ‘EaaS’ Table 2: Glossary 65