Una vez mas traigo un ejemplo de como realizar un motor grafico en 3d basico, esta vez decidi recordar los viejos tiempos de estudiante, las formulas de rotacion de puntos en 3d son las siguientes, basandome en el articulo de la wikipedia
en processing y la mayor parte de los lenguajes de progamacion deberian de quedar asi:
void rot(float a, float b, float c) {
xt=x;
yt=y;
zt=z;
//rotar sobre x
xr=xt;
yr=yt*cos1(a)-zt*sin1(a);
zr=yt*sin1(a)+zt*cos1(a);
xt=xr;
yt=yr;
zt=zr;
//rotar sobre y
xr=xt*cos1(b)+zt*sin1(b);
yr=yt;
zr=-xt*cos1(b)+zt*cos1(b);
xt=xr;
yt=yr;
zt=zr;
//rotar sobre z
xr=xt*cos1(c)-yt*sin1(c);
yr=xt*sin1(c)+yt*cos1(c);
zr=zt;
xt=xr;
yt=yr;
zt=zr;
}
Pero al no utilizar las librerias 3d de los programas se tiene que representar los puntos 3d en 2d, de la siguiente manera:
int tx() {
ri=cx+(int)(100000*xt/(zt+100000));
return ri;
}
int ty() {
rj= cy-(int)(100000*yt/(zt+100000));
return rj;
}
Teniendo la teoria matematica podemos realizar graficas, o la representacion de objetos 3d,
Video
Una vez logrado el cometido, la meta es obtener objetos del mundo exterior a traves de fotografias y representarlos virtualmente en un software , modificarlos y posteriormente imprimirlos en alguna impresora 3d.
Anexo codigo fuente para processing:
float [] coseno=new float[63];
float [] seno=new float[63];
float [][][] malla=new float[101][101][3];
float [][][] malla2d=new float[101][101][3];
float theta=0,alfa=0 ,pi=3.14159265358979, rrr, it, jt;
int i, j, k, click=0;
int con=0, cx=250, cy=250;
p3d px=new p3d(100, 0, 0);
p3d py=new p3d(0, 100, 0);
p3d pz=new p3d(0, 0, 100);
//
p3d p1=new p3d(0, 0, 0);
void setup() {
size(500, 500);
con=0;
for (theta=0; theta<=6.2; theta+=.1) {
seno[con]=sin(theta);
coseno[con]=cos(theta);
con++;
}
for (i=0; i<=60; i+=1) {
for (j=0; j<=60; j+=1) {
malla[i][j][0]=i*5-150;
malla[i][j][1]=j*5-150;
//plano
//malla[i][j][2]=0;
//silla
//malla[i][j][2]=malla[i][j][0]*malla[i][j][0]/100-malla[i][j][1]*malla[i][j][1]/100;
//sombrero
jt=(j-30)*.50;
it=(i-30)*.50;
rrr=sqrt(it*it+jt*jt)+3*cos(sqrt(it*it+jt*jt));
malla[i][j][2]=rrr*10-100;
}
}
i=0;
}
void draw() {
background(255);
fill(0);
stroke(0);
px.rot(theta, alfa, .75);
py.rot(theta, alfa, .75);
pz.rot(theta, alfa, .75);
stroke(255, 0, 0);
line(cx, cy, px.tx(), px.ty());
stroke(0, 255, 0);
line(cx, cy, py.tx(), py.ty());
stroke(0, 0, 255);
line(cx, cy, pz.tx(), pz.ty());
stroke(0);
//rotar malla
for (i=0; i<=60; i+=1) {
for (j=0; j<=60; j+=1) {
p1.set(malla[i][j][0], malla[i][j][1], malla[i][j][2]);
p1.rot(theta, .5, .75);
malla2d[i][j][0]=p1.tx();
malla2d[i][j][1]=p1.ty();
//dibujar malla
if (j>0 &&i>0) {
line(malla2d[i][j][0], malla2d[i][j][1], malla2d[i-1][j-1][0], malla2d[i-1][j-1][1]);
line(malla2d[i][j][0], malla2d[i][j][1], malla2d[i][j-1][0], malla2d[i][j-1][1]);
}
}
}
delay(10);
theta+=.1;
alfa+=.03;
if (theta>=6.2) {
theta=0;
}
if(alfa>=6.2){
alfa=0;
}
}
void mouseClicked() {
if (click==0) {
for (i=0; i<=60; i+=1) {
for (j=0; j<=60; j+=1) {
malla[i][j][0]=i*5-150;
malla[i][j][1]=j*5-150;
//plano
malla[i][j][2]=0;
}
}
}
if (click==1) {
for (i=0; i<=60; i+=1) {
for (j=0; j<=60; j+=1) {
malla[i][j][0]=i*5-150;
malla[i][j][1]=j*5-150;
//silla
malla[i][j][2]=malla[i][j][0]*malla[i][j][0]/100-malla[i][j][1]*malla[i][j][1]/100;
}
}
}
if (click==2) {
for (i=0; i<=60; i+=1) {
for (j=0; j<=60; j+=1) {
malla[i][j][0]=i*5-150;
malla[i][j][1]=j*5-150;
//sombrero
jt=(j-30)*.50;
it=(i-30)*.50;
rrr=sqrt(it*it+jt*jt)+3*cos(sqrt(it*it+jt*jt));
malla[i][j][2]=rrr*10-100;
}
}
}
click+=1;
if (click>=3) {
click=0;
}
}
float sin1(float ang) {
if (ang<0) {
ang=-ang;
}
return seno[(int)(ang*10)];
}
float cos1(float ang) {
if (ang<0) {
ang=-ang;
}
return coseno[(int)(ang*10)];
}
class p3d {
float x, y, z, xt, yt, zt, xr, yr, zr;
int ri, rj;
p3d(float xx, float yy, float zz) {
x=xx;
y=yy;
z=zz;
}
void set(float xx, float yy, float zz) {
x=xx;
y=yy;
z=zz;
}
void rot(float a, float b, float c) {
xt=x;
yt=y;
zt=z;
//rotar sobre x
xr=xt;
yr=yt*cos1(a)-zt*sin1(a);
zr=yt*sin1(a)+zt*cos1(a);
xt=xr;
yt=yr;
zt=zr;
//rotar sobre y
xr=xt*cos1(b)+zt*sin1(b);
yr=yt;
zr=-xt*cos1(b)+zt*cos1(b);
xt=xr;
yt=yr;
zt=zr;
//rotar sobre z
xr=xt*cos1(c)-yt*sin1(c);
yr=xt*sin1(c)+yt*cos1(c);
zr=zt;
xt=xr;
yt=yr;
zt=zr;
}
int tx() {
ri=cx+(int)(100000*xt/(zt+100000));
return ri;
}
int ty() {
rj= cy-(int)(100000*yt/(zt+100000));
return rj;
}
}
domingo, 28 de diciembre de 2014
domingo, 21 de diciembre de 2014
efecto de fuego basico en processing
A continuacion les muestro como pueden hacer efecto de fuego aplicando la siguiente ecuacion, la cual consiste en el promedio de color basado en las posiciones del pixel.
(x,y)=((x,y)+(x-1,y+1)+(x,y+1)+(x+1,y+1))/4
El random de los colores van desde rojo, amarillo, negro y blanco, en el cual solamente se generan aletareamente en el ultimo renglon.
Codigo en processing:
Video
float y;
int r, g, b, i, j, n, np=20, cc=0;
int [][][] colores1=new int[101][101][3];
void setup() {
size(510, 510);
noStroke();
for (i=1; i<=100; i++) {
for (j=1; j<=100; j++) {
colores1[i][j][0]=0;
colores1[i][j][1]=0;
colores1[i][j][2]=0;
}
}
}
void draw() {
delay(10);
for (i=1; i<=100; i++) {
for (j=1; j<=100; j++) {
if (j==100 ) {
if ((int)random(0, 10)%3==0) {
//rojo
r=255;
g=0;
b=0;
} else if ((int)random(0, 10)%2==0) {
//amarillo
r=g=255;
b=0;
} else if ((int)random(0, 10)%2==0) {
r=g=b=255;
} else {
r=g=255;
b=0;
}
colores1[i][j][0]=r;
colores1[i][j][1]=g;
colores1[i][j][2]=b;
} else if (i<100 && j<100 &&i>1 &&j>1) {
if ((int)random(0, 10)%5==0) {
n=0;
} else {
n=(int)random(0, 5);
}
r=(colores1[i][j][0]+colores1[i-1][j+1][0]+colores1[i][j+1][0]+colores1[i+1][j+1][0])/4-n;
g=(colores1[i][j][1]+colores1[i-1][j+1][1]+colores1[i][j+1][1]+colores1[i+1][j+1][1])/4-n;
b=(colores1[i][j][2]+colores1[i-1][j+1][2]+colores1[i][j+1][2]+colores1[i+1][j+1][2])/4-n;
if (r<0)
r=0;
if (g<0)
g=0;
if (b<0)
b=0;
////////////
//////////
colores1[i][j][0]=r;
colores1[i][j][1]=g;
colores1[i][j][2]=b;
cuadro c=new cuadro(i, j, r, g, b);
if (j<96)
c.pinta();
}
}
}
}
class cuadro {
int x, y, r, g, b;
cuadro(int xx, int yy, int rr, int gg, int bb) {
x=xx;
y=yy;
r=rr;
g=gg;
b=bb;
}
void pinta() {
fill(r, g, b);
rect(x*5, y*5, 5, 5);
}
}
(x,y)=((x,y)+(x-1,y+1)+(x,y+1)+(x+1,y+1))/4
El random de los colores van desde rojo, amarillo, negro y blanco, en el cual solamente se generan aletareamente en el ultimo renglon.
Codigo en processing:
Video
float y;
int r, g, b, i, j, n, np=20, cc=0;
int [][][] colores1=new int[101][101][3];
void setup() {
size(510, 510);
noStroke();
for (i=1; i<=100; i++) {
for (j=1; j<=100; j++) {
colores1[i][j][0]=0;
colores1[i][j][1]=0;
colores1[i][j][2]=0;
}
}
}
void draw() {
delay(10);
for (i=1; i<=100; i++) {
for (j=1; j<=100; j++) {
if (j==100 ) {
if ((int)random(0, 10)%3==0) {
//rojo
r=255;
g=0;
b=0;
} else if ((int)random(0, 10)%2==0) {
//amarillo
r=g=255;
b=0;
} else if ((int)random(0, 10)%2==0) {
r=g=b=255;
} else {
r=g=255;
b=0;
}
colores1[i][j][0]=r;
colores1[i][j][1]=g;
colores1[i][j][2]=b;
} else if (i<100 && j<100 &&i>1 &&j>1) {
if ((int)random(0, 10)%5==0) {
n=0;
} else {
n=(int)random(0, 5);
}
r=(colores1[i][j][0]+colores1[i-1][j+1][0]+colores1[i][j+1][0]+colores1[i+1][j+1][0])/4-n;
g=(colores1[i][j][1]+colores1[i-1][j+1][1]+colores1[i][j+1][1]+colores1[i+1][j+1][1])/4-n;
b=(colores1[i][j][2]+colores1[i-1][j+1][2]+colores1[i][j+1][2]+colores1[i+1][j+1][2])/4-n;
if (r<0)
r=0;
if (g<0)
g=0;
if (b<0)
b=0;
////////////
//////////
colores1[i][j][0]=r;
colores1[i][j][1]=g;
colores1[i][j][2]=b;
cuadro c=new cuadro(i, j, r, g, b);
if (j<96)
c.pinta();
}
}
}
}
class cuadro {
int x, y, r, g, b;
cuadro(int xx, int yy, int rr, int gg, int bb) {
x=xx;
y=yy;
r=rr;
g=gg;
b=bb;
}
void pinta() {
fill(r, g, b);
rect(x*5, y*5, 5, 5);
}
}
jueves, 30 de octubre de 2014
targetcli iscsi initiator linux SAN
Procedimiento para la instalacion de targetcli y iscsi initiator, SAN
#Adquirir el inq del cliente
cat /etc/iscsi/initiatorname.iscsi
InitiatorName=iqn.1994-05.com.redhat:855e84c2fdf6
Configuracion lado del servidor:
$targetcli
- Crear disco
/backstores/fileio> create disco.img /home/user/algo.img 1G
- Crear wwn
/iscsi> create iqn.1994-05.com.redhat:94e529c0ab16
- Crear acl
/iscsi/iqn.19...b16/tpg1/acls> create iqn.1994-05.com.redhat:94e529c0ab16
- Crear lun
/iscsi/iqn.19...b16/tpg1/luns> create /backstores/fileio/disco.img
- Desactivar autentificacion
/iscsi/iqn.19...29c0ab16/tpg1> set attribute authentication=0
- Listar configuracion:
/ ls
##
- Salvar la configuracion
/ saveconfig
----------
Autentificacion
Desactivar autentificacion
.../tpg1> set attribute authentication=0
Verificar autentificacion
...> get auth
Establecer accesos:
...> set auth userid=foo
...> set auth password=bar
Instalacion de iscsi , del lado del cliente
##iscsi iniciator lado del cliente
yum -y install iscsi-initiator-utils
- Verificar el acceso
iscsiadm -m discovery -t sendtargets -p 10.199.11.19
10.199.11.19:3260,1 iqn.1994-05.com.redhat:94e529c0ab16
- Logearse
iscsiadm -m node --login
- Verificar la sesion
iscsiadm -m session -o show
tcp: [1] 10.199.11.19:3260,1 iqn.1994-05.com.redhat:94e529c0ab16 (non-flash)
- Configuracion del iscsi
vi /etc/iscsi/iscsid.conf
...
node.session.auth.authmethod = CHAP
...
node.session.auth.username = username
...
node.session.auth.password = password
...
#Adquirir el inq del cliente
cat /etc/iscsi/initiatorname.iscsi
InitiatorName=iqn.1994-05.com.redhat:855e84c2fdf6
Configuracion lado del servidor:
$targetcli
- Crear disco
/backstores/fileio> create disco.img /home/user/algo.img 1G
- Crear wwn
/iscsi> create iqn.1994-05.com.redhat:94e529c0ab16
- Crear acl
/iscsi/iqn.19...b16/tpg1/acls> create iqn.1994-05.com.redhat:94e529c0ab16
- Crear lun
/iscsi/iqn.19...b16/tpg1/luns> create /backstores/fileio/disco.img
- Desactivar autentificacion
/iscsi/iqn.19...29c0ab16/tpg1> set attribute authentication=0
- Listar configuracion:
/ ls
##
- Salvar la configuracion
/ saveconfig
----------
Autentificacion
Desactivar autentificacion
.../tpg1> set attribute authentication=0
Verificar autentificacion
...> get auth
Establecer accesos:
...> set auth userid=foo
...> set auth password=bar
Instalacion de iscsi , del lado del cliente
##iscsi iniciator lado del cliente
yum -y install iscsi-initiator-utils
- Verificar el acceso
iscsiadm -m discovery -t sendtargets -p 10.199.11.19
10.199.11.19:3260,1 iqn.1994-05.com.redhat:94e529c0ab16
- Logearse
iscsiadm -m node --login
- Verificar la sesion
iscsiadm -m session -o show
tcp: [1] 10.199.11.19:3260,1 iqn.1994-05.com.redhat:94e529c0ab16 (non-flash)
- Configuracion del iscsi
vi /etc/iscsi/iscsid.conf
...
node.session.auth.authmethod = CHAP
...
node.session.auth.username = username
...
node.session.auth.password = password
...
viernes, 17 de octubre de 2014
Linux y xmonad!
Una de las ventajas que se pueden tener en linux, es que tienes muchas opciones de personalizarlo a las necesidades o gustos, xmonad es un escritorio de mosaicos donde cada ventana ocupa un espacio en el escritorio, y es ubicado en el escritorio segun sea el algoritmo de posicionamiento, la ventaja de xmonad es que tenemos todas nuestras ventanas a nuestra vista y optimiza el uso de escritorios en los cuales podemos organizar por ventanas multimedia, ofimatica, explorador de archivos, consolas, chats, ademas que hacemos uso menos del raton optimizando nuestro tiempo con atajos del teclado.
Mostrare los pasos para una instalacion en fedora
Los sw que se instalaran son:
xmonad -> escritorio
xmobar -> barra
shutter -> tomar screenshot
gmrun -> lanzador de aplicaciones
feh -> fondo de pantalla
Instalacion:
yum install xmonad xmobar shutter gmrun feh
Anexo configuracion de xmonad:
~/.xmonad/xmonad.hs
--------------------------------------------------------------------------
-- default desktop configuration for Fedora
import System.Posix.Env (getEnv)
import Data.Maybe (maybe)
import XMonad
import XMonad.Hooks.EwmhDesktops
---
import System.Exit
import qualified XMonad.StackSet as W
import qualified Data.Map as M
-- GHC hierarchical libraries
import XMonad.Operations
import XMonad.Config
import XMonad.Util.Run
import System.IO
import Data.Ratio ((%))
--Contribs
import XMonad.Actions.CycleWS
import XMonad.Actions.NoBorders
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.ManageHelpers
import XMonad.Hooks.UrgencyHook
import XMonad.Hooks.FadeInactive
-- import XMonad.Layout
--librerias necesarias para los diferentes tipos de layouts
import XMonad.Layout.Accordion
import XMonad.Layout.Grid
import XMonad.Layout.IM
import XMonad.Layout.NoBorders
import XMonad.Layout.PerWorkspace
import XMonad.Layout.SimpleFloat
import XMonad.Layout.Spacing
import XMonad.Layout.Tabbed
import XMonad.Layout.Circle
import XMonad.Layout.Dishes
import XMonad.Layout.FixedColumn
import XMonad.Layout.ThreeColumns
---
import XMonad.Config.Desktop
--import XMonad.Config.Gnome
--import XMonad.Config.Kde
--import XMonad.Config.Xfce
import XMonad.Util.EZConfig
-- The preferred terminal program, which is used in a binding below and by
-- certain contrib modules.
-- Especificamos la terminal por default
myTerminal = "terminator"
-- Width of the window border in pixels.
-- El tamaño del borde que nos indicara si nuestra pantalla esta activa segun el color que pongamos
myBorderWidth =2
-- modMask lets you specify which modkey you want to use. The default
-- is mod1Mask ("left alt"). You may also consider using mod3Mask
-- ("right alt"), which does not conflict with emacs keybindings. The
-- "windows key" is usually mod4Mask.
-- tecla de acceso a comandos de xmonad por default super
myModMask = mod4Mask
altMask = mod1Mask
myNumlockMask = mod2Mask
-- The default number of workspaces (virtual screens) and their names.
-- Podemos anexar los espacios de trabajos que requerimos
myWorkspaces = ["web","mail","music","im","code","tex","consola","datos"]
-- Border colors for unfocused and focused windows, respectively.
--Especificamos los colores de vantanas activas e inactivas
-- Ventana inactiva
myNormalBorderColor = "#87ceeb"
-- Ventana activa
myFocusedBorderColor = "#adff2f"
------------------------------------------------------------------------
-- Key bindings. Add, modify or remove key bindings here.
--
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $
-- Lanzar Terminal [ Terminator ]
[ ((modm .|. shiftMask, xK_Return),
spawn $ XMonad.terminal conf)
-- Lanzar menu de apps [ DMENU ]
, ((modm, xK_p ),
--spawn "exe=`dmenu_run | dmenu` && eval \"exec $exe\"")
spawn "exe=`gmrun` && eval \"exec $exe\"")
-- Cerrar Aplicacion
, ((modm .|. shiftMask, xK_c ),
kill)
-- Rota las aplicaciones entre los algoritmos disponibles
, ((modm, xK_space ),
sendMessage NextLayout)
-- Resetea las aplicaciones
, ((modm .|. shiftMask, xK_space ),
setLayout $ XMonad.layoutHook conf)
-- Resize viewed windows to the correct size
, ((modm, xK_n ),
refresh)
-- Move focus to the next window
, ((modm, xK_Tab ),
windows W.focusDown)
-- Move focus to the next window
, ((modm, xK_j ),
windows W.focusDown)
-- Move focus to the previous window
, ((modm, xK_k ),
windows W.focusUp )
-- Move focus to the master window
, ((modm, xK_m ),
windows W.focusMaster )
-- Swap the focused window and the master window
, ((modm, xK_Return),
windows W.swapMaster)
-- Swap the focused window with the next window
, ((modm .|. shiftMask, xK_j ),
windows W.swapDown )
-- Swap the focused window with the previous window
, ((modm .|. shiftMask, xK_k ),
windows W.swapUp )
-- Reducir el Area maestra
, ((modm, xK_h ),
sendMessage Shrink)
-- Expandir el Area maestra
, ((modm, xK_l ),
sendMessage Expand)
-- Push window back into tiling
, ((modm, xK_t ),
withFocused $ windows . W.sink)
-- Increment the number of windows in the master area
, ((modm, xK_comma ),
sendMessage (IncMasterN 1))
-- Deincrement the number of windows in the master area
, ((modm , xK_period),
sendMessage (IncMasterN (-1)))
-- Toggle the status bar gap
-- Use this binding with avoidStruts from Hooks.ManageDocks.
-- See also the statusBar function from Hooks.DynamicLog.
--
-- , ((modm , xK_b ), sendMessage ToggleStruts)
-- Quit xmonad
, ((modm .|. shiftMask, xK_q ), io (exitWith ExitSuccess))
-- Restart xmonad
, ((modm , xK_q ), spawn "xmonad --recompile; xmonad --restart")
]
++
--
-- mod-[1..9], Switch to workspace N
--
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
--
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
--
-- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
--
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
-- Whether focus follows the mouse pointer.
--
myFocusFollowsMouse :: Bool
--myFocusFollowsMouse = False
myFocusFollowsMouse = True
myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
-- mod-button1, Set the window to floating mode and move by dragging
[ ((modm, button1), (\w -> focus w >> mouseMoveWindow w
>> windows W.shiftMaster))
-- mod-button2, Raise the window to the top of the stack
, ((modm, button2), (\w -> focus w >> windows W.shiftMaster))
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modm, button3), (\w -> focus w >> mouseResizeWindow w
>> windows W.shiftMaster))
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
--myLayoutHook =
-- avoidStruts $
--smartBorders $
-- Especificamos los tipos de layouts, podemos hacer las conbinaciones que mas nos acomodemos
myLayout = avoidStruts $ smartBorders $ Mirror tiled ||| Full
--myLayout = avoidStruts $ smartBorders $ simpleFloat ||| Full ||| tabbed shrinkText defaultTheme ||| Mirror tiled ||| Grid ||| Dishes 2 (1/6) ||| Circle ||| ThreeCol 1 (3/100) (1/2)
where
-- default tiling algorithm partitions the screen into two panes
-- Espacio entre las ventanas
tiled = spacing 5 $ Tall nmaster delta ratio
tileds = spacing 5 $ Tall nmaster delta ratio
grids = spacing 5 $ Grid
-- The default number of windows in the master pane
nmaster = 1
-- Default proportion of screen occupied by master pane
ratio = 1/2
-- Percent of screen to increment by when resizing panes
delta = 3/100
myLogHook :: X ()
myLogHook = fadeInactiveLogHook fadeAmount
where
--Cantidad de transparencia
fadeAmount = 0.6
myStartupHook = do
-- No olvidar el permiso de ejecucion
-- En este script se puede inciar feh,xcompmgr (para hacer transparentes las ventanas) , stalonetray (bandeja del sistema)
spawn "/home/usuarios/.xmonad/init.sh"
myManagementHooks :: [ManageHook]
myManagementHooks = [
resource =? "stalonetray" --> doIgnore
]
main = do
-- Inicia la barra xmobar
xmproc <- spawnPipe "xmobar"
session <- getEnv "DESKTOP_SESSION"
--xmonad $ maybe desktopConfig desktop session
xmonad $ ewmh defaultConfig {
--xmonad $ withUrgencyHook NoUrgencyHook defaultConfig {
--layoutHook = avoidStruts $ layoutHook defaultConfig,
layoutHook = myLayout,
-- simple stuff
terminal = myTerminal,
focusFollowsMouse = myFocusFollowsMouse,
borderWidth = myBorderWidth,
modMask = myModMask,
--numlockMask = myNumlockMask,
workspaces = myWorkspaces,
normalBorderColor = myNormalBorderColor,
focusedBorderColor = myFocusedBorderColor,
-- key bindings
keys = myKeys,
mouseBindings = myMouseBindings,
logHook = myLogHook,
--
manageHook = manageDocks <+> manageHook defaultConfig <+> composeAll myManagementHooks,
--
startupHook = myStartupHook
-- hooks, layouts
--manageHook = myManageHook <+> manageDocks,
--logHook = myLogHook workspaceBarPipe >> fadeInactiveLogHook 0xdddddddd,
-- For use with no panels or just dzen2
--layoutHook = ewmhDesktopsLayout $ avoidStruts $ myLayout
--layoutHook = myLayoutHook
}
--desktop "gnome" = gnomeConfig
--desktop "kde" = kde4Config
--desktop "xfce" = xfceConfig
--desktop "xmonad-mate" = gnomeConfig
desktop _ = desktopConfig
--------------------------------------------------------------------------
Configuracion de xmobar
~/.xmobarrc
--------------------------------------------------------------------------
Config { font = "-misc-fixed-*-*-*-*-10-*-*-*-*-*-*-*"
, bgColor = "black"
, fgColor = "grey"
--, position = Top
, position = TopW L 95
, lowerOnStart = True
, allDesktops = True
, commands = [ Run Weather "EGPF" ["-t","<station>: <tempC>C","-L","18","-H","25","--normal","green","--high","red","--low","lightblue"] 36000
, Run Network "eth0" ["-L","0","-H","32","--normal","green","--high","red"] 10
, Run Network "eth1" ["-L","0","-H","32","--normal","green","--high","red"] 10
, Run Cpu ["-L","3","-H","50","--normal","green","--high","red"] 10
, Run Memory ["-t","Mem: <usedratio>%"] 10
, Run Swap [] 10
, Run Com "uname" ["-s","-r"] "" 36000
, Run Date "%a %b %_d %Y %H:%M:%S" "date" 10
]
, sepChar = "%"
, alignSep = "}{"
, template = "%cpu% | %memory% * %swap% | %eth0% - %eth1% }{ <fc=#ee9a00>%date%</fc>| %EGPF% | %uname%"
}
--------------------------------------------------------------------------
Anexo unos capturas de pantalla
-- Mirror tiled
-- Full
-- Circle
-- Circle con transparencia
-- xmobar
-- Mirror tiled, imagen de fondo, ventanas trasnparentes
Algunos atajos del xmonad:
super
+ space : rotar layouts
+ enter : hacer la ventana actual a principal
+ tab : rotar las ventanas
+ p : Abrir gmrun
Para lograr la transparencia instalar xcompmgr
xcompmgr -I1 -O1 -Ff &
Pueden instalar feh para la imagen de fondo:
feh --randomize --bg-scale ~/Downloads/images/*
Un protector de pantalla xlock:
xlock -mode matrix
Con aportaciones de @cookkie_galleto
Mostrare los pasos para una instalacion en fedora
Los sw que se instalaran son:
xmonad -> escritorio
xmobar -> barra
shutter -> tomar screenshot
gmrun -> lanzador de aplicaciones
feh -> fondo de pantalla
Instalacion:
yum install xmonad xmobar shutter gmrun feh
Anexo configuracion de xmonad:
~/.xmonad/xmonad.hs
--------------------------------------------------------------------------
-- default desktop configuration for Fedora
import System.Posix.Env (getEnv)
import Data.Maybe (maybe)
import XMonad
import XMonad.Hooks.EwmhDesktops
---
import System.Exit
import qualified XMonad.StackSet as W
import qualified Data.Map as M
-- GHC hierarchical libraries
import XMonad.Operations
import XMonad.Config
import XMonad.Util.Run
import System.IO
import Data.Ratio ((%))
--Contribs
import XMonad.Actions.CycleWS
import XMonad.Actions.NoBorders
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.ManageHelpers
import XMonad.Hooks.UrgencyHook
import XMonad.Hooks.FadeInactive
-- import XMonad.Layout
--librerias necesarias para los diferentes tipos de layouts
import XMonad.Layout.Accordion
import XMonad.Layout.Grid
import XMonad.Layout.IM
import XMonad.Layout.NoBorders
import XMonad.Layout.PerWorkspace
import XMonad.Layout.SimpleFloat
import XMonad.Layout.Spacing
import XMonad.Layout.Tabbed
import XMonad.Layout.Circle
import XMonad.Layout.Dishes
import XMonad.Layout.FixedColumn
import XMonad.Layout.ThreeColumns
---
import XMonad.Config.Desktop
--import XMonad.Config.Gnome
--import XMonad.Config.Kde
--import XMonad.Config.Xfce
import XMonad.Util.EZConfig
-- The preferred terminal program, which is used in a binding below and by
-- certain contrib modules.
-- Especificamos la terminal por default
myTerminal = "terminator"
-- Width of the window border in pixels.
-- El tamaño del borde que nos indicara si nuestra pantalla esta activa segun el color que pongamos
myBorderWidth =2
-- modMask lets you specify which modkey you want to use. The default
-- is mod1Mask ("left alt"). You may also consider using mod3Mask
-- ("right alt"), which does not conflict with emacs keybindings. The
-- "windows key" is usually mod4Mask.
-- tecla de acceso a comandos de xmonad por default super
myModMask = mod4Mask
altMask = mod1Mask
myNumlockMask = mod2Mask
-- The default number of workspaces (virtual screens) and their names.
-- Podemos anexar los espacios de trabajos que requerimos
myWorkspaces = ["web","mail","music","im","code","tex","consola","datos"]
-- Border colors for unfocused and focused windows, respectively.
--Especificamos los colores de vantanas activas e inactivas
-- Ventana inactiva
myNormalBorderColor = "#87ceeb"
-- Ventana activa
myFocusedBorderColor = "#adff2f"
------------------------------------------------------------------------
-- Key bindings. Add, modify or remove key bindings here.
--
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $
-- Lanzar Terminal [ Terminator ]
[ ((modm .|. shiftMask, xK_Return),
spawn $ XMonad.terminal conf)
-- Lanzar menu de apps [ DMENU ]
, ((modm, xK_p ),
--spawn "exe=`dmenu_run | dmenu` && eval \"exec $exe\"")
spawn "exe=`gmrun` && eval \"exec $exe\"")
-- Cerrar Aplicacion
, ((modm .|. shiftMask, xK_c ),
kill)
-- Rota las aplicaciones entre los algoritmos disponibles
, ((modm, xK_space ),
sendMessage NextLayout)
-- Resetea las aplicaciones
, ((modm .|. shiftMask, xK_space ),
setLayout $ XMonad.layoutHook conf)
-- Resize viewed windows to the correct size
, ((modm, xK_n ),
refresh)
-- Move focus to the next window
, ((modm, xK_Tab ),
windows W.focusDown)
-- Move focus to the next window
, ((modm, xK_j ),
windows W.focusDown)
-- Move focus to the previous window
, ((modm, xK_k ),
windows W.focusUp )
-- Move focus to the master window
, ((modm, xK_m ),
windows W.focusMaster )
-- Swap the focused window and the master window
, ((modm, xK_Return),
windows W.swapMaster)
-- Swap the focused window with the next window
, ((modm .|. shiftMask, xK_j ),
windows W.swapDown )
-- Swap the focused window with the previous window
, ((modm .|. shiftMask, xK_k ),
windows W.swapUp )
-- Reducir el Area maestra
, ((modm, xK_h ),
sendMessage Shrink)
-- Expandir el Area maestra
, ((modm, xK_l ),
sendMessage Expand)
-- Push window back into tiling
, ((modm, xK_t ),
withFocused $ windows . W.sink)
-- Increment the number of windows in the master area
, ((modm, xK_comma ),
sendMessage (IncMasterN 1))
-- Deincrement the number of windows in the master area
, ((modm , xK_period),
sendMessage (IncMasterN (-1)))
-- Toggle the status bar gap
-- Use this binding with avoidStruts from Hooks.ManageDocks.
-- See also the statusBar function from Hooks.DynamicLog.
--
-- , ((modm , xK_b ), sendMessage ToggleStruts)
-- Quit xmonad
, ((modm .|. shiftMask, xK_q ), io (exitWith ExitSuccess))
-- Restart xmonad
, ((modm , xK_q ), spawn "xmonad --recompile; xmonad --restart")
]
++
--
-- mod-[1..9], Switch to workspace N
--
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
--
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
--
-- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
--
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
-- Whether focus follows the mouse pointer.
--
myFocusFollowsMouse :: Bool
--myFocusFollowsMouse = False
myFocusFollowsMouse = True
myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
-- mod-button1, Set the window to floating mode and move by dragging
[ ((modm, button1), (\w -> focus w >> mouseMoveWindow w
>> windows W.shiftMaster))
-- mod-button2, Raise the window to the top of the stack
, ((modm, button2), (\w -> focus w >> windows W.shiftMaster))
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modm, button3), (\w -> focus w >> mouseResizeWindow w
>> windows W.shiftMaster))
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
--myLayoutHook =
-- avoidStruts $
--smartBorders $
-- Especificamos los tipos de layouts, podemos hacer las conbinaciones que mas nos acomodemos
myLayout = avoidStruts $ smartBorders $ Mirror tiled ||| Full
--myLayout = avoidStruts $ smartBorders $ simpleFloat ||| Full ||| tabbed shrinkText defaultTheme ||| Mirror tiled ||| Grid ||| Dishes 2 (1/6) ||| Circle ||| ThreeCol 1 (3/100) (1/2)
where
-- default tiling algorithm partitions the screen into two panes
-- Espacio entre las ventanas
tiled = spacing 5 $ Tall nmaster delta ratio
tileds = spacing 5 $ Tall nmaster delta ratio
grids = spacing 5 $ Grid
-- The default number of windows in the master pane
nmaster = 1
-- Default proportion of screen occupied by master pane
ratio = 1/2
-- Percent of screen to increment by when resizing panes
delta = 3/100
myLogHook :: X ()
myLogHook = fadeInactiveLogHook fadeAmount
where
--Cantidad de transparencia
fadeAmount = 0.6
myStartupHook = do
-- No olvidar el permiso de ejecucion
-- En este script se puede inciar feh,xcompmgr (para hacer transparentes las ventanas) , stalonetray (bandeja del sistema)
spawn "/home/usuarios/.xmonad/init.sh"
myManagementHooks :: [ManageHook]
myManagementHooks = [
resource =? "stalonetray" --> doIgnore
]
main = do
-- Inicia la barra xmobar
xmproc <- spawnPipe "xmobar"
session <- getEnv "DESKTOP_SESSION"
--xmonad $ maybe desktopConfig desktop session
xmonad $ ewmh defaultConfig {
--xmonad $ withUrgencyHook NoUrgencyHook defaultConfig {
--layoutHook = avoidStruts $ layoutHook defaultConfig,
layoutHook = myLayout,
-- simple stuff
terminal = myTerminal,
focusFollowsMouse = myFocusFollowsMouse,
borderWidth = myBorderWidth,
modMask = myModMask,
--numlockMask = myNumlockMask,
workspaces = myWorkspaces,
normalBorderColor = myNormalBorderColor,
focusedBorderColor = myFocusedBorderColor,
-- key bindings
keys = myKeys,
mouseBindings = myMouseBindings,
logHook = myLogHook,
--
manageHook = manageDocks <+> manageHook defaultConfig <+> composeAll myManagementHooks,
--
startupHook = myStartupHook
-- hooks, layouts
--manageHook = myManageHook <+> manageDocks,
--logHook = myLogHook workspaceBarPipe >> fadeInactiveLogHook 0xdddddddd,
-- For use with no panels or just dzen2
--layoutHook = ewmhDesktopsLayout $ avoidStruts $ myLayout
--layoutHook = myLayoutHook
}
--desktop "gnome" = gnomeConfig
--desktop "kde" = kde4Config
--desktop "xfce" = xfceConfig
--desktop "xmonad-mate" = gnomeConfig
desktop _ = desktopConfig
--------------------------------------------------------------------------
Configuracion de xmobar
~/.xmobarrc
--------------------------------------------------------------------------
Config { font = "-misc-fixed-*-*-*-*-10-*-*-*-*-*-*-*"
, bgColor = "black"
, fgColor = "grey"
--, position = Top
, position = TopW L 95
, lowerOnStart = True
, allDesktops = True
, commands = [ Run Weather "EGPF" ["-t","<station>: <tempC>C","-L","18","-H","25","--normal","green","--high","red","--low","lightblue"] 36000
, Run Network "eth0" ["-L","0","-H","32","--normal","green","--high","red"] 10
, Run Network "eth1" ["-L","0","-H","32","--normal","green","--high","red"] 10
, Run Cpu ["-L","3","-H","50","--normal","green","--high","red"] 10
, Run Memory ["-t","Mem: <usedratio>%"] 10
, Run Swap [] 10
, Run Com "uname" ["-s","-r"] "" 36000
, Run Date "%a %b %_d %Y %H:%M:%S" "date" 10
]
, sepChar = "%"
, alignSep = "}{"
, template = "%cpu% | %memory% * %swap% | %eth0% - %eth1% }{ <fc=#ee9a00>%date%</fc>| %EGPF% | %uname%"
}
--------------------------------------------------------------------------
Anexo unos capturas de pantalla
-- Mirror tiled
-- Full
-- Circle con transparencia
-- xmobar
-- Mirror tiled, imagen de fondo, ventanas trasnparentes
Algunos atajos del xmonad:
super
+ space : rotar layouts
+ enter : hacer la ventana actual a principal
+ tab : rotar las ventanas
+ p : Abrir gmrun
Para lograr la transparencia instalar xcompmgr
xcompmgr -I1 -O1 -Ff &
Pueden instalar feh para la imagen de fondo:
feh --randomize --bg-scale ~/Downloads/images/*
Un protector de pantalla xlock:
xlock -mode matrix
Con aportaciones de @cookkie_galleto
miércoles, 9 de abril de 2014
Cluster HA en centos
En varias ocasiones se requiere que algun tipo de servicio como por ejemplo base de datos, peticiones http esten siempre disponibles, en linux hay varias opciones para poder solventar este problema y mantener al maximo la disponibilidad de servicio, una de ellas es heartbeat.
A continuacion describire algunos pasos para lograr un cluster de alta disponibilidad en 2 equipos con centos 6.5
Desactivar selinux.
Necesario instalar los repositorios epel.
Se instalan los siguientes paquetes.
yum --enablerepo=epel install heartbeat install cluster-glue resource-agents pacemaker
En archivo /etc/hosts en necesario espeficicar nombre del host e ip
nodo1 ip1
nodo2 ip2
Interfaces de red eth0 y eth1
eth0-> red de configuracion
eth1-> red del cluster
Editar el archivo /etc/ha.d/ha.cf con el siguiente contenido
auto_failback on
bcast eth0
warntime 5
deadtime 15
initdead 60
keepalive 2
node nodo1
node nodo2
Donde:
auto_failback on -> regresar la configuracion de la ip cuando regrese el nodo caido
bcast eth0 -> interface de red por donde se comunica el servicio de hearbeat
warntime 5 -> tiempo minimo de no respuesta
deadtime 15 -> tiempo para activar la ip y nodo inactivo
initdead 60
keepalive 2
node nodo1 -> nombre del host nodo1
node nodo2 -> nombre del host nodo2
Falta generar las llaves de autorizacion entre los nodos
( echo -ne "auth 1\n1 sha1 "; dd if=/dev/urandom bs=512 count=1 | openssl md5 ) > /etc/ha.d/authkeys
Modificar permisos
chmod 0600 /etc/ha.d/authkeys
Los servicios que iniciara automaticamente el ha, se necesitaran especificar en el archivo /etc/ha.d/haresources
nodo2 192.168.0.50/24/eth1/192.168.0.255 httpd mysqld
Agregar el servicio al incio:
chkconfig heartbeat on
Iniciar el servicio:
/etc/init.d/heartbeat start
A continuacion describire algunos pasos para lograr un cluster de alta disponibilidad en 2 equipos con centos 6.5
Desactivar selinux.
Necesario instalar los repositorios epel.
Se instalan los siguientes paquetes.
yum --enablerepo=epel install heartbeat install cluster-glue resource-agents pacemaker
En archivo /etc/hosts en necesario espeficicar nombre del host e ip
nodo1 ip1
nodo2 ip2
Interfaces de red eth0 y eth1
eth0-> red de configuracion
eth1-> red del cluster
Editar el archivo /etc/ha.d/ha.cf con el siguiente contenido
auto_failback on
bcast eth0
warntime 5
deadtime 15
initdead 60
keepalive 2
node nodo1
node nodo2
Donde:
auto_failback on -> regresar la configuracion de la ip cuando regrese el nodo caido
bcast eth0 -> interface de red por donde se comunica el servicio de hearbeat
warntime 5 -> tiempo minimo de no respuesta
deadtime 15 -> tiempo para activar la ip y nodo inactivo
initdead 60
keepalive 2
node nodo1 -> nombre del host nodo1
node nodo2 -> nombre del host nodo2
Falta generar las llaves de autorizacion entre los nodos
( echo -ne "auth 1\n1 sha1 "; dd if=/dev/urandom bs=512 count=1 | openssl md5 ) > /etc/ha.d/authkeys
Modificar permisos
chmod 0600 /etc/ha.d/authkeys
Los servicios que iniciara automaticamente el ha, se necesitaran especificar en el archivo /etc/ha.d/haresources
nodo2 192.168.0.50/24/eth1/192.168.0.255 httpd mysqld
Agregar el servicio al incio:
chkconfig heartbeat on
Iniciar el servicio:
/etc/init.d/heartbeat start
martes, 8 de abril de 2014
Configurando gfs2
Existen ocaciones en que se requiere un grupo de sistemas de archivos en el cual se tiene que compartir un conjunto de discos a 2 o mas nodos .
Una posible solucion es utilizar gfs, voy a desscribir a grandes rasgos los pasos para instalarlo en 2 equipos con centos 6.5
Instalar:
yum install -y gfs2-utils lvm2-cluster cman modcluster rgmanager openais
Agregar en el archivos de cada nodo /etc/hosts
nodo1 ip1
nodo2 ip2
Habilitar en el firewall las ips correspondientes de los nodos y deshabilitar selinux
Crear el esqueto de la configuracion del cluster
ccs_tool create clusterprueba
Estructura que controlara los nodos que no lleguen a responder
ccs_tool addfence nombre_referencia nombre_agente
Agregar los nodos:
ccs_tool addnode nodo1 -n 1 -v 1 -f nombre_referencia
ccs_tool addnode nodo2 -n 2 -v 1 -f nombre_referencia
Listar nodos:
ccs_tool lsnode
Validar configuracion:
ccs_config_validate
Si la configuracion no muestra ningun mensaje de error copiar el archivo en los nodos:
/etc/cluster/cluster.conf
Posteriormente en los nodos habilitar los servicios y agregarlos al autoinicio:
service cman start
service rgmanager start
lvmconf --enable-cluster
service clvmd start
chkconfig cman on; chkconfig rgmanager on; chkconfig clvmd on;
A partir de este momento tenemos la configuracion del grupo de sistema de archivos, ahora falta configurar los discos que estaran disponibles en los nodos.
Crear un pv
pvcreate /dev/vdb
Agregar un vg con las opciones de cluster
vgcreate -c y vg_cluster /dev/vdb
Agregar los volumenes logicos al grupo
lvcreate -l PE -n lv_cluster vg_cluster
Formateamos el volumen logico en gfs2
mkfs.gfs2 -p lock_dlm -t clusterprueba:lv_cluster -j <numero_nodos> /dev/vg_cluster/lv_cluster
Crear una carpeta en la cual montaremos nuestro sistema de archivo
mkdir /cluster
Ahora lo montamos
mount -t gfs2 -o noatime,nodiratime /dev/vg_cluster/lv_cluster /cluster/
Autoiniciar el servicio gfs2
chkconfig gfs2 on
Posteriormente en los demas nodos faltaria encontrar los discos:
#Encontrar pvs
pvscan
#Encontrar grupos logicos
vgscan
#Encontrar volumenes logicos
lvscan
La configuracion en el archivo fstab seria:
/dev/mapper/vg_cluster-lv_cluster /cluster gfs2 rw,noatime,nodiratime 0 0
o montar de forma manual.
Saludos.
Una posible solucion es utilizar gfs, voy a desscribir a grandes rasgos los pasos para instalarlo en 2 equipos con centos 6.5
Instalar:
yum install -y gfs2-utils lvm2-cluster cman modcluster rgmanager openais
Agregar en el archivos de cada nodo /etc/hosts
nodo1 ip1
nodo2 ip2
Habilitar en el firewall las ips correspondientes de los nodos y deshabilitar selinux
Crear el esqueto de la configuracion del cluster
ccs_tool create clusterprueba
Estructura que controlara los nodos que no lleguen a responder
ccs_tool addfence nombre_referencia nombre_agente
Agregar los nodos:
ccs_tool addnode nodo1 -n 1 -v 1 -f nombre_referencia
ccs_tool addnode nodo2 -n 2 -v 1 -f nombre_referencia
Listar nodos:
ccs_tool lsnode
Validar configuracion:
ccs_config_validate
Si la configuracion no muestra ningun mensaje de error copiar el archivo en los nodos:
/etc/cluster/cluster.conf
Posteriormente en los nodos habilitar los servicios y agregarlos al autoinicio:
service cman start
service rgmanager start
lvmconf --enable-cluster
service clvmd start
chkconfig cman on; chkconfig rgmanager on; chkconfig clvmd on;
A partir de este momento tenemos la configuracion del grupo de sistema de archivos, ahora falta configurar los discos que estaran disponibles en los nodos.
Crear un pv
pvcreate /dev/vdb
Agregar un vg con las opciones de cluster
vgcreate -c y vg_cluster /dev/vdb
Agregar los volumenes logicos al grupo
lvcreate -l PE -n lv_cluster vg_cluster
Formateamos el volumen logico en gfs2
mkfs.gfs2 -p lock_dlm -t clusterprueba:lv_cluster -j <numero_nodos> /dev/vg_cluster/lv_cluster
Crear una carpeta en la cual montaremos nuestro sistema de archivo
mkdir /cluster
Ahora lo montamos
mount -t gfs2 -o noatime,nodiratime /dev/vg_cluster/lv_cluster /cluster/
Autoiniciar el servicio gfs2
chkconfig gfs2 on
Posteriormente en los demas nodos faltaria encontrar los discos:
#Encontrar pvs
pvscan
#Encontrar grupos logicos
vgscan
#Encontrar volumenes logicos
lvscan
La configuracion en el archivo fstab seria:
/dev/mapper/vg_cluster-lv_cluster /cluster gfs2 rw,noatime,nodiratime 0 0
o montar de forma manual.
Saludos.
Suscribirse a:
Entradas (Atom)












