CMDBuild V2.4.1 Manual de instalación
1
Installing cmdbuild on Ubuntu 16.04 LTS Install ubuntu on your platform. Requerimientos • • • •
Procesador 1Ghz (64 bits) 8 Gb RAM 400 Gb disco Conexión a internet 1
-Descargamos el ISO desde el URL de Ubuntu, muy recomendado usar la via torrent (mas rápida y no recargamos un único servidor) y generamos un DVD / USB booteable
-Hacemos boot de nuestro servidor y escogemos el idioma en que instalaremos, en este caso, English presionando Enter
-Entramos a instalar por la primera opción Instalar Ubuntu Server presionando Enter
-Escogemos nuestra ubicación y presionamos Enter
2
-Se nos pide confirmar si auto detecta la distribución del teclado, respondemos No y presionamos Enter
-Confirmamos nuestro distribución de teclado, en mi caso, Spanish (Latin American) y presionamos Enter
3
-Volvemos a confirmar nuestra distribución de teclado y presionamos Enter
-El instalador carga algunos drivers
-Escribimos el hostname de nuestro servidor de la forma host (nombre) dominio (dominio internet) y presionamos Enter sobre el botón Continuar
4
-Creamos una cuenta de usuario para administrar nuestro servidor. Escribimos el nombre del encargado y presionamos Enter sobre el botón Continuar
-Escribimos el nombre de usuario con el que se logeara y presionamos Enter sobre el botón Continuar
-Escribimos la contraseña a usar (un nuevo detalle en esta versión, se puede activar la opción Show Password in Clear para ver lo que escribimos). Presionamos Enter sobre el botón Continuar
5
-Confirmamos la contraseña. Presionamos Enter sobre el botón Continuar
-Quieres cifrar tu carpeta de usuario? Elegimos la opción y presionamos Enter sobre el botón Continuar
-El sistema auto detecta nuestra ubicación y sugiere la zona horaria, si es la correcta, elegimos Si y presionamos Enter sobre el botón Continuar
6
-Tiempo para particionar el disco. Elegimos la segunda opción, Guiado con LVM y presionamos Enter
-Nos mostraran discos detectados en el equipo, escogemos cual se usar y presionamos Enter
-Este el disco donde instalaremos? Presionamos Enter sobre Si
-Usaremos todo el espacio del disco. Presionamos Enter sobre el botón Continuar
7
-Ultima oportunidad para arrepentirnos. Respondemos Si para escribir cambios y formatear presionando Enter
-Comienza la instalación base
8
-Usas un proxy para salir a internet? Escribela en la caja de texto (no usas proxy, dejalo en blanco). Presionamos Enter en el botón Continuar
-Escogemos la primera opción, Sin actualizaciones automáticas y presionamos Enter
-Hora de escoger que paquetes instalar, para un modo minimal elegimos Standard system utilities y OpenSSH server. Presionamos Enter sobre el botón Continuar
9
-Se instalan los paquetes, hora de ir por un café ;-)
-Instalaremos Grub en el sector de arranque del disco. Respondemos Si presionando Enter
-Ya finalizamos la instalación de Linux Ubuntu server Xenial Xerus. Reiniciamos el equipo y retiramos el DVD / USB booteable desde la que instalamos
10
-Ingresamos con la cuenta creada en pasos anteriores y primer paso, actualizar nuestro OS con los comandos sudo apt-get update sudo apt-get dist-upgrade
Ya tenemos listo nuestro servidor Linux Ubuntu server LTS X enial Xerus 16.04.
Install Java by running: First, add Oracle's PPA, then update your package repository. • •
sudo add- apt-repository ppa :webupd8team/java sudo apt-get update
In addition to configuring proxies, tell sudo to preserve the environment with the -E option: export http_proxy=http://
: export https_proxy=http://: sudo -E add-apt-repository ppa:webupd8team/java with username and password:
11
export https_proxy=https://:@: Then, depending on the version you want to install, execute one of the following commands:
Oracle JDK 8 This is the latest stable version of Java at time of writing, and the recommended version to install. You can do so using the following command: •
sudo apt -get ins tall or acle-java8-installer
Setting the JAVA_HOME Environment Variable Many programs, such as Java servers, use the JAVA_HOME environment variable to determine the Java installation location. To set this environment variable, we will first need to find out where Java is installed. You can do this by executing the same command as in the previous section: •
sudo update-alternatives --config java
Copy the path from your preferred installation and then open /etc/environment using nano or your favorite text editor. •
sudo nano /etc/environment
At the end of this file, add the following line, making sure to replace the highlighted path with your own copied path. /etc/environment JAVA_HOME=" /usr/lib/jvm/java-8-oracle "
Save and exit the file, and reload it. •
source / etc/environment
You can now test whether the environment variable has been set by executing the following command: •
echo $JAVA_HOME
This will return the path you just set.
Install PostgreSQL by running: • •
su do a pt-ge t uinst pdatall e postgresql postgresql-contrib sudo aptget
Switch over to the postgres account on your server by typing: •
sudo - i - u p ostgres
You can now access a Postgres prompt immediately by typing: 12
•
psql
You will be logged in and able to interact with the database management system right away. Exit out of the PostgreSQL prompt by typing: •
\q
If you are logged in as the postgres account, you can create a new user by typing: •
createuser -- interactive
If, instead, you prefer to use sudo for each command without switching from your normal account, you can type: •
sudo -u postgres createuser --interactive
The script will prompt you with some choices and, based on your responses, execute the correct Output Postgres commands to create a user to your specifications. Enter name of role to add: cmdbuild Shall the new role be a superuser? (y/n) y
Managing users and rights To manage users, you first have to edit/etc/postgresql/current/main/pg_hba.conf and modify the default configuration which is very locked down and secure. For example, if you want postgres to manage its own users (not linked with system users), you will add the following line: 8<------------------------------------------# TYPE DATABASE USER IP-ADDRESS IP-MASK METHOD host all all 10.0.0.0 255.255.255.0 md5 8<------------------------------------------Which means that on your local network (10.0.0.0/24 - replace with your own local network !), postgres users can connect through the network to the database providing a classical couple user / password. Besides allowing a user to connect over the network to the to a database on the server, you must enable PostgreSQL to listen across different networks. To do that, open up/etc/postgresql/current/main/ postgresql.conf in your favourite editor and alter thelisten_addresses as below: listen_addresses = '*'
Restarting the server After configuring the networking / users you may need to reload the server, here is a suggested command to do so. sudo /etc/init.d/postgresql reload Some settings changes inpostgresql.conf require a full restart, which will terminate active connections and abort uncommitted transactions:
sudo /etc/init.d/postgresql restart
For security purposes, Tomcat should be run as an unprivileged user (i.e. not root). We will create a new user and group that will run the Tomcat service. First, create a new tomcat group: •
sudo g roupadd t omcat
Next, create a new tomcat user. We'll make this user a member of the tomcat group, with a home directory of /opt/tomcat (where we will install Tomcat), and with a shell of /bin/ false (so nobody can log into the account): 13
•
sudo useradd -s /bin/false -g tomcat -d /opt/tomcat-latest tomcat
Now that our tomcat user is set up, let's download and install Tomcat.
Install Tomcat by running: The best way to install Tomcat 8 is to download the latest binary release then configure it manually. Find the latest version of Tomcat 8 at the Tomcat Downloads page. At the time of writing, the latest version is 8.0.35, but you should use a later stable version if it is available. Under the Binary Distributions section, then under the Core list, copy the link to the "tar.gz". Next, change to the directorytarball, on your server. a good directory to download ephemeral items, like/tmp the Tomcat which we This won'tisneed after extracting the Tomcat contents: •
cd /tmp
Use curl to download the link that you copied from the Tomcat website: •
curl -O http://www-us.apache.org/dist/tomcat/tomcat-8/v8.0.35/bin/ apache-tomcat-8.0.35.tar.gz
We will install Tomcat to the /opt/tomcat directory. Create the directory, then extract the archive to it with these commands: • •
sudo mkdir /opt/tomcat sudo t ar xzv f apac he-tomcat-8*tar.gz -C /o pt/tomcat --st rip-components=1
Next, we can set up the proper user permissions for our installation. Add tomcat user and group:
ln -s /opt/apache-tomcat-8.0.35 /opt/tomcat-latest chown -hR tomcat: /opt/tomcat-latest /opt/apache-tomcat-8.5.4 Before starting Tomcat, configure CATALINA_HOME environment variable in your system using following commands. # echo "export CATALINA_HOME=\"apache-tomcat-8.5.4\"" >> ~/.bashrc # source ~/.bashrc
If you need to start, sto p or restart Tomcat you can use the following commands: systemctl start tomcat systemctl stop tomcat systemctl restart tomcat The tomcat user that we set up needs to have access to the Tomcat installation. We'll set that up now. Change toopthe • cd / t/tdirectory omcat where we unpacked the Tomcat installation: Give the tomcat user write access to the conf directory, and read access to the files in that directory: • •
sudo chgrp -R tomcat conf sudo chmod g+rwx conf 14
•
sudo chmod g+r conf/*
Make the tomcat user the owner of the webapps, work, temp, and logs directories: •
sudo cho wn -R t omcat we bapps/ w ork/ te mp/ l ogs/ bi n/
Now that the proper permissions are set up, we can create a systemd service file to manage the Tomcat process. We want to be able to run Tomcat as a service, so we will set up systemd service file. Tomcat needs to know where Java is installed. This path is commonly referred to as "JAVA_HOME". With this piece of information, we can create the systemd service file. Open a file called tomcat.service in the /etc/systemd/system directory by typing: •
sudo nano /et c/systemd/system/tomcat.service
Paste the following contents into your service file. Modify the value of JAVA_HOME if necessary to match the value you found on your system. You may also want to modify the memory allocation settings that are specified in CATALINA_OPTS: /etc/systemd/system/tomcat.service [Unit] Description=Apache Tomcat Web Application Container After=network.target
[Service] Type=forking Environment=JAVA_HOME= /usr/lib/jvm/oracle-java-8 /jre Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid Environment=CATALINA_HOME=/opt/tomcat Environment=CATALINA_BASE=/opt/tomcat Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC' Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/ dev/./urandom' ExecStart=/opt/tomcat/bin/startup.sh ExecStop=/opt/tomcat/bin/shutdown.sh User=tomcat Group=tomcat RestartSec=10 Restart=always [Install] WantedBy=multi-user.target
When you are finished, save and close the file. Next, reload the systemd daemon so that it knows about our service file: •
sudo systemctl daemon-reload
Start the Tomcat service by typing: •
sudo systemctl start tomcat
Double check that it started without errors by typing: 15
•
sudo systemctl status tomcat
Install CMDBuild running Download and extract the cmdbuild to a folder, and move the <>/extras/ tomcat-libs/x.y/* to the /opt/tomcat/lib folder, where x.y is the tomcat version being used. Rename the “cmdbuild.x.y.z.war” to just “cmdbuild.war” Start Tomcat Go to http://localhost:8080/cmdbuild once the page is loaded and the WAR file is deployed. You should see the following settings page:
Enter in the following parameters for the database settings, tailoring when you like (especially for the CMDBuild database).
16
Then you will be prompted to log in with the username “admin” and password “admin” for the demo distribution.
17
2
Cómo instalar Ubuntu 16.04 LTS en tu PC paso a paso Cómo instalar Ubuntu 16.04 LTS. En Abril se lanzó oficialmente Ubuntu 16.04 Xenial Xerus, la nueva versión con soporte extendido del sistema operativo más popular basado en el núcleo Linux. Pese a que el proceso de instalación de Ubuntu es muy sencillo, hemos elaborado este tutorial para ayudar a los usuarios menos experimentados a instalar el nuevo sistema operativo de Canonical. Ubuntu 16.04 viene cargado de novedades
siendo los paquetes Snap una de las más llamativas.
18
Cómo Instalar Ubuntu 16.04 LTS paso a paso En primer lugar vamos a fijarnos en los requisitos mínimos que debe cumplir nuestro ordenador para poder ejecutar Ubuntu 16.04 de forma correcta, no son especialmente altos y prácticamente cualquier ordenador con 10 años o menos va a ser apto. Requisitos mínimos: 1 Procesador Dual Core. 2 2GB de memoria RAM. 3 16GB de disco duro. 4 Acceso a internet. 5 Pendrive de 2 GB o más que usaremos como medio de instalación.
Preparación del pendrive El siguiente paso es descargar una imagen ISO de Ubuntu 16.04 LTS, puedes hacerlo desde los siguientes enlaces. Recuerda elegir la versión de 32 bits o 64 bits según las características de tu procesador, si no estas seguro elige la de 32 bits. Ubuntu 16.04 LTS 32 bits y para Ubuntu 16.04 LTS 64 bits. A continuación vamos a preparar un pendrive para instalar nuestro sistema Ubuntu 16.04, lo que haremos será usar la aplicación YUMI para generar un medio de instalación en nuestro pendrive con una capacidad de al menos 2 GB. En primer lugar necesitamos descargar la herramienta YUMI para preparar nuestro Pendrive, una vez más se trata de una aplicación gratuita y descargarla es tan fácil como dirigirnos a su página web. Una vez dentro de la página web debemos descender hasta encontrar la opción para descargar la última versión de YUMI y hacemos click.
Descargamos la aplicación y la abrimos, nos aparecerá la siguiente ventana en la cual debemos aceptar el acuerdo de licencia para poder usarla. No tenemos más que hacer click en “I agree”
19
Aceptamos el acuerdo de licencia y nos aparece la siguiente ventana en la cual debemos seleccionar nuestro Pendrive, la distribución a instalar desde el menú desplegable y por último buscamos nuestra imagen ISO en nuestro sistema y hacemos click en “Create”. También nos ofrece la opción de marcar la opción para formatear nuestro Pendrive si no lo hemos hecho previamente.
20
Nos aparece un mensaje advirtiéndonos que se borrará toda la información en nuestro Pendrive, comprobamos una vez más que no hay nada valioso en él y aceptamos.
21
Esperamos a que acabe el proceso de copia de archivos al Pendrive y hacemos click en “Next”
22
Nos preguntará si queremos añadir más distribuciones a nuestro Pendrive, si no vamos a añadir nada más le decimos que no y se acaba el proceso, en este caso vamos a añadir una segunda distribución por lo que le decimos que sí.
Instalando Ubuntu 16.04 LTS en nuestro PC Una vez que tenemos listo nuestro pendrive para instalar Ubuntu 16.04 LTS en nuestro ordenador tan solo nos queda reiniciar el PC con el pendrive conectado y usar el pendrive como medio de inicio, para esto tendrás que configurar el orden de preferencia de arranque desde la BIOS. Para seleccionar el medio de arranque solo hay que pulsar F12 repetidamente al encender nuestro ordenador y nos aparecerá el menú de selección de medio donde elegiremos nuestro pendrive. Este proceso instala Ubuntu 16.04 en tu disco duro, si no estás seguro puedes empezar probando Ubuntu sobre una maquina virtual antes de hacer cambios en el disco duro de tu PC.
23
La instalación comienza con una pantalla de bienvenida que a su vez hace la función de asistente de instalación en el que debemos seleccionar elidioma a usar y pulsar en “instalar Ubuntu”. Su instalación ha sido bastante rápida, nos ha llevado un total de 9 minutos.
En la siguiente pantalla nos da la opción de descargar las actualizaciones e instalar software de terceros para reproducir archivos multimedia y otros. Es recomendable marcar ambas opciones para que nuestro sistema Ubuntu esté a la última y podemos reproducir todo nuestro contenido multimedia nada más que se acabe de instalar. No obstante ninguno de los dos es obligatorio y podemos hacerlo una vez que el sistema ya esté instalado.
24
A continuación nos saldrá el asistente del particionado del disco duro, en este caso vamos a usar todo el disco por lo que dejamos la opción por defecto y pulsamos en “instalar ahora“. Desde aquí podemos hacer un particionado avanzado de nuestro disco duro para una mejor organización. También podremos instalar Ubuntu junto a otros sistemas operativos como Windows.
25
Debemos aceptar el mensaje de confirmación, pulsamos en “ continuar“. Hasta que no aceptemos este mensaje no se hará ningún cambio en nuestro disco duro por lo que es mejor que nos aseguremos de que hemos hecho todo como queremos antes de aplicar los cambios. En caso de realizar particiones a mano, os recomendamos la siguiente configuración de particiones: 1 /boot (150 megas). 2 /(10 GB) 3 Memoria SWAP (2GB si tu equipo tienes 4GB, en caso de tener menos deberás multiplicar por dos la cantidad que tienes. Por ejemplo, 512 MB serían 1 GB de memoria RAM). 4 /home (el resto del disco duro). Aquí es donde guardarás todos tus datos personales. ¿Por qué esperamos la partición /home? Si te gusta probar muchas distribuciones linux, no te obliga hacer copias de seguridad cada vez que reinstalas y simplemente deberás instalar el nuevo sistema operativo con las particiones: boot y /. Además de mantener la memoria SWAP. En nuestro caso hemos elegido la opción fácil qué es “Borrar disco e instalar ubuntu”.
26
Seleccionamos nuestra zona horaria y pulsamos en “continuar”
27
Elegimos nuestra distribución del teclado y “continuar“. Existe un espacio para que podamos escribir y comprobar que hemos elegido la opción correcta. Ya nos queda poco para terminar este tutorial de como instalar ubuntu paso a paso.
28
Luego nos saldrá una última pantalla en la que deberemos poner nuestro nombre de usuario y contraseña. También podemos seleccionar la opción de inicio de sesión automático e incluso cifrar nuestra carpeta personal para una mayor seguridad.
29
Finalmente reiniciamos nuestro sistema, arrancamos desde el disco duro y ya tendremos un Ubuntu 16.04 LTS funcionando en todo su esplendor.
30
31
SECTION 1
Bueno, el proxy… si el proxy… como configurarlo. Depende de que requieres pasar por el Proxy. Empecemos con los básicos, Firefox, Chrome, Chromium, Thunderbird, Pidgin, Evolution, Banshee, Rhythmbox, etc…, estos clientes tomas la configuración del proxy de las propiedades del sistema en Proxy de la Red. Y solo es necesario colocar los datos de nuestro proxy.
Para las aplicaciones de terminal, como wget, winetrics, add-apt-repository, etc… se requiere que la configuración del proxy este en las variables de ambiente. Es necesario abrir una terminal para realizar las siguientes configuraciones. $ export http_proxy=http://usuario:contraseñ[email protected]:puerto/ $ export https_proxy=https://usuario:contraseñ[email protected]:puerto/
Si el proxy no tiene contraseña se puede omitir la parte de usuario:contraseña@, y debe ser algo como: $ export http_proxy=http://proxy.dominio:puerto/ 32
$ export https_proxy=https://proxy.dominio:puerto/
Para el caso especifico de add-apt-repository no funciona si las variables se exportan en la sesión y después se ejecuta el comando con “sudo”, es necesario entrar a root. $ # # #
sudo su export http_proxy=http://usuario:contraseñ[email protected]:puerto/ export https_proxy=https://usuario:contraseñ[email protected]:puerto/ add-apt-repository ppa:identificador
Asiendo uso también de la terminal. Para dejar permanente estas variables sin tenerlas que estar configurando todo el tiempo, modificamos el archivo /etc/environment sudo gedit /etc/environment
Y agrega las siguientes líneas: http_proxy=http://usuario:contraseñ[email protected]:puerto/ https_proxy=https://usuario:contraseñ[email protected]:puerto/
Y por ultimo como utilizar proxy en Ubuntu Software Center, o los asistentes de instalación de paquetes, como instalación de codecs, soporte a idiomas, apt-get, aptitude, etc. Para estos es necesario modificar o crear el archivo si no existe: /etc/apt/apt.conf: $ sudo gedit /etc/apt/apt.conf
Y después agregar las siguientes líneas: Acquire::http::Proxy "http://usuario:contraseñ[email protected]:puerto/"; Acquire::https::Proxy "https://usuario:contraseñ[email protected]:puerto/";
Como mencione al inicio, si no requieres contraseña se puede omitir usuario:contraseña@
33
3
How To Install Java with Apt-Get on Ubuntu 16.04 Introduction Java and the JVM (Java's virtual machine) are widely used and required for many kinds of software. This article will guide you through the process of installing and managing different versions of Java using apt-get.
34
Prerequisites To follow this tutorial, you will need: • One Ubuntu 16.04 server. • A sudo non-root user, which you can set up by following the Ubuntu 16.04 initial server setup guide.
Installing the Default JRE/JDK The easiest option for installing Java is using the version packaged with Ubuntu. Specifically, this will install OpenJDK 8, the latest and recommended version. First, update the package index. •
sudo apt-get update
Next, install Java. Specifically, this command will install the Java Runtime Environment (JRE). •
sudo a pt-get i nstall d efault-jre
There is another default Java installation called the JDK (Java Development Kit). The JDK is usually only needed if you are going to compile Java programs or if the software that will use Java specifically requires it. The JDKofdoes contain the JRE, solarger there file aresize. no disadvantages if you install the JDK instead the JRE, except for the You can install the JDK with the following command: •
sudo a pt-get i nstall d efault-jdk
Installing the Oracle JDK If you want to install the Oracle JDK, which is the official version distributed by Oracle, you will need to follow a few more steps. If you need Java 6 or 7, which are not available in the default Ubuntu 16.04 repositories (not recommended), this installation method is also available. First, add Oracle's PPA, then update your package repository. • •
sud apt pos sudo o addapt-ge t -re upda teitory ppa :webupd8team/java
In addition to configuring proxies, tell sudo to preserve the environment with the -E option: export http_proxy=http://: 35
export https_proxy=http://: sudo -E add-apt-repository ppa:webupd8team/java with username and password: export https_proxy=https://:@: Then, depending on the version you want to install, execute one of the following commands:
Oracle JDK 6 or 7 These are very old versions of Java which reached end of life in February 2013 and April 2015 respectively. It's not recommended to use them, but they might still be required for some programs. To install JDK 6, use the following command: •
sudo apt -get ins tall or acle-java6-installer
To install JDK 7, use the following command: •
sudo apt -get ins tall or acle-java7-installer
Oracle JDK 8 This is the latest stable version of Java at time of writing, and the recommended version to install. You can do so using the following command: •
sudo apt -get ins tall or acle-java8-installer
Oracle JDK 9 This is a developer preview and the general release is scheduled for March 2017. It's not recommended that you use this version because there may still be security issues and bugs. There is more information about Java 9 on the official JDK 9 website. To install JDK 9, use the following command: •
sudo apt -get ins tall or acle-java9-installer
Managing Java There can be multiple Java installations on one server. You can configure which version is the default for use in the command line by using update-alternatives, which manages which symbolic links are used for different commands. •
sudo update-alternatives --config java
36
The output will look something like the following. In this case, this is what the output will look like with all Java versions mentioned above installed. Output There are 5 choices for the alternative java (providing /usr/bin/java).
Selection
Path Priority Status -----------------------------------------------------------* 0 /usr/lib/jvm/java -8-openjdk-amd64/j re/bin/java auto mode /usr/lib/jvm/java -6-oracle/jre/bin/ java 1
1 2 3 4 5
1081
manual mode /usr/lib/jvm/java -7-oracle/jre/bin/ java 2 manual mode /usr/lib/jvm/java -8-openjdk-amd64/j re/bin/java 1081 manual mode /usr/lib/jvm/java -8-oracle/jre/bin/ java 3 manual mode /usr/lib/jvm/java -9-oracle/bin/java 4 manual mode Press to keep the current choice[*], or type selection number:
You can now choose the number to use as a default. This can also be done for other Java commands, such as the compiler ( javac), the documentation generator (javadoc), the JAR signing tool (jarsigner), and more. You can use the following command, filling in the command you want to customize. •
sudo update-alternatives --config command
Setting the JAVA_HOME Environment Variable Many programs, such as Java servers, use the JAVA_HOME environment variable to determine the Java installation location. To set this environment variable, we will first need to find out where Java is installed. You can do this by executing the same command as in the previous section: •
sudo update-alternatives --config java
Copy the path from your preferred installation and then open /etc/environment using nano or your favorite text editor. •
sudo nano /etc/environment
At the end of this file, add the following line, making sure to replace the highlighted path with your own copied path. /etc/environment JAVA_HOME=" /usr/lib/jvm/java-8-oracle "
37
Save and exit the file, and reload it. •
source / etc/environment
You can now test whether the environment variable has been set by executing the following command: •
echo $JAVA_HOME
This will return the path you just set.
Conclusion You have now installed Java and know how to manage different versions of it. You can now install software which runs on Java, such as Tomcat, Jetty, Glassfish, Cassandra, or Jenkins.
38
4
How To Install and Use PostgreSQL on Ubuntu 16.04 Introduction Relational database management systems are a key component of many web sites and applications. They provide a structured way to store, organize, and access information. PostgreSQL, or Postgres, is a relational database management system that provides an implementation of the SQL querying language. It is a popular choice for many small and large projects and has the advantage of being standards-compliant and having many advanced features like reliable transactions and concurrency without read locks.
39
In this guide, we will demonstrate how to install Postgres on an Ubuntu 16.04 VPS instance and go over some basic ways to use it.
Installation Ubuntu's default repositories contain Postgres packages, so we can install these easily using the apt packaging system. Since this is our first time using apt in this session, we need to refresh our local package index. We can then install the Postgres package and a -contrib package that adds some additional utilities and functionality: • •
sudo apt-get update sudo apt-get install postgresql postgresql-contrib
Now ourdatabase software management is installed, we can go you overmay howhave it works and how it may be different from that similar systems used.
Using PostgreSQL Roles and Databases By default, Postgres uses a concept called "roles" to handle in authentication and authorization. These are, in some ways, similar to regular Unix-style accounts, but Postgres does not distinguish between users and groups and instead prefers the more flexible term "role". Upon installation Postgres is set up to use ident authentication, which means that it associates Postgres roles with a matching Unix/Linux system account. If a role exists within Postgres, a Unix/Linux username with the same name will be able to sign in as that role. There are a few ways to utilize this account to access Postgres.
Switching Over to the postgres Account The installation procedure created a user account called postgres that is associated with the default Postgres role. In order to use Postgres, we can log into that account. Switch over to the postgres account on your server by typing: •
sudo - i - u p ostgres
You can now access a Postgres prompt immediately by typing: •
psql
You will be logged in and able to interact with the database management system right away. Exit out of the PostgreSQL prompt by typing: •
\q
You should now be back in the postgres Linux command prompt.
Accessing a Postgres Prompt Without Switching Accounts You can also run the command you'd like with the postgres account directly with sudo. For instance, in the last example, we just wanted to get to a Postgres prompt. We could do this in one step by running the single command psql as the postgres user with sudo like this: • sudo -u postgres psql This will log you directly into Postgres without the intermediary bash shell in between. Again, you can exit the interactive Postgres session by typing: •
\q
40
Create a New Role Currently, we just have the postgres role configured within the database. We can create new roles from the command line with the createrole command. The --interactive flag will prompt you for the necessary values. If you are logged in as the postgres account, you can create a new user by typing: •
createuser -- interactive
If, instead, you prefer to use sudo for each command without switching from your normal account, you can type: •
sudo -u postgres createuser --interactive
The script will prompt you with some choices and, based on your responses, execute the correct Output Postgres commands to create a user to your specifications. Enter name of role to add: sammy Shall the new role be a superuser? (y/n) y
You can get more control by passing some additional flags. Check out the options by looking at the man page: •
man createuser
Create a New Database By default, another assumption that the Postgres authentication system makes is that there will be an database with the same name as the role being used to login, which the role has access to. So if in the last section, we created a user called sammy, that role will attempt to connect to a database which is also called sammy by default. You can create the appropriate database with the createdb command. If you are logged in as the postgres account, you would type something like: •
createdb sammy
If, instead, you prefer to use sudo for each command without switching from your normal account, you would type: •
sudo -u postgres createdb sammy
Open a Postgres Prompt with the New Role To log in with ident based authentication, you'll need a Linux user with the same name as your Postgres role and database. If you don't have a matching Linux user available, you can create one with the adduser command. You will have to do this from an account with sudo privileges (not logged in as the postgres user): •
sudo a dduser sammy
Once you have the appropriate account available, you can either switch over and connect to the database by typing: • •
sudo -i -u sammy psql
Or, you can do this inline: •
sudo -u sammy psql
41
You will be logged in automatically assuming that all of the components have been properly configured. If you want your user to connect to a different database, you can do so by specifying the database like this: •
psql -d postgres
Once logged in, you can get check your current connection information by typing: • \conninfo Output You are connected to database "sammy" as user "sammy" via socket in "/var/ run/postgresql" at port "5432".
This can be useful if you are connecting to non-default databases or with non-default users.
Create and Delete Tables Now that you know how to connect to the PostgreSQL database system, we can to go over how to complete some basic tasks. First, we can create a table to store some data. Let's create a table that describes playground equipment. The basic syntax for this command is something like this: CREATE TABLE table_name ( column_name1 col_type (field_length ) column_constraints , column_name2 col_type (field_length ), column_name3 col_type (field_length ) );
As you can see, we give the table a name, and then define the columns that we want, as well as the column type and the max length of the field data. We can also optionally add table constraints for each column. You can learn more about how to create and manage tables in Postgres here. For our purposes, we're going to create a simple table like this: CREATE TABLE playground ( equip_id serial PRIMARY KEY, type varchar (50) NOT NULL, color varchar (25) NOT NULL, location varchar(25) check (location in ('north', 'south', 'west', 'east', 'northeast', 'southeast', 'southwest', 'northwest')), install_date date );
We have made a playground table that inventories the equipment that we have. This starts with an equipment ID, which is of the serial type. This data type is an auto-incrementing integer. We have given this column the constraint of primary key which means that the values must be unique and not null. For two of our columns ( equip_id and install_date), we have not given a field length. This is because some column types don't require a set length because the length is implied by the type. We then give columns for the equipment type and color, each of which cannot be empty. We create a location column and create a constraint that requires the value to be one of
42
eight possible values. The last column is a date column that records the date that we installed the equipment. We can see our new table by typing: • \d Output List of relations Schema | Name | Type | Owner --------+-------------------------+----------+------public | playground | table | sammy public | playground_equip_id_seq | sequence | sammy (2 rows)
Our playground table is here, but we also have something called playground_equip_id_seq that is of the type sequence. This is a representation of the serial type we gave our equip_id column. This keeps track of the next number in the sequence and is created automatically for columns of this type. If you want to see just the table without the sequence, you can type: • \dt Output List of relations Schema | Name | Type | Owner --------+------------+-------+------public | playground | table | sammy (1 row)
Add, Query, and Delete Data in a Table Now that we have a table, we can insert some data into it. Let's addthe a slide and and a swing. do thisdata by calling thecolumn. table we're wanting add to, naming columns then We providing for each Our slide andtoswing could be added like this: • •
INSERT INTO pla yground (type, color, lo cation, install_date) V ALUES ('slide', 'blue', 'south', '2014-04-28'); INSERT INTO pla yground (type, color, lo cation, install_date) V ALUES ('swing', 'yellow', 'northwest', '2010-08-16');
You should take care when entering the data to avoid a few common hangups. First, keep in mind that the column names should not be quoted, but the column values that you're entering do need quotes. Another thing to keep in mind is that we do not enter a value for the equip_id column. This is because this is auto-generated whenever a new row in the table is created. We can then get back the information we've added by typing: • SELECT * F ROM p layground; Output equip_id | type | color | location | install_date ----------+-------+--------+-----------+-------------1 | slide | blue | south | 2014-04-28 2 | swing | yellow | northwest | 2010-08-16 (2 rows)
43
Here, you can see that our equip_id has been filled in successfully and that all of our other data has been organized correctly. If the slide on the playground breaks and we have to remove it, we can also remove the row from our table by typing: •
DELETE FROM p layground WH ERE ty pe = 'slide';
If we query our table again, we will see our slide is no longer a part of the table: • SELECT * F ROM p layground; Output equip_id | type | color | location | install_date ----------+-------+--------+-----------+-------------2 | swing | yellow | northwest | 2010-08-16 (1 row)
How To Add and Delete Columns from a Table If we want to modify a table after it has been created to add an additional column, we can do that easily. We can add a column to show the last maintenance visit for each piece of equipment by typing: •
ALTER T ABLE p layground AD D last_maint date;
If you view your table information again, you will see the new column has been added (but no data has been entered): • SELECT * F ROM p layground; Output equip_id | type | color | location | install_date | last_maint ----------+-------+--------+-----------+--------------+-----------2 | swing | yellow | northwest | 2010-08-16 | (1 row)
We can delete a column just as easily. If we find that our work crew uses a separate tool to keep track of maintenance history, we can get rid of the column here by typing: •
ALTER TABLE playground DROP last_maint;
How To Update Data in a Table We know how to add records to a table and how to delete them, but we haven't covered how to modify existing entries yet. You can update the values of an existing entry by querying for the record you want and setting the column to the value you wish to use. We can query for the "swing" record (this will match every swing in our table) and change its color to "red". This could be useful if we gave the swing set a paint job: •
UPDATE playground SET color = 'red' WHERE type = 'swing';
We can verify that the operation was successful by querying our data again: • SELECT * F ROM p layground; Output equip_id | type | color | location | install_date ----------+-------+-------+-----------+-------------2 | swing | red | northwest | 2010-08-16 (1 row)
44
As you can see, our slide is now registered as being red.
Managing the Server Managing users and rights To manage users, you first have to edit/etc/postgresql/current/main/pg_hba.conf and modify the default configuration which is very locked down and secure. For example, if you want postgres to manage its own users (not linked with system users), you will add the following line: 8<------------------------------------------# TYPE DATABASE USER IP-ADDRESS IP-MASK METHOD host all all 10.0.0.0 255.255.255.0 md5 8<------------------------------------------Which means that on your local network (10.0.0.0/24 - replace with your own local network !), postgres users can connect through the network to the database providing a classical couple user / password. Besides allowing a user to connect over the network to the to a database on the server, you must enable PostgreSQL to listen across different networks. To do that, open up/etc/postgresql/current/main/ postgresql.conf in your favourite editor and alter thelisten_addresses as below: listen_addresses = '*' to listen on all network interfaces. See the docs forlisten_addresses for other options. To create a database with a user that have full rights on the database, use the following command:
sudo -u postgres createuser -D -A -P myuser sudo -u postgres createdb -O myuser mydb The first command line creates the user with no database creation rights (-D) with no add user rights -A) and 'mydb with will prompt you for entering a password (-P). The second command line create the database 'myuser' as owner. This little example will probably suit most of your needs. For more details, please refer to the corresponding man pages or the online documentation.
restarting the server After configuring the networking / users you may need to reload the server, here is a suggested command to do so. sudo /etc/init.d/postgresql reload Some settings changes inpostgresql.conf require a full restart, which will terminate active connections and abort uncommitted transactions:
sudo /etc/init.d/postgresql restart
Secure Local PostgreSQL Access
PostgreSQL uses peer authentication by default. This means database connections will be granted to local system users that own or have privileges on the database being connected to. Such authentication is useful in cases where a particular system user will be running a local program (e.g. scripts, CGI/FastCGI processes owned by separate users, etc.), but for greater security, you may wish to require passwords to access your databases. Commands in this section should be run as the postgres Linux user unless otherwise specified.
45
Edit the /etc/postgresql/9.5/main/pg_hba.conf file, under the # "local" is for Unix domain socket connections only header: /etc/postgresql/9.5/main/pg_hba.conf # #
# "local" is for Unix domain socket connections only local all all peer
Replace peer with md5 on this line to activate password authentication using an MD5 hash. To enable these changes, we need to restart PostgreSQL. However, we did not grant the postgres user sudo privileges for security reasons. Return to the normal user shell: # # exit # Restart PostgreSQL and switch back to the postgres user: # #
sudo service postgresql restart su - postgres
As postgres, connect to the test database as the examplerole PostgreSQL user: #
psql -U examplerole -W mytestdb
You willtobethe prompted to enter password for theyou examplerole andprivileges given psqlfor shell access database. Whenthe using a database, may checkuser access each of its tables with the \z command.
46
5
How To Install Apache Tomcat 8 on Ubuntu 16.04 Introduction Apache Tomcat is a web server and servlet container that is used to serve Java applications. Tomcat is an open source implementation of the Java Servlet and JavaServer Pages technologies, released by the Apache Software Foundation. This tutorial covers the basic installation and some configuration of the latest release of Tomcat 8 on your Ubuntu 16.04 server.
47
Prerequisites Before you begin with this guide, you should have a non-root user with sudo privileges set up on your server. You can learn how to do this by completing our Ubuntu 16.04 initial server setup guide.
Step 1: Install Java Tomcat requires Java to be installed on the server so that any Java web application code can be executed. We can satisfy that requirement by installing OpenJDK with apt-get. First, update your apt-get package index: • sudo apt-get update Then install the Java Development Kit package with apt-get: •
sudo a pt-get i nstall d efault-jdk
Now that Java is installed, we can create a tomcat user, which will be used to run the Tomcat service. Once you have verified if Java is installed or not, choose the type of Java installation that you want with one the following: sudo apt-get install openjdk-8-jre sudo apt-get install openjdk-8-jdk Another alternative Java install is with Oracle JRE and JDK. However, we would need to install additional repositories for a proper installation: sudo apt-get install python-software-properties sudo add-apt-repository ppa:webupd8team/java Then, you will need to fully update the system with the following command and install it: sudo apt-get update sudo apt-get install oracle-java8-installer Verify Installed Java Version. java -version Result: java version "1.8.0_74" Java(TM) SE Runtime Environment (build 1.8.0_74-b02) Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode) Setup JAVA_HOME on Ubuntu 16.0 4.
48
Since many programs now days need a JAVA_HOME environment variable to work properly. We will need to find the appropriate path to make these changes. With the following command, you can view your installs and their path: sudo update-alternatives --config java sudo nano /etc/profile Now that you are in the user profile file, add the following code, along with the Path of your installation from the previous step, to the bottom. ( Example: JAVA_HOME=”YOUR_PATH”): export JAVA_HOME="/usr/lib/jvm/java-oracle-jdk" Reload the file so all your changes could take effect with the following command: source /etc/profile Verify that your implementations are correct with the following command: echo $JAVA_HOME
Step 2: Create Tomcat User For security purposes, Tomcat should be run as an unprivileged user (i.e. not root). We will create a new user and group that will run the Tomcat service. First, create a new tomcat group: •
sudo g roupadd t omcat
Next, create a new tomcat user. We'll make this user a member of the tomcat group, with a home directory of /opt/tomcat (where we will install Tomcat), and with a shell of /bin/ false (so nobody can log into the account): •
sudo useradd -s /bin/false -g tomcat -d /opt/tomcat-latest tomcat
Now that our tomcat user is set up, let's download and install Tomcat.
Step 3: Install Tomcat The best way to install Tomcat 8 is to download the latest binary release then configure it manually. Find the latest version of Tomcat 8 at the Tomcat 8 Downloads page. At the time of writing, the latest version is 8.0.33, but you should use a later stable version if it is available. Under the Binary Distributions section, then under the Core list, copy the link to the "tar.gz". Next, change to the /tmp directory on your server. This is a good directory to download ephemeral items, like the Tomcat tarball, which we won't need after extracting the Tomcat contents: •
cd /tmp
Use curl to download the link that you copied from the Tomcat website: •
curl -O http://www-us.apache.org/dist/tomcat/tomcat-8/v8.5.4/bin/apachetomcat-8.5.4.tar.gz
We will install Tomcat to the /opt/tomcat directory. Create the directory, then extract the archive to it with these commands: 49
• •
sudo mkdir /opt/tomcat sudo t ar xzv f apac he-tomcat-8*tar.gz -C /o pt/tomcat --st rip-components=1
Next, we can set up the proper user permissions for our installation. Add tomcat user and group:
ln -s /opt/apache-tomcat-8.0.35 /opt/tomcat-latest chown -hR tomcat: /opt/tomcat-latest /opt/apache-tomcat-8.5.4 Before starting Tomcat, configure CATALINA_HOME environment variable in your system using following commands. # echo "export CATALINA_HOME=\"apache-tomcat-8.5.4\"" >> ~/.bashrc # source ~/.bashrc
Optional: Install Apache Tomcat Install Tomcat from the Ubuntu repository: apt-get install tomcat8 OpenJDK will be installed as a dependency when you install the tomcat8 package. OpenJDK is included with the default-java meta package in Ubuntu. You may also want to install the tomcat8-docs, tomcat8-examples, and tomcat8-admin tools which provide web-based applications that document, test, and allow you to administer Tomcat. You can install all three with the following command: apt-get install tomcat8-docs tomcat8-examples tomcat8-admin If you need to start, stop or restart Tomcat you can use the following commands: systemctl start tomcat8 systemctl stop tomcat8 systemctl restart tomcat8
Step 4: Update Permissions The tomcat user that we set up needs to have access to the Tomcat installation. We'll set that up now. Change to the directory where we unpacked the Tomcat installation: •
cd /opt/tomcat
Give the tomcat user write access to the conf directory, and read access to the files in that directory: • •
sudo chgrp -R tomcat conf sudo chmod g+rwx conf
50
•
sudo chmod g+r conf/*
Make the tomcat user the owner of the webapps, work, temp, and logs directories: •
sudo cho wn -R t omcat we bapps/ w ork/ te mp/ l ogs/ /b in
Now that the proper permissions are set up, we can create a systemd service file to manage the Tomcat process.
Step 5: Create a systemd Service File We want to be able to run Tomcat as a service, so we will set up systemd service file. Tomcat needs to know where Java is installed. This path is commonly referred to as "JAVA_HOME". The easiest way to look up that location is by running this command: • sudo up date-java-alternatives -l Output java-1.8.0-openjdk-amd64 1081 amd64
/usr/lib/jvm/java-1.8.0-openjdk-
The correct JAVA_HOME variable can be constructed by taking the output from the last column (highlighted in red) and appending /jre to the end. Given the example above, the correct JAVA_HOME for this server would be: JAVA_HOME /usr/lib/jvm/java-1.8.0-openjdk-amd64/jre
Your JAVA_HOME may be different. With this piece of information, we can create the systemd service file. Open a file called tomcat.service in the /etc/systemd/system directory by typing: •
sudo nano /et c/systemd/system/tomcat.service
Paste the following contents into your service file. Modify the value of JAVA_HOME if necessary to match the value you found on your system. You may also want to modify the memory allocation settings that are specified in CATALINA_OPTS: /etc/systemd/system/tomcat.service [Unit] Description=Apache Tomcat Web Application Container After=network.target
[Service] Type=forking Environment=JAVA_HOME= /usr/lib/jvm/java-8-openjdk-amd64 /jre Environment=CATALINA_PID=/opt/tomcat-latest/temp/tomcat.pid Environment=CATALINA_HOME=/opt/tomcat-latest Environment=CATALINA_BASE=/opt/tomcat-latest Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC' Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/ dev/./urandom' ExecStart=/opt/tomcat-latest/bin/startup.sh ExecStop=/opt/tomcat-latest/bin/shutdown.sh User=tomcat Group=tomcat RestartSec=10 51
Restart=always [Install] WantedBy=multi-user.target
When you are finished, save and close the file. Next, reload the systemd daemon so that it knows about our service file: •
sudo systemctl daemon-reload
Start the Tomcat service by typing: •
sudo systemctl start tomcat
Double check that it started without errors by typing: •
sudo systemctl status tomcat
Step 6: Adjust the Firewall and Test the Tomcat Server Now that the Tomcat service is started, we can test to make sure the default page is available. Before we do that, we need to adjust the firewall to allow our requests to get to the service. If you followed the prerequisites, you will have a ufw firewall enabled currently. Tomcat uses port 8080 to accept conventional requests. Allow traffic to that port by typing: •
sudo u fw a llow 8 080
With the firewall modified, you can access the default splash page by going to your domain or IP address followed by :8080 in a web browser: Open in web browser http://server _domain_or_IP :8080
You will see the default Tomcat splash page, in addition to other information. However, if you click the links for the Manager App, for instance, you will be denied access. We can configure that access next. If you were able to successfully accessed Tomcat, now is a good time to enable the service file so that Tomcat automatically starts at boot: •
sudo systemctl enable tomcat
Step 7: Configure Tomcat Web Management Interface In order to use the manager web app that comes with Tomcat, we must add a login to our Tomcat server. We will do this by editing the tomcat-users.xml file: •
sudo nano /o pt/tomcat/conf/tomcat-users.xml
You will want to add a user who can access the manager-gui and admin-gui (web apps that come with Tomcat). You can do so by defining a user, similar to the example below, between the tomcat-users tags. Be sure to change the username and password to something secure: tomcat-users.xml — Admin User 52
Save and close the file when you are finished. To put our changes into effect, restart the Tomcat service: •
sudo systemctl restart tomcat
Step 8: Access the Web Interface Now that we have create a user, we can access the web management interface again in a web browser. Once again, you can get to the correct interface by entering your server's domain name or IP address followed on port 8080 in your browser: Open in web browser http://server _domain_or_IP :8080 The page you see should be the same one you were given when you tested earlier:
Let's take a look at the Manager App, accessible via the link or http://server_domain_or_IP:8080/manager/ html. You will need to enter the account credentials that you added to the tomcatusers.xml file. Afterwards, you should see a page that looks like this:
The Web Manager is used
Application to manage your 53
Java applications. You can Start, Stop, Reload, Deploy, and Undeploy here. You can also run some diagnostics on your apps (i.e. find memory leaks). Lastly, information about your server is available at the very bottom of this page. Now let's take a look at the Host Manager, accessible via the link or http:// server_domain_or_IP:8080/host-manager/html/:
From the Virtual Host Manager page, you can add virtual hosts to serve your applications from.
Conclusion Your installation of Tomcat is complete! Your are now free to deploy your own Java web applications! Currently, your Tomcat installation is functional, but entirely unencrypted. This means that all data, including sensitive items like passwords, are sent in plain text that can be intercepted and read by other parties on the internet. In order to prevent this from happening, it is strongly recommended that you encrypt your connections with SSL.
54
SECTION 1
After installing Tomcat with apt-get on Ubuntu 12.04, Tomcat creates and uses these directories: /etc/tomcat6/ /etc/tomcat6/ !"" Catalina # %"" localhost # !"" ROOT.xml # %"" solr.xml -> ../../../solr/solr-tomcat.xml !"" catalina.properties !"" context.xml !"" logging.properties !"" policy.d # !"" 01system.policy # !"" 02debian.policy # !"" 03catalina.policy # !"" 04webapps.policy # !"" 05solr.policy -> /etc/solr/tomcat.policy # %"" 50local.policy !"" server.xml !"" tomcat-users.xml %"" web.xml
/usr/share/tomcat6 /usr/share/tomcat6 !"" bin # !"" bootstrap.jar
## # # # # # # # !"" !"" %""
!"" !"" !"" !"" !"" !"" !"" !"" %""
catalina.sh catalina-tasks.xml digest.sh setclasspath.sh shutdown.sh startup.sh tomcat-juli.jar -> ../../java/tomcat-juli.jar tool-wrapper.sh version.sh defaults.md5sum defaults.template lib !"" annotations-api.jar -> ../../java/annotations-api-6.0.35.jar !"" catalina-ant.jar -> ../../java/catalina-ant-6.0.35.jar !"" catalina-ha.jar -> ../../java/catalina-ha-6.0.35.jar !"" catalina.jar -> ../../java/catalina-6.0.35.jar !"" catalina-tribes.jar -> ../../java/catalina-tribes-6.0.35.jar !"" commons-dbcp.jar -> ../../java/commons-dbcp.jar commons-pool.jar -> ../../java/commons-pool.jar !"" el-api.jar -> ../../java/el-api-2.1.jar !"" jasper-el.jar -> ../../java/jasper-el-6.0.35.jar !"" jasper.jar -> ../../java/jasper-6.0.35.jar !"" jasper-jdt.jar -> ../../java/ecj.jar !"" jsp-api.jar -> ../../java/jsp-api-2.1.jar !"" servlet-api.jar -> ../../java/servlet-api-2.5.jar "" to mcat-co ote. ar -> ../../ ava/tomcat-co ote-6.0.35. ar 55
If you install Tomcat 7 using apt: sudo apt-get install tomcat7
Then the webapps are located in /var/lib/tomcat7 $ tree /var/lib/tomcat7 -L 2 /var/lib/tomcat7 !"" common # %"" classes !"" conf -> /etc/tomcat7 !"" logs -> ../../log/tomcat7 !"" server # %"" classes !"" shared # %"" classes
#!"" webapps %"" ROOT %"" work -> ../../cache/tomcat7 This is the default Tomcat home page, that can be found on the local file system at: /var/lib/tomcat7/webapps/ROOT/index.html
56
6
Installing Community Edition on Linux Installing additional software for Alfresco The third-party software used by Alfresco is installed when you use the setup wizards to install Alfresco. If you wish to install the third-party software independently, this information describes the steps for obtaining and installing the software. Some of the software can be installed any time before or after installing Alfresco. 1 Installing LibreO!ce In Alfresco, you can transform a document from one format to another, for example, a text file to a PDF file. To have access to these transformation facilities in Alfresco, you must install LibreO!ce. This is optional, and can be done any time after Alfresco is installed. 57
sudo apt-get install libreo!ce 2
Installing ImageMagick To enable image manipulation in Alfresco, you must install and configure ImageMagick. Alfresco uses ImageMagick to manipulate images for previewing.
sudo apt-get install ghostscript imagemagick convert --version 3
Installing Ghostscript Alfresco uses Ghostscript for creating document thumbnails and previews. Use this information to install Ghostscript on your system.
apt-get install ghostscript 4
Installing TinyMCE language packs Translations in Alfresco use the language packs supplied in the default install. The supported language packs are: German (de), English (en), Spanish (es), French (fr), Italian (it), Japanese (ja), and Dutch (nl). The language used switches according to the browser locale. Ensure that your browser is set up to view the relevant locale, which ensures that the special characters display correctly in your installed instance.
58
Installing ImageMagick To enable image manipulation in Alfresco, you must install and configure ImageMagick. Alfresco uses ImageMagick to manipulate images for previewing. 1 Verify that ImageMagick, Ghostscript, and Ghostscript fonts are already installed on your system. Use the ImageMagick convert command to check that you have the right software installed on your machine. This command is usually located in /usr/bin: install Image. 2 If the ImageMagick and Ghostscript software is not available on your system, download and install the appropriate package for your platform. To download ImageMagick, browse to ImageMagick download website. To download Ghostscript, browse toGhostscript download website.
3 4 5 6
Note: In next steps you will make changes to the Alfresco application configuration files to enable the manually installed ImageMagick application. These steps can only be performed after Alfresco has been installed. Browse to the directory. See System paths for more information. Open the alfresco-global.properties file. Modify the ImageMagick properties to point to the ImageMagick root directory: Table1.ImageMagickproperties 1
Property
1
Description
1
img.root
1
On Windows, set this property to img.root=C:\ \ImageMagickOn Linux, set this property to img.root=/ ImageMagick Note: Do not include a slash ( /) at the end of the path. For example, / ImageMagick/
1
img.dyn
1
On Windows, set this property to img.dyn=${img.root}\ \libOn Linux, set this property to img.dyn=${img.root}/lib
1
img.exe
1
On Windows, set this property to img.exe=${img.root}\ \convert.exeOn Linux, set this property to img.exe=$ {img.root}/bin/convert
1
img.coder s
1
On Windows, set this property to img.coders=${img.root}\ \modules\\codersOn Linux, set this property to img.coders=$ {img.root}/modules/coders
1
img.confi g
1
On Windows, set this property to img.config=${img.root}\ \config On Linux, set this property to img.config=$ {img.root}/config
19 Note: Test that you are able to convert a PDF using the command convert filename.pdf[0] filename.png.
59
Installing TinyMCE language packs Translations in Alfresco use the language packs supplied in the default install. The supported language packs are: German (de), English (en), Spanish (es), French (fr), Italian (it), Japanese (ja), and Dutch (nl). The language used switches according to the browser locale. Ensure that your browser is set up to view the relevant locale, which ensures that the special characters display correctly in your installed instance. The source-localized files are encoded in ASCII, and the special and accented characters are displayed using escape sequences. The source files have been renamed using the corresponding locale for each language. For example, site-welcome.properties is called sitewelcome_ fr.propertiesfor the French version. If you wish to use a translation that is not supplied with Alfresco, then you must add the appropriate TinyMCE language pack for the translation to work correctly. If you installed Alfresco using one of the setup wizards, the default language packs are already installed. If you have installed Alfresco manually, you must install the supported language pack manually. 1 Browse to the TinyMCE website: TinyMCE. 2 Download the required TinyMCE language pack. Note: The next step makes configuration changes to the Share application to configure the additional language packs for TinyMCE. This step can only be performed after Alfresco has been installed. 3 Unpack the language file to: /webapps/share/modules/editors/ tiny_mce/langs. 4 Ensure that the browser cache is cleared or refresh the page.
60
Installing Linux libraries manually Use this information to install Linux libraries manually on supported Linux distributions, such as Ubuntu, SUSE and Red Hat. LibreO!ce requires the following libraries to be installed on your system: • libfontconfig • libICE • libSM • libXrender • libXext • libXinerama • libcups
• libGLU On some Linux distributions, such as Ubuntu, SUSE, and Red Hat, the Alfresco setup wizard will validate whether or not the required libraries are present. If the required libraries are missing, you will get a warning message. You can install them using your package manager from the command line. If LibreO!ce does not start up normally with Alfresco, test manually; for example, by running this startup script: start ex. {installdir}/libreoffice/scripts/libreoffice_ctl.sh start status ex. {installdir} /libreoffice/scripts/libreoffice_ctl.sh status If you receive errors that indicate that a library missing, work with your system administrator to add the missing library or its equivalent from your configured repositories. sudo apt-get install libsm6:i386
61
Installing Community Edition on Linux (text mode) Use this information to install Alfresco on Linux where you do not have a graphical interface. The Linux installation file can be run as a graphical setup wizard, but you can also run this file to install Alfresco using text mode. Text mode is a keyboard-based installation method. 1 Download the installation file: alfresco-community-installer-201606-EA-linuxx64.bin Files are available from Download and install Alfresco. 2 Run the following file: alfresco-community-installer-201606-EA-linux-x64.bin Follow the prompts on the screen to complete the install. 3 4
5 6 7 8
9
Choose a language for the installation steps. Enter the number that relates to your chosen language. Enter the folder where you'd like to install Alfresco. Installation folder
Please choose a folder to install Alfresco Community (Evaluation Use Only) Select a folder [/opt/alfresco-community]: The default is /opt/alfresco-community. You might need root (sudo) rights to access this folder. Enter a password to use for your Administrator user. Admin Password
10 11 Please give a password to use for the Alfresco administrator account. 12 13 Admin Password: : The Administrator user is called admin. The Administrator is the user account that can manages Alfresco and its users. 14 Repeat the password. 15 Enter Y (yes) to continue with the installation. 16 (Optional) If you are logged in as root, you then see an option for installing Alfresco as a service. Note: If you are logged in as a standard user, you do not see this option. You can optionally register Alfresco Enterprise as a service. This way it will 17 automatically be started every time the machine is started. 18 19 Install Alfresco Community as a service? [Y/n]:" 20 21 The alfresco service script file exists. Please insert a different name for the 22 service script. 23 24 Service script name: [alfresco]:
!
Select Yes to register Alfresco as a service. The default name of the service is alfresco. The server will then automatically be started every time the machine is started. If you select Yes, when you click Next, you may be asked to provide the Alfresco service script name. Enter a name for the script to run the service. 62
Select No to install Alfresco. ! 25 Enter Y (yes) to continue with the installation. Setup is now ready to begin installing Alfresco Community (Evaluation Use Only) on 26 your computer. 27 28 Do you want to continue? [Y/n]: You'll then see a status bar showing the progress of the files being installed. When it is complete, you'll see the following:
29
Installing 0% ______________ 50% ______________ 100%
30 ######################################## 31 To finish the install and show the README file, enter Y (yes). 32 Finally, press Enter to continue. When you have finished, start the server and login using the user admin and the password you entered in step 4. Use the URL http://127.0.0.1:8080/share on this machine to verify that Alfresco is running successfully. This is not an externally addressable URL, which means that it's not possible for users on other machines to access this URL. To make sure that other users can access the machine where Alfresco is installed, you need to define and create a publicly addressable name.
63
Installing Community Edition on Linux The setup wizard for Linux installs all the software and components that you require for running Alfresco. This setup wizard installs Alfresco and additional software, including a Tomcat application server, PostgreSQL database, JRE, and LibreO!ce. 1 Download the installation file: alfresco-community-installer-201606-EA-linuxx64.bin Files are available from Download and install Alfresco. This Alfresco setup wizard is for 64-bit Linux systems. 2 Execute the downloaded file. You can do this by changing the file permissions: chmod +x alfresco-community-installer-201606-EA-linux-x64.bin and running the file:./alfresco-community-installer-201606-EA-linux-x64.bin The setup wizard starts. 3 On the Language Selection window, select the installation language. The default language i s English. Click OK to accept the default language. 4 On the Setup - Alfresco Communitywindow, click Next. 5 Select the installation language. This sets the language to be used for the remainder of the setup wizard. 6 On the Installation type window, choose how you want to use the setup wizard. There are two types of installation in the setup wizard: 1
1
Description
1
Easy type installs Alfresco using the default options and configuration. This install type requires you to enter information in only two fields: the Alfresco install location and the administrator password. Choose this route to install Alfresco with the default environment.Note: If you have previously installed Alfresco and the server is running, when you run this installation wizard again, you may be prompted to enter alternative port numbers for the components and services that you install.
1
Advanced type installs Alfresco but lets you configure the server ports and service properties. You can also choose which additional components to install.
O pti on 1 Ea sy
1 A dv an ce d
a b
c
d e
13 To complete the Easy setup wizard: Select Easy, and then click Next. On the Installation Folder window, click Next to accept the default location. Note: You must use ASCII characters only when setting the installation folder using the Alfresco setup wizard. On the Admin Password window, enter a password for the Administrator user (admin). CAUTION: You must use ASCII characters only when setting the password using the Alfresco setup wizard. If you need to reset the password (to include non-ASCII characters) after installation, see Changing a user's password. Repeat the password, and then click Next. Click Next through the remaining windows in the setup wizard. 64
Click Finish to complete the installation. Go to the step for the Completing the Alfresco Community Setup Wizardwindow and l aunching Alfresco Share. 7 To complete the Advanced setup wizard, select Advanced and then click Next. Follow the remaining steps in this task. 8 On the Select Components window, select the components that you want to install. Deselect the components that you do not want to install. a Java (this is JRE only) b PostgreSQL c LibreO!ce d Solr 1 e Solr 4 f Alfresco O !ce Services g Web Quick Start h Google Docs Integration 9 When you have finished selecting the components, click Next. 10 On the Installation Folder window, click Next to accept the default location. For example, the default location is /opt/alfresco-community. f
Alternatively, click the
icon to choose another location.
Note: You must use ASCII characters only when setting the installation folder using the Alfresco setup wizard. 11 The Database Server Parameterswindow prompts you to enter a port number for your database. 12 On the Tomcat Port Configuration window, enter the following Tomcat configuration parameters: a Web Server Domain For example, the default is 127.0.0.1. The URL http://127.0.0.1:8080/share is based on the web server domain and the Tomcat port number that you specify on the Tomcat Port Configuration window. The default of 127.0.0.1 can be used on this machine to verify that Alfresco is running successfully. However, it is not an externally addressable URL, which means that it is not possible for users on other machines to access this URL. To make sure that other users can access the machine where Alfresco is installed, you need to define and create a publicly addressable name. b Tomcat Server Port For example, the default is 8080. c Tomcat Shutdown Port For example, the default is 8005. d Tomcat SSL Port For example, the default is 8443. e Tomcat AJP Port For example, the default is 8009. 13 (Optional) If you are installing the LibreO !ce component, the LibreO!ce Server Port window displays. Enter a port number on which the LibreO!ce server will listen. 14 On the Alfresco FTP Port window, enter a port number for the Alfresco FTP server. 15 On the Admin Password window, type a password. Repeat the password, and then click Next. This sets the password for the Alfresco Administrator user account ( admin). CAUTION: You must use ASCII characters only when setting the password using the Alfresco setup wizard. If you need to reset the password (to include non-ASCII characters) after installation, see Changing a user's password. 16 (Optional) If you are ins talling SharePoint Protocol Support, the Alfresco SharePoint Port window displays. Enter a port number, and then click Next. 17 On the Ready to Install window, click Next. The Installing window displays, showing the progress of the installation. 65
18 On the Completing the Alfresco Community Setup Wizardwindow, click Finish. This window shows check boxes that determine whether you will see the Readme file, the Getting Started web page, and also whether to launch Alfresco. By default, these options are selected and will launch when you click Finish. If you do not want to start Alfresco at this point, deselect the Launch Alfresco Community check box. 19 Click OK to close the Readme. The Alfresco server starts and then Alfresco launches in your default browser. Important: It can take several minutes to start the Alfresco server and to launch Alfresco. Your browser opens and tries to connect to http://127.0.0.1:8080/share. 20 Log on to Alfresco as the admin user. Enter the password that you specified in the Admin Password Thethe Alfresco server is launched automatically as a service called alfresco. This servicewindow. comprises following individual services:
a b
postgresql Tomcat S erver
21 If you did not automatically launch Alfresco at the end of the setup wizard, to start Alfresco, you need to start all the services. 22 Manually start the Alfresco server: Browse to /opt/alfresco-community/ (the installation folder that you created in 9). As an administrator, run ./alfresco.sh start 23 To fully stop Alfresco, you must stop all the servi ces: Browse to /opt/alfrescocommunity/ (the installation folder that you created in 9). As an administrator, run ./alfresco.sh stop
66
Alfresco UI Interface Nos conectamos desde un browser a http://10.10.10.5:8080/share y entramos con el usuario admin y la contraseña que colocamos al instalar.
-Ya en el Dashboard de administrador damos click en More - Groups para crear grupos.
-Para crear un grupo damos click al botón Browse.
67
-Nos aparecen los grupos del sistema ya creados, damos click al botón redondo New group.
-Llenamos el campo Identifier con un nombre único y el campo Display Name con un comentario. Damos click al botón Create Group.
68
-Después de ingresar los grupos ya debemos verlos en el listado junto a los del sistema.
-Ya podemos crear usuarios. Damos click al link izquierdo Users y después en el botón New User.
69
-Llenamos los campos del nuevo usuario teniendo en cuenta que los campos obligatorios son los terminados en * y debemos asignarle un group.
-Un usuario puede pertenecer a varios grupos a la vez al igual que tener una cuota de uso de disco. Ademas, podemos en un caso dado deshabilitar una cuenta con la opción Disable Account.
70
-Ya creado el usuario podemos buscarlo en Users escribiendo parte del nombre en el campo User Search.
Ya tenemos nuestro Alfresco Community funcionando y listo para comenzar a crear sitios de colaboración y demás.
71
7
How To Encrypt Tomcat 8 Connections with Apache or Nginx on Ubuntu 16.04 Introduction Apache Tomcat is a web server and servlet container designed to serve Java applications. Frequently used in production enterprise deployments and for smaller application needs, Tomcat is both flexible and powerful. In this guide, we will discuss how to secure your Ubuntu 16.04 Tomcat installation with SSL. By default, upon installation, all communication between the Tomcat server and clients is unencrypted, including any passwords entered or any sensitive data. There are a
72
number of ways that we can incorporate SSL into our Tomcat installation. This guide will cover how to set up a SSL-enabled proxy server to securely negotiate with clients and then hand requests off to Tomcat. We will cover how to set this up with both Apache and Nginx.
Why a Reverse Proxy? There are a number of ways that you can set up SSL for a Tomcat installation, each with its set of trade-offs. After learning that Tomcat has the ability to encrypt connections natively, it might seem strange that we'd discuss a reverse proxy solution. SSL with Tomcat has a number of drawbacks that make it difficult to manage: •
Tomcat, when run as r ecommended with an unp rivileged user, cannot bi nd to restricted ports like the conventional SSL port 443: There are workarounds to this, like using the authbind program to map an unprivileged program with a restricted port, setting up port forwarding with a firewall, etc., but they still represent additional complexity. • SSL with Tomcat is not as widely supported by other software : Projects like Let's Encrypt provide no native way of interacting with Tomcat. Furthermore, the Java keystore format requires conventional certificates to be converted before use, which complicates automation. • Conventional web servers release more frequently than Tomcat : This can have significant security implications for your applications. For instance, the supported Tomcat SSL cipher suite can become out-of-date quickly, leaving your applications with suboptimal protection. In the event that security updates are needed, it is likely easier to update a web server than your Tomcat installation. A reverse proxy solution bypasses many of these issues by simply putting a strong web server in front of the Tomcat installation. The web server can handle client requests with SSL, functionality it is specifically designed to handle. It can then proxy requests to Tomcat running in its normal, unprivileged configuration. This separation of concerns simplifies the configuration, even if it does mean running an additional piece of software.
Prerequisites In order to complete this guide, you will have to have Tomcat already set up on your server. This guide will assume that you used the instructions in our Tomcat 8 on Ubuntu 16.04 installation guide to get set up. When you have a Tomcat up and running, continue below with the section for your preferred web server. Apache starts directly below, while the Nginx configuration can be found by skipping ahead a bit.
(Option 1) Proxying with the Apache Web Server's mod_jk
73
The Apache web server has a module called mod_jk which can communicate directly with Tomcat using the Apache JServ Protocol. A connector for this protocol is enabled by default within Tomcat, so Tomcat is already ready to handle these requests.
Section Prerequisites Before we can discuss how to proxy Apache web server connections to Tomcat, you must install and secure an Apache web server. You can install the Apache web server by following step 1 of this guide. Do not install MySQL or PHP. Afterwards, you will need to set up SSL on the server. The way you do this will depend on whether you have a domain name or not. •
If you hav e a do main nafree, me...trusted the easiest way toFollow secureour your server is with Let'sfor Encrypt, which provides certificates. Let's Encrypt guide Apache to set this up. • If you do not have a domain... and you are just using this configuration for testing or personal use, you can use a self-signed certificate instead. This provides the same type of encryption, but without domain validation. Follow our self-signed SSL guide for Apache to get set up. When you are finished with these steps, continue below to learn how to hook up the Apache web server to your Tomcat installation.
Step 1: Install and Configure
mod_jk
First, we need to install the mod_jk module. The Apache web server uses this to communicate with Tomcat using the Apache JServ Protocol. We can install mod_jk from Ubuntu's default repositories. Update the local package index and install by typing: • •
sudo apt-get update sudo apt-get install libapache2-mod-jk
•
sudo nano /etc/libapache2-mod-jk/workers.properties
The module will be enabled automatically upon installation. Next, we need to configure the module. The main configuration file is located at /etc/ libapache2-mod-jk/workers.properties. Open this file now in your text editor: Inside, find the workers.tomcat_home directive. Set this to your Tomcat installation home directory. For our Tomcat installation, that would be /opt/tomcat: /etc/libapache2-mod-jk/workers.properties workers.tomcat_ho me=/opt/tomcat
Save and close the file when you are finished.
Step 2: Adjust the Apache Virtual Host to Proxy with
mod_jk
Next, we need to adjust our Apache Virtual Host to proxy requests to our Tomcat installation. The correct Virtual Host file to open will depend on which method you used to set up SSL. If you set up a self-signed SSL certificate using the guide linked to above, open the default-ssl.conf file: •
sudo nano /etc/apache2/sites-available/default-ssl.con f
If you set up SSL with Let's Encrypt, the file location will depend on what options you selected during the certificate process. You can find which Virtual Hosts are involved in serving SSL requests by typing: 74
•
sudo apache2ctl -S
Your output will likely begin with something like this: Output • VirtualHost configuration: • *:80 example.com (/etc/apache2/sites-enabled/000default.conf:1) • *:443 is a NameVirtualHost • default server example.com (/etc/apache2/sites-enabled/000default-le-ssl.conf:2) • port 443 namevhost example.com (/etc/apache2/sites-enabled/000default-le-ssl.conf:2) • port 443 namevhost www.example.com (/etc/apache2/sites-enabled/ • •
default-ssl.conf:2) ...
Looking at the lines associated with SSL port 443 (lines 3-6 in this example), we can determine which Virtual Hosts files are involved in serving those domains. Here, we see that both the 000-default-le-ssl.conf file and the default-ssl.conf file are involved, so you should edit both of these. Your results will likely differ: • •
sudo nano /etc/apache2/sites-enabled/000-default-le-ssl.conf sudo nano /etc/apache2/sites-enabled/default-ssl.conf
Regardless of which files you have to open, the procedure will be the same. Somewhere within the VirtualHost tags, you should enter the following: . . . JKMount /* ajp13_worker . . .
Save and close the file. Repeat the above process for any other files you identified that need to be edited. When you are finished, check your configuration by typing: •
sudo apache2ctl configtest
If the output contains Syntax OK, restart the Apache web server process: •
sudo systemctl restart apache2
You should now be able get to your Tomcat installation by visiting the SSL version of your site in your web browser: https://example.com
Next, skip past the Nginx configuration below and continue at the section detailing how to restrict access to Tomcat in order to complete your configuration.
(Option 2) HTTP Proxying with Nginx Proxying is also easy with Nginx, if you prefer it to the Apache web server. While Nginx does not have a module allowing it to speak the Apache JServ Protocol, it can use its robust HTTP proxying capabilities to communicate with Tomcat. 75
Section Prerequisites Before we can discuss how to proxy Nginx connections to Tomcat, you must install and secure Nginx. You can install Nginx by following our guide on installing Nginx on Ubuntu 16.04. Afterwards, you will need to set up SSL on the server. The way you do this will depend on whether you have a domain name or not. • If you have a domain name... the easiest way to secure your server is with Let's Encrypt, which provides free, trusted certificates. Follow our Let's Encrypt guide for Nginx to set this up. • If you do not have a domain... and you are just using this configuration for testing or personal use, you can a self-signed certificateFollow instead. providesSSL the same type of encryption, but use without domain validation. ourThis self-signed guide for Nginx to get set up. When you are finished with these steps, continue below to learn how to hook up the Nginx web server to your Tomcat installation.
Step 1: Adjusting the Nginx Server Block Configuration Setting up Nginx to proxy to Tomcat is very straight forward. Begin by opening the server block file associated with your site. We will assume you are using the default server block file in this guide: •
sudo nano /et c/nginx/sites-available/default
Inside, towards the top of the file, we need to add an upstream block. This will outline the connection details so that Nginx knows where our Tomcat server is listening. Place this outside of any of the server blocks defined within the file: /etc/nginx/sites-available/default upstream tomcat {
}
server 127.0.0.1:8080 fail_timout=0;
server { . . .
Next, within the server block defined for port 443, modify the location / block. We want to pass all requests directly to the upstream block we just defined. Comment out the current contents and use the proxy_pass directive to pass to the "tomcat" upstream we just defined. We will also need to include the proxy_params configuration within this block. This file defines many of the details of how Nginx will proxy the connection: /etc/nginx/sites-available/default upstream tomcat { server 127.0.0.1:8080 fail_timout=0; }
server { . . . location / { #try_files $uri $uri/ =404; 76
include proxy_params; proxy_pass http://tomcat /; } . . . }
When you are finished, save and close the file.
Step 2: Test and Restart Nginx Next, test to make sure your configuration changes did not introduce any syntax errors: •
sudo nginx -t
If no errors are reported, restart Nginx to implement your changes: •
sudo systemctl restart nginx
You should now be able get to your Tomcat installation by visiting the SSL version of your site in your web browser: https://example.com
Restricting Access to the Tomcat Installation Now you have SSL encrypted access to your Tomcat installation, we can lock down the Tomcat installation a bit more. Since we want all of our requests to Tomcat to come through our proxy, we can configure Tomcat to only listen for connections on the local loopback interface. This ensures that outside parties cannot attempt to make requests from Tomcat directly. Open the server.xml file within your Tomcat configuration directory to change these settings: •
sudo nano /opt/tomcat/conf/server.xml
Within this file, we need to modify the Connector Currently are two Connectors enabled within the configuration. One definitions. handles normal HTTPthere requests on port 8080, while the other handles Apache JServ Protocol requests on port 8009. The configuration will look something like this: /opt/tomcat/conf/server.xml . . .
. . .
In order to restrict access to the local loopback interface, we just need to add an "address" attribute set to 127.0.0.1 in each of these Connector definitions. The end result will look like this: /opt/tomcat/conf/server.xml . . .
redirectPort="844 3" /> . . .
address="127.0.0.1" protocol="AJP/1.3"
After you've made those two changes, save and close the file. We need to restart our Tomcat process to implement these changes: •
sudo systemctl restart tomcat
If you followed our Tomcat installation guide, you have a ufw firewall enabled on your installation. Now that all of our requests to Tomcat are restricted to the local loopback interface, we can remove the rule from our firewall that allowed external requests to Tomcat. • sudo ufw delete allow 8080 Your Tomcat installation should now only be accessible through your web server proxy.
Conclusion At this point, connections to your Tomcat instance should be encrypted with SSL with the help of a web server proxy. While configuring a separate web server process might increase the software involved in serving your applications, it simplifies the process of securing your traffic significantly.
78