hiousi-blog-blog
hiousi-blog-blog
Hiousi
126 posts
At the time of writing, nobody knows what a Hiousi is. I am Hiousi and my real name is Pierre Bastoul
Don't wanna be here? Send us removal request.
hiousi-blog-blog · 5 years ago
Text
SuperLoadedHost with a Pfsense Libvirt VM on a VLAN tagged network
Running a Pfsense instance inside a KVM/libvirt host is trivial. What is less is allowing the host uses dns, dhcp, ntp and all services that the Pfsense guest as to offer.
And what happens if your network is made of tagged VLANs? How to talk to Pfsense VM ans others VM inside the host from your your lan?
Now I known how to do all that, and that make me happy :)
8021q and Macvtap will help
If you are here you probably have some libvirt/KVM VMs running around. My lab host is a Debian 10, so I'm sure all I need is included in the distribution. I have installed libvirt and KVM already, Just check if "8021q" and "macvlan" modules are loaded.
modprobe 8021q lsmod | grep 8021q modprobe macvlan lsmod | grep macvlan
The picture
Tumblr media
vlanNN are just linux 8021q interfaces bond to the physical eth0 interface. They are responsible for exchanging tagged traffic from/to the switch. You can give them any name, eth0.NN is commonly used. Keeping the id of the VLAN in the name is not mandatory, you can even give them the name of the VLAN: "management" or "voip" or "data"...
macvlanN are macvlan type interfaces bond to a vlanNN interface, one macvlanN is bond to one vlanNN interface. Those interfaces will be used by libvirt to make a bridge between the host and the guests.
Do not forget to prepare your switch with a trunked port, tagged for all the VLAN ids you need. I need 4 tagged VLANs: 10, 20, 30 and 90.
Host interfaces configuration
Now edit /etc/network/interfaces on the host
# file /etc/network/interfaces # you probably have a main interface in your own file already. # do not add any IP here auto eth0 iface eth0 inet manual pre-up ip link set $IFACE up post-down ip link set $IFACE down # the second interface of the host # the one that is going to the Wan. auto eth1 iface eth1 inet manual # this is the first VLAN interface, for VLAN10 # make one for each of the needed VLAN auto vlan10 iface vlan10 inet manual vlan-raw-device eth0 # the macvlan interface auto macvlan10 iface macvlan10 inet static address 192.168.1.2 netmask 255.255.255.0 gateway 192.168.1.1 pre-up ip link add macvlan10 link vlan10 type macvlan mode bridge post-down ip link set $IFACE down # duplicate vlan and macvlan config for all the VLANs # ... # ...
or if you prefer use iproute2 commands in a bootup script
# iproute2 commands ip link add link eth0 name vlan10 type vlan id 10 ip link set vlan10 up ip link add macvlan10 link vlan10 type macvlan mode ip addr add 192.168.1.2/24 dev vlan10 ip link set macvlan10 up
VM config
Now edit the vm .xml file to create all the needed interfaces.
<interface type='direct'>      <source dev='vlan10' mode='bridge'/>      <model type='virtio'/> </interface> <interface type='direct'>      <source dev='vlan30' mode='passthrough'/>      <model type='virtio'/> </interface> <interface type='direct'>      <source dev='eth1' mode='private'/>      <model type='virtio'/> </interface>
Check to see if all works
Ping from and to anything. From the host you should be able to ping all the bridged VMs. From the VMs, you can ping host and a endpoint on the lan. From the lan, you can ping a VM if you ping from inside the good vlan.
Acknowledgements
furor teutonicus "Enabling host-guest networking with KVM, Macvlan and Macvtap"
DAVID VASSALLO "KVM & BRCTL in Linux – bringing VLANs to the guests"
libvirt "Network XML format"
Hi cube "Macvlan vs Bridge"
0 notes
hiousi-blog-blog · 11 years ago
Text
Prestashop images hosted on Amazon S3
It's easy to move all Prestashop images to a remote S3 bucket, including products and categories images. It does not require any modification of the Prestashop core code
.
We will use the AWS SDK for PHP that comes with a great PHP Stream Wrapper.
Choose your favorite way of installing AWS SDK for PHP. I like to use Composer because it fits well with our deploy strategies.
Write a composer.json
{ "name": "o10c/mpm", "type": "project", "description": "mpm prestashop", "autoload": { "psr-0": { "": "src/" } }, "require": { "aws/aws-sdk-php": "2.*" }, "minimum-stability": "stable" }
and run "composer install"
Find a place to load the vendor/autoload.php class, and init the stream wrapper. I've choosed to override the Controller class, it's the first class loaded that we can override in Prestashop (you may have a better place/idea ?)
/override/classes/controller/Controller.php
use Aws\S3\S3Client; // find the path to your vendor/autoload.php require_once('/path/to/vendor/autoload.php'); abstract class Controller extends ControllerCore { public function __construct() { // register the S3 Stream Wrapper $s3 = S3Client::factory('/path/to/awsconfig.php'); $s3->registerStreamWrapper(); parent::__construct(); } }
An easy way to pass your credential to the wrapper is to use a config file.If you don't mind sharing your access keys in your code, it might be ok.
awsconfig.php
return array( 'includes' => array('_aws'), 'services' => array( 'default_settings' => array( 'params' => array( 'key' => 'YOUR_AWS_ACCESS_KEY_ID', 'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY', 'region' => 'eu-west-1' ) ) ) );
I prefer using an IAM role for my EC2 instances.. Please read the doc it's not so hard to configure.
Now you are able to use normal functions like file_get_contents() fopen() unlink(), is_file()... just use e.g. readfile("s3://yourbucket/path/to/filename.ext")! Read the Amazon S3 Stream Wrapper features guide
And now ? how does it work for Prestashop ?
Change a line in your config/defines.inc.php
// #define('_PS_IMG_DIR_', _PS_ROOT_DIR_.'/img/'); define('_PS_IMG_DIR_', 's3://bucket/');
et voilà. Try to upload a product image from admin...
Requirements
For all the images operations that Prestashop requires, you will need to use a recent GD extension, our is bundled with GD 2.1.0. Previous versions may not work properly.
and now?
You need a way to serve your images from S3. And S3 is not know as the killer webserver. Here is how we do.
Configure a dedicated cookieless domain for images, like "static.domain.com". Add this domain to settings.php
define('_MEDIA_SERVER_1_', 'static.domain.com);
Run a Nginx server to rewrite friendly images urls and/or proxy them to S3.
0 notes
hiousi-blog-blog · 11 years ago
Text
tu connais natsort() ?
PHP est un langage riche de functions... et après 17 ans de pratique (ben oui c'est vrai), je découvre aujourd'hui la géniale fonction natsort() natsort() pour tri "naturel", démonstration par l'exemple : $a = $b = array("K10.8", "K10.1", "K10.10", "K9.20", "K9.3", "K10.9", "K9.1", "K9.2"); Avec asort($a); Array ( [1] => K10.1 [2] => K10.10 [0] => K10.8 [5] => K10.9 [6] => K9.1 [7] => K9.2 [3] => K9.20 [4] => K9.3 ) Avec natsort($b); Array ( [6] => K9.1 [7] => K9.2 [4] => K9.3 [3] => K9.20 [1] => K10.1 [0] => K10.8 [5] => K10.9 [2] => K10.10 ) Ah oui, asort() se mélange un peu les pinceaux ! natsort() fait preuve de plus d'intelligence, enfin, disons que la fonction produit un résultat plus proche de ce que l'on pourrait attendre de ce genre de tri... voir : php.net/natsort
0 notes
hiousi-blog-blog · 11 years ago
Text
BOM DAG with a transitive closure table
ce billet doit être re-écrit, pas mal de bugs, use at your own risk!
Cette semaine j'ai découvert les "transitive closure tables", une manière élégante de représenter un DAG (directed acyclic graph) dans une base de donnée SQL.
Mais pourquoi faire ?
Mes produits sont assemblés à partir de sous-composants, eux mêmes assemblés à partir de pièces. Une pièce peut servir dans plusieurs composants, il faut parfois plusieurs sous-composants pour faire un produit. Dans le monde des ERP on appelle cela une BOM pour Bill of Material, en français une Nomenclature.
Tumblr media
J'ai un petit stock de pièces et voudrais savoir les quantités de produits que je suis en mesure de fabriquer.
D'abord, modéliser les relations parent/enfant des pièces avec leur composant dans une table SQL. Première idée utiliser le très classique "Adjacency List Model" :
parentchildquantity null1.91 11.9186.0 186.085.753 11.9138.2002 1.9138.1991 1.91288.01 1.9285.7531
BOM explosion
Pour connaitre les quantités de sous composants pour construire le produit 1.91 il faut construire une requête récursive, pour "descendre" dans l'arbre en faisant la somme de chacun des sous composants. MySQL n'est pas doué pour cela, il faut laisser à l'application le soin d'assurer la récursivité (avec PHP par exemple), on va exécuter autant de requêtes que l'arbre est profond.
Lors d'un mouvement de stock d'une des pièces, il faudra recalculer l'ensemble des quantités de produits que l'on peut fabriquer à partir de cette pièce. Je te dis pas le nombre de foreach et le nombre de requêtes qui vont avec...
Après avoir implémenté ce modèle, j'ai vite déjanté lorsqu'il a fallu recalculer les quantités fabricables d'un arbre de 80 produits composées de 300 sous ensembles. Finalement j'ai assez peu de sous-composants, mais un simple re-stockage d'une pièce nécessitait des dizaines de requêtes et un lock de la table "stock" pendant 2 à 3 secondes avec mon serveur de dev.
transitive closure table à mon secours.
Au lieu de décrire seulement les relations directes entre composants, on va écrire 1 ligne pour chacune des relations, même si elles ne sont pas directes.
child_p child_pa parent_p parent_pa hops quantity 38 199 1 91 0 1 38 200 1 91 0 1 85 753 1 91 0 1 85 753 1 91 1 4 85 753 1 92 0 1 85 753 86 0 0 1 85 753 288 0 0 2 86 0 1 91 0 1 86 0 288 0 0 1 288 0 1 91 0 1
Les relations directes on une valeur 0 pour "hops" (sauts). Quand "hops" est supérieur à 0 la ligne décrit une relation induite, en pointillée sur le schéma suivant. Le nombre de "hops" est le nombre de noeuds que l'on saute dans cette relation.
Tumblr media
La colonne "quantity" indique le nombre de composants nécessaires dans la relation. Ainsi il faut 1x(85.753) pour faire 1x(86.1). Et, selon la relation induite, il faut 4x(85.753) pour faire 1x(1.91).
Il devient très facile de connaitre les quantités de composants nécessaires pour fabriquer le produit (1.91) :
SELECT child_p as id_product, child_pa as id_product_attribute, SUM(quantity) as quantity FROM product_bom_closure WHERE parent_p = 1 AND parent_pa = 91 GROUP BY child_p, child_pa;
Exécuter sur sqlfiddle
BOM explosion, done !
et pour mon stock ?
La quantité que l'on peut fabriquer d'un composant, est égal à la plus petite quantité disponible de ces sous-composants (pondéré de la quantité nécessaire dans l'assemblage).
Ajoutons à notre modèle une table "stock_available"
id_product id_product_attribute quantity 38 199 20 38 199 20 38 200 8 85 753 10
et voilà comment, en une requête, calculer les quantités que l'on peut fabriquer des différents composants :
SELECT ascendants.id_product, ascendants.id_product_attribute, MIN(makable) as makable FROM ( SELECT descendants.parent_p as id_product, descendants.parent_pa as id_product_attribute, MAX(descendants.quantity) as quantity, descendants_stock.quantity as quantity_available, FLOOR(descendants_stock.quantity / MAX(descendants.quantity)) as makable FROM product_bom_closure descendants LEFT JOIN stock_available descendants_stock ON descendants.child_p = descendants_stock.id_product AND descendants.child_pa = descendants_stock.id_product_attribute GROUP BY descendants.child_p,descendants.child_pa, descendants.parent_p,descendants.parent_pa ) AS ascendants GROUP BY id_product,id_product_attribute
Exécuter sur sqlfiddle
Références
Guozhu Dong et al., "Maintaining Transitive Closure of Graphs in SQL http://homepages.inf.ed.ac.uk/libkin/papers/tc-sql.pdf
A Model to Represent Directed Acyclic Graphs (DAG) on SQL Databases http://www.codeproject.com/Articles/22824/A-Model-to-Represent-Directed-Acyclic-Graphs-DAG-o
Models for hierarchical data http://fr.slideshare.net/billkarwin/models-for-hierarchical-data
0 notes
hiousi-blog-blog · 11 years ago
Text
Stimuler la publication ?
Tumblr media
pourquoifair ? peut être rétablir une sorte de logique et avoir plus de personnes atteintes que de likes... je ne sais.
2 notes · View notes
hiousi-blog-blog · 12 years ago
Text
Extends Prestashop 1.5 modules
/themes/my_theme/module/cheque/cheque.php
<?php /* */ class ChequeExtends extends Cheque { /* ....... */ }
/override/module/Module.php
<?php /* * module override * @hiousi 2011 * */ class Module extends ModuleCore { /** * Return an instance of the specified module * * @param string $module_name Module name * @return Module */ public static function getInstanceByName($module_name) { if (!Validate::isModuleName($module_name)) { if (_PS_MODE_DEV_) die(Tools::displayError($module_name.' is not a valid module name.')); return false; } if (!isset(self::$_INSTANCE[$module_name])) { if (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/'.$module_name.'.php')) { include_once(_PS_MODULE_DIR_.$module_name.'/'.$module_name.'.php'); $override = _PS_THEME_DIR_.'modules/'.$module_name.'/'.$module_name.'.php'; if (Tools::file_exists_cache($override)) { include_once($override); $module_name .= "Extends"; } if (class_exists($module_name, false)) return self::$_INSTANCE[$module_name] = new $module_name; } return false; } return self::$_INSTANCE[$module_name]; } }
0 notes
hiousi-blog-blog · 13 years ago
Text
Human drone to mesure radioactivity ;)
Cesar Harada
J'ai rencontré Cesar Harada au TedX BasqueCountry. Comment vous dire ? pour moi il est le chevalier des temps modernes : technologique, open minded et open source, forcément intelligent, éco-citoyen, bardé de capteurs et un peu rebelle.
Il nous explique qu'il a démissionné du MIT (Le Massachusetts Institute of Technology, la plus prestigieuse université de techno du monde) pour concevoir des drones marins "open hardware" utilisés pour lutter contre les marées noires, projet entièrement financé par une souscription KickStarter. Les plans sont libres de droit, vous pouvez en construire vous aussi, tout est là : projet Protei
Peu après notre rencontre César s'envolait pour Tokyo. Il était très inquiet pour l'avenir des habitants de la région de Fukushima, une partie de sa famille habite au Japon. Beaucoup de gens vont contracter des maladies dues à cette immense catastrophe nucléaire. Il veut enregistrer les niveaux de radiations, accumuler les preuves que ne manquerons pas d'exiger les assurances maladie.
Il a donc équipé sont VTT de 2 capteurs Geiger, et parcouru la route Tokyo -> Sendai en relevant les niveaux de radioactivité. Il a réussi à s'approcher jusqu'à la limite de la zone évacuée autour du réacteur. Il a compilé toutes les mesures sur une carte, je vous laisse l'explorer, elle est richement illustrée de photos et vidéos : La carte du bike nuclear trail
Il projette maintenant d'utiliser ses drones marins pour les envoyer mesurer la radioactivité en mer. Vous aussi allez faire connaissance de César sur son site : CesarHarada.com
A oui dernier truc, César est un windsurfer, une excellente qualité, et il se demande s'il ne va pas se mettre au kitesurf, encore meilleure qualité.
Alors César, ce #kite, tu l'as acheté ou vas tu le construire toi même ? ;)
2 notes · View notes
hiousi-blog-blog · 13 years ago
Text
Un mini kit pour une nuit improvisée sur le Bassin
Hier, profitant d’une marée tardive et d’un fort coefficient, je me suis offert une petite balade avec notre catamaran. Le jouet est un New cat 12 (chantier Erplast), normalement réservé au enfants jusqu’à 12 ans en duo. Pour moi en solo, et encore très jeune (d’esprit), il marche à peu près, même si le caractère sportif de l’engin disparait sous mon poids généreux.
Tumblr media
photo @estouki
Le vent de Nord Est me décide à tirer un bord vers un recoin du domaine de Certes.
. A l’heure ou nous sommes (20h) j’espère pouvoir observer les oiseaux qui viennent là pour se reposer pour la nuit.
Le bord aller est rapide, je suis à destination rapidement. Pas de clapot, seulement quelques rides sur l’eau formées par le vent de terre, tout est calme et j’assiste alors au bal des cygnes qui se laissent approcher sans crainte. La lumière décline et il est temps de rentrer, virement de bord, cap Nord Ouest. Ciel de feu droit devant, c’est magnifique. Je me gave de ce couché de soleil grandiose, jusqu’au dernier rayon.
Des marins me l’ont dit, après le couché du soleil, soit le vent perdure, soit il tombe. Aujiourd'hui il tombe. Il me reste donc à parcourir 2 milles nautique, dans la presque parfaite pétole. La nuit s'installe, les lampadaires des ports et villages s’éclairent.
21h00, je suis encore loin de ma base, un peu faim et il commence à faire frais en t-shirt et maillot de bain. Je tue le temps en me racontant des histoires : la marée est en train de descendre, et si en plus, le peu de vent qu’il reste tombait.. ben voilà ! Échoué, planté ici, au milieu de la vasière, il ne me resterait plus qu’a attendre le retour de l’eau et de l’air, peut être jusqu’au lendemain à l’aube.
Qu’est ce que j’aimerai avoir pour passer un nuit sur mon trampoline humide ? des petites choses de confort et de sécurité que je puisse glisser dans la coque et oublier toute la saison jusqu’à ce que j’en ai besoin, j'ai pensé à :
2 couvertures de survie
1 sifflet
2 battons lumineux (Cyalume)
2/3 barres énergétiques, lait concentré
2 petites bouteilles d’eau (genre Evian) pas ouvertes (3 ans de durée de conservation)
1 bout, 1 couteau
1 sac étanche pour ranger le tout
Mais inutile, puisque je suis arrivé à la maison vers 22h30, où un bon plat de pâtes m’attendait ;)
Et vous vous, au cas où, vous auriez aimé avoir quoi ?
2 notes · View notes
hiousi-blog-blog · 14 years ago
Link
0 notes
hiousi-blog-blog · 14 years ago
Text
A Apache Vhost running as Asterisk for FreePBX
One problem I faced with FreePBX was the requirement to run Apache as user/group Asterisk. It's just annoying because I don't want to dedicate a machine just for Asterisk. I want to keep Apache running as www-data for most of the other apps.
For years I used to run a second instance of Apache, with it's own conf files, where I changed User and Group directives.
That was before I discovered apache2-mpm-itk. Works as Prefork server but with the hability to run each vhost with a particular user/group. Cool.
apt-get install apache2-mpm-itk
And accept to remove your old prefork Apache package. To configure just add in your Vhost configuration :
<IfModule mpm_itk_module> AssignUserId user group </IfModule>
Here is my Vhost for my Freepbx, with a dedicated log file.
<VirtualHost *> ServerName asterisk.domain.com DocumentRoot /var/www/freepbx CustomLog /var/log/apache2/freepbx_access.log combined <IfModule mpm_itk_module> AssignUserId asterisk asterisk </IfModule> </VirtualHost>
0 notes
hiousi-blog-blog · 14 years ago
Link
not been there #fail
0 notes
hiousi-blog-blog · 14 years ago
Photo
Tumblr media
finally something to show from my @home video distribution project
0 notes
hiousi-blog-blog · 14 years ago
Link
full of beans today
0 notes
hiousi-blog-blog · 14 years ago
Text
Protect your Prestashop template files
Prestashop templates (.tpl files), which are used to build themes and modules, are easily readable from a web browser. Just try a url like this :
http://www.really-cool-presta-shop.com/themes/win-a-free-theme/header.tpl
To prevent from copy, just add this to your .htaccess :
<Files "*.tpl"> Order allow,deny Deny from all ErrorDocument 403 "If you like our work, please visit <a href=\"http://www.lawebagence.com\">us</a> </Files>
0 notes
hiousi-blog-blog · 14 years ago
Link
0 notes
hiousi-blog-blog · 14 years ago
Text
A FreePBX ARI module to send fax from the User Portal
Hylafax is a very good fax server, but at our little office we are sending less and less faxes. Now Hylafax is a little bit "overscaled" for us. I've decided to remove it and look for Asterisk/Freepbx to do the job of sending faxes.
Receiving faxes with Asterisk is very easy. Digium Free For Fax (FFA) comes free for that. Download it from the Digium Store. Get a free license, and install. This page will give you all informations you need to make it work. Install the Fax module for Freepbx it will help you much for the settings.
Sending faxes is little more tricky. Recluse wrote a Wep Fax for Asterisk that works alone with FFA and Asterisk. I re-wrote his script to make a ARI module for FreePBX so users can access the page via the User Portal.
Simply go to your User Portal Page, something like http://your_asterisk_server/recordings Click on "Send fax", and fill the form : fax header, your local fax number, your email for report, the destination number (yes, please). Attach a PDF or TIFF file. Click on SendFax. After a short time you will receive by email a report about success or failure.
Download webfax-ari-module.tar.gz Extract it somewhere
Copy sendfax.module to /%AMPROOT%/recordings/modules/sendfax.module
Copy sendfaxnotify.php to ${ASTVARLIBDIR}/bin/sendfaxnotify.php
Change the two files to be owned by the user running Asterisk.
Create the following context in /etc/asterisk/extensions_custom.conf and reload asterisk :
[outboundfax] exten => s,1,Set(FAXOPT(filename)=${FAXFILE}) exten => s,n,Set(FAXOPT(ecm)=yes) exten => s,n,Set(FAXOPT(headerinfo)=${FAXHEADER}) exten => s,n,Set(FAXOPT(localstationid)=${LOCALID}) exten => s,n,Set(FAXOPT(maxrate)=14400) exten => s,n,Set(FAXOPT(minrate)=2400) exten => s,n,SendFAX(${FAXFILE},d) exten => s,n,System(${ASTVARLIBDIR}/bin/sendfaxnotify.php INIT "${EMAIL}" "${DESTINATION}" "${TIMESTAMP}" "NO_STATUS" "NO_PAGES") exten => h,1,NoOp(FAXOPT(ecm) : ${FAXOPT(ecm)}) exten => h,n,NoOp(FaxStatus : ${FAXSTATUS}) exten => h,n,NoOp(FaxStatusString : ${FAXSTATUSSTRING}) exten => h,n,NoOp(FaxError : ${FAXERROR}) exten => h,n,NoOp(RemoteStationID : ${REMOTESTATIONID}) exten => h,n,NoOp(FaxPages : ${FAXPAGES}) exten => h,n,NoOp(FaxBitRate : ${FAXBITRATE}) exten => h,n,NoOp(FaxResolution : ${FAXRESOLUTION}) exten => h,n,System(${ASTVARLIBDIR}/bin/sendfaxnotify.php NOTIFY "${EMAIL}" "${DESTINATION}" "${TIMESTAMP}" "${FAXSTATUSSTRING}" "${FAXPAGES}") ; end of outboundfax context
Your comments are very welcome.
1 note · View note
hiousi-blog-blog · 14 years ago
Link
0 notes