domingo, 3 de septiembre de 2017

Supervisord - Agregar Tomcat como como proceso del supervisord.



Instalar el supervisord de la siguiente manera:

sudo apt-get install -y supervisor

La configuración esta en /etc/supervisord y dentro de esta carpeta esta el archivo llamado /etc/supervisord/supervisord.conf donde se encuentra la siguiente linea:

[include]
files = /etc/supervisor/conf.d/*.conf

Todo archivo dentro de la carpeta conf.d y que tenga en la extensión conf va a ser incluido como proceso dentro de supervisor.

Podemos crear un archivo llamado tomcat_control.conf dentro de la carpeta /etc/supervisor/config.d/ y agregar lo siguiente:

[program:tomcat]
command=/opt/tomcat/bin/catalina.sh run
user=tomcat
numprocs=1
autostart=true
autorestart=true
stderr_logfile=/var/log/supervisor/tomcat.log
stdout_logfile=/var/log/supervisor/tomcat.out.log

De esta manera luego ejecutar los siguiente comandos:

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start tomcat
sudo supervisorctl status

Vamos como salida que el proceso tomcat esta corriendo correctamente.


CONFIGURAR NOTIFICACIONES SOBRE EL PROCESO TOMCAT


Para ello vamos a utilizar distintos lisener que nos ofrece supervisord como ser Crashmail y HttpOk


Primeramente debemos configurar el SMTP para poder enviar mails desde nuestro windows.

Instalamos primeramente mailutils:

sudo apt-get install mailutils

Intalamos SMTP:

sudo apt-get install ssmtp

Configuramos el SMTP:

sudo vim /etc/ssmtp/ssmtp.conf

Actualizamos con los datos de la cuenta a utilizar:

AuthUser=<user>@gmail.com
AuthPass=Your-Gmail-Password
mailhub=smtp.gmail.com:587
UseSTARTTLS=YES

Hacemos una prueba para verificar que el mail quedo correctamente configurado.

echo "This is a test" | mail -s "Test" <user>@<email>.com

Ahora vamos a crear un archivo llamado monitoring_lisener.conf dentro de la carpeta /etc/supervisor/conf.d/* y le agregamos la siguiente información:

[eventlistener:httpok]
command=httpok -m <user>@<email>.com -t 10 http://localhost:8080
events=TICK_5

[eventlistener:crashmail]
command=crashmail -a -m <user>@<email>.com
events=PROCESS_STATE_EXITED

El primero realiza un chequeo sobre la url localhost:8080 cada 5 segundos y con un timeout de 10 segundos. Si esta condicion se cumple envia una notificación al email que se pasa como parametro.

El segundo envia un mail cuando algún proceso pasa de estado RUNNING a EXITED

Fuente:

https://rianjs.net/2013/08/send-email-from-linux-server-using-gmail-and-ubuntu-two-factor-authentication
https://serversforhackers.com/c/monitoring-processes-with-supervisord
http://superlance.readthedocs.io/en/latest/httpok.html
https://poweruphosting.com/blog/install-tomcat-8-ubuntu/



sábado, 8 de julio de 2017

Angular 2 - 15) Soportar diferentes llamadas a servicios Rest API



Objetivo:
  • Soportar múltiples entornos(desarrollo-producción)


  1. Abrir una consola y dentro del proyecto angular-faster ejecutar este comando:


json-server database.json


Levante un servidor en el puerto 3000


  1. Abrir una nueva consola y dentro del proyecto angular-faster ejecutar este comando:


json-server --port 3001 database.json


Levanta un servidor en el puerto 3001


  1. Abrir el archivo llamado environment.ts y agregar la siguiente información:


export const environment = {
production: false,
apiEndPoint: "http://localhost:3000"
};


  1. Abrir el archivo llamado environment.prod.ts y agregar la siguiente información:


export const environment = {
production: true,
apiEndPoint: "http://localhost:3001"
};


  1. Abrir el archivo llamado user.service.ts y actualizar la información siguiente:


import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs';
import { User } from '../models/user';
import { environment } from '../../../environments/environment'


const SERVER_REST_API_URL = "http://localhost:3000/users/";


@Injectable()
export class UserService {


private http: Http;
private serverRestAPIUrl: string;


constructor(http:Http) {
  this.http = http;
  this.serverRestAPIUrl = environment.apiEndPoint + "/users";
}


getUsers() {
  return this.http.get(this.serverRestAPIUrl)
      .map(res => res.json());
}


deleteUser(id) {
  return this.http.delete(this.serverRestAPIUrl + id);
}


saveUser(user:User) {
  let body = JSON.stringify({
      "id": user.id,
      "name": user.name,
      "username": user.username
  });
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });
  return this.http.post(this.serverRestAPIUrl, body, options);
}


}


  1. Abrir una consola y dentro del proyecto angular-faster ejecutar los siguiente:


ng serve --env=prod


  1. Abrir en un brower la url: http://localhost:4200 y analizar que las consultas en la consola se ejecutan contra el entorno que fue definido para producción




  1. Analizar cómo agregar un nuevo entorno además del de producción. Para ello se debe actualizar el archivo llamado angular-cli.json





jueves, 6 de julio de 2017

Angular 2 - 14) Animaciones


Objetivo:
  • Aplicar animación trigger, state, transform


  1. Abrir el proyecto package.json y agregar la dependencia del módulo de animación


"dependencies": {
  "@angular/animations": "~4.2.0",
  "@angular/common": "^4.0.0",
  "@angular/compiler": "^4.0.0",
  "@angular/core": "^4.0.0",
  "@angular/forms": "^4.0.0",
  "@angular/http": "^4.0.0",
  "@angular/platform-browser": "^4.0.0",
  "@angular/platform-browser-dynamic": "^4.0.0",
  "@angular/router": "^4.0.0",
  "core-js": "^2.4.1",
  "rxjs": "^5.1.0",
  "zone.js": "^0.8.4"
},


  1. Abrir una consola y ejecutar npm install para instalar la dependencia de animations
  2. Dentro de app crear una carpeta llamada animations.
  3. Dentro de la carpeta animations crear un archivo llamado animations.components.css y agregar el siguiente contenido


p {
  width:200px;
  background:lightgray;
  margin: 100px auto;
  text-align:center;
  padding:20px;
  font-size:1.5em;
}


  1. Dentro de la carpeta animations crear un archivo llamado animations.component.html y agregar el siguiente contenido:


<p [@myAwesomeAnimation]='stateAnimation' (click)="animateMe()">Mi animacion</p>


  1. Dentro de la carpeta animations crear un archivo llamado animations.component.ts y agregar el siguiente contenido:


import { Component, OnInit } from '@angular/core';
import { trigger,state,style,transition,animate } from '@angular/animations';


@Component({
selector: 'app-animations',
templateUrl: './animations.component.html',
styleUrls: ['./animations.component.css'],
animations:  [
  trigger('myAwesomeAnimation', [
      state('small', style({
          transform: 'scale(1)',
      })),
      state('large', style({
          transform: 'scale(1.2)',
      })),
      transition('small => large', animate('100ms',style({
          transform: 'translateY(40px)'
      }))),
  ]),
]
})
export class AnimationsComponent implements OnInit {


stateAnimation: string = 'small';
 constructor() { }


animateMe() {
  this.stateAnimation = (this.stateAnimation === 'small' ? 'large' : 'small');
}


ngOnInit() {


}


}


Para los puntos anteriores revisar la opción de crear el component desde la consola. Mirar este link: https://github.com/angular/angular-cli/wiki/generate-component


  1. Abrir el archivo llamado app.module.ts y agregar lo siguiente:


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { ROUTES } from './app.route';


import { BrowserAnimationsModule } from '@angular/platform-browser/animations';


import { AppComponent } from './app.component';
import { UsersComponent } from './users/users.component';
import { UserFormComponent } from './user-form/user-form.component';
import { UserService } from './shared/services/user.service';
import { AnimationsComponent } from './animations/animations.component';


@NgModule({
declarations: [
  AppComponent,
  UsersComponent,
  UserFormComponent,
  AnimationsComponent
],
imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  ROUTES,
  BrowserAnimationsModule
],
providers: [
  UserService
],
bootstrap: [AppComponent]
})
export class AppModule { }


  1. Abrir el archivo app.route.ts y actualizar el contenido con esta información:


import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


import { AppComponent } from './app.component';
import { UsersComponent } from './users/users.component';
import { UserFormComponent } from './user-form/user-form.component';
import { AnimationsComponent } from './animations/animations.component';


export const ROUTE: Routes = [
  { path: '', redirectTo: 'users', pathMatch: 'full' },
  { path: 'users', component: UsersComponent },
  { path: 'new-user', component: UserFormComponent },
  { path: 'animations' , component: AnimationsComponent }
];


export const ROUTES: ModuleWithProviders = RouterModule.forRoot(ROUTE);


  1. Desde la consola ejecutar ng serve