Tuesday, September 17, 2013

Creating a debian package from binaries



Create directory following the naming $PACKAGE-$VERSION:

mkdir private-tomcat-7.0.42
cd private-tomcat-7.0.42

Copy to this directory the files that you want to be installed.


Create configuration:

#dh_make --createorig

Type of package: single binary, indep binary, multiple binary, library, kernel module, kernel patch?
 [s/i/m/l/k/n] s

Maintainer name  : root
Email-Address    : root@unknown
Date             : Wed, 21 Aug 2013 01:36:59 -0700
Package Name     : private-tomcat
Version          : 7.0.42
License          : blank
Type of Package  : Single
Hit  to confirm: 
Currently there is no top level Makefile. This may require additional tuning.
Done. Please edit the files in the debian/ subdirectory now. You should also
check that the private-tomcat Makefiles install into $DESTDIR and not in / .


Edit the created debian/control file:

Source: private-tomcat
Section: main
Priority: extra
Maintainer: root 
Build-Depends: debhelper (>= 8.0.0)
Standards-Version: 3.9.2
#Vcs-Git: git://git.debian.org/collab-maint/private-tomcat.git
#Vcs-Browser: http://git.debian.org/?p=collab-maint/private-tomcat.git;a=summary

Package: private-tomcat
Replaces: 7.0.35
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: Apache tomcat for internal use in private Project

Edit debian/changelog and remove references to ITP (is not needed)

Rename debian/postinst.ex to postinst
mv postinst.ex postinst

Create the file debian/packagename.install with the following structure:

path/to/file/relative/to/source/root path/to/install/relative/to/system/root
i.e.
apache-tomcat-7.0.42/* opt/

change debian/compat to level 7

echo "7" > debian/compat

Copy the init.d or upstart script for the installed package name it as
debian/$PACKAGENAME.init

then run:

dh_installinit


IF you want to install the init.d package under a different name, please rename the init file to debian/$NAME.init and edit debian/rules and add the following

override_dh_installinit
 dh_installinit --name=tomcat (this is the desired name)

please remember to run dh_prep between runs of dh_installinit, Otherwise, it may cause multiple instances of the same text to be added to maintainer scripts.


from the directory above:

dpkg-buildpackage -b -us -uc
This will build the package and avoid signing errors

Friday, August 23, 2013

Puppet: certificates signed with multiple names

The default creation of SSL certs for the puppet master create a certicate base on the hostname of the server. If this server is reached with two different names (zB internalname.domain.com & external.domain.com) this creates problems such as: Server hostname 'internalname.domain.com' did not match server certificate; expected observer1 You can do the following:
rm -fr /var/lib/puppet/ssl #could delete individual .pem files 
puppet cert generate external.domain.com --dns_alt_names=internalname.domain,puppet
If executed as above (deleting all certs, all puppet nodes need to request certificate and the master to sign it)

Thursday, February 28, 2013

Managing SIP extensions with puppet

I decided to take the next step into the world of Puppet and actually created my own Provider and Type. So I would like to introduce "puppet-asterisk" which creates a custom type and provider for managing Asterisk's SIP configuration. The provider allows for simple SIP resource management, by managing /etc/asterisk/sip.conf and treating each SIP extension defined as an individual resource, so the following extension:
[100]
type=friend
host=dynamic
secret=MyPass123
context=internal
mailbox=100@default
callgroup=1
pickupgroup=1
dtmfmode=rfc2833
canreinvite=no
permit=10.34.0.1/32
deny=10.34.0.2/32
Can be expressed as:
sip {'100':
    ensure  => present,
    type    => 'friend',
    host    => 'dynamic',
    secret  => 'MyPass123',
    context => 'internal'
    mailbox => '100@default'
    permit  => '10.34.0.1/32',
    deny    => '10.34.0.2/32',
}
This allow to actually manage a SIP extension and it's properties individually and even grouping them as Virtual Resources. I have scouted Puppet Forge and most solutions focus completely on uploading the entire sip.conf as a template, which is pretty limiting. We must aim to keep as much as the infrastructure managed by Puppet as possible. Installing At the time of this writing I have not yet submitted it to puppet forge, so you must clone the repository from Github https://github.com/AlexRRR/puppet-asterisk and copy it to your /etc/puppet/modules Testing Please make sure you have rake, rspec installed
gem install rake
gem install rspec
Run the tests from root directory of project
>
rake spec

Friday, January 4, 2013

Creating a private signed repository with Ubuntu

To have a streamlined deployment and management strategy via Puppet it is necessary to be able to create signed Debian Packages and have a private signed repository that can contain such packages, this makes the Puppet manifest simpler and the updates will be done in a controlled manner.


Webserver configuration

Installing the webserver
apt-get install apache
<Directory /var/www/repos/ >
        Options Indexes FollowSymLinks Multiviews
        Order allow,deny
        Allow from all
</Directory>
<Directory "/var/www/repos/apt/*/db/">
        Order allow,deny
        Deny from all
</Directory>
<Directory "/var/www/repos/apt/*/conf/">
        Order allow,deny
        Deny from all
</Directory>
<Directory "/var/www/repos/apt/*/incoming/">
        Order allow,deny
        Deny from all
<?/Directory>

RNG Tools


The rngd daemon acts as a bridge between a Hardware TRNG (true random number generator) such as the ones in some Intel/AMD/VIA chipsets, and the kernel's PRNG (pseudo-random number generator). Virtual Machines are generally really bad at generating enough entropy that the gpg key generation need. RNG Tools aids that process.< /br>

NOTE: This step is optional but highly recommended if you are using a virtual machine

apt-get install rng-tools
vi /etc/default/rng-tools
Edit and Add the following

HRNGDEVICE=/dev/urandom

Finally start the service
/etc/init.d/rng-tools start

GPG key file generation


Next we will generate a GPG key to sign our repository and all of our packages with.
root@agent1:/home/alex# gpg --gen-key
gpg (GnuPG) 1.4.11; Copyright (C) 2010 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Please select what kind of key you want:
   (1) RSA and RSA (default)
   (2) DSA and Elgamal
   (3) DSA (sign only)
   (4) RSA (sign only)
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048) 
Requested keysize is 2048 bits
Please specify how long the key should be valid.
         0 = key does not expire
        = key expires in n days
      w = key expires in n weeks
      m = key expires in n months
      y = key expires in n years
Key is valid for? (0) 
Key does not expire at all
Is this correct? (y/N) y
You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
    "Heinrich Heine (Der Dichter) "
Real name: DevOps stuff
Email address: dev@gmx.de
Comment: DevOps stuff
You selected this USER-ID:
    "devops (DevOps stuff) "
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.
gpg: gpg-agent is not available in this session
passphrase not correctly repeated; try again.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
...+++++
+++++
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
.................+++++
.......+++++
gpg: key F15542E1 marked as ultimately trusted
public and secret key created and signed.
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
pub   2048R/F15542E1 2012-11-30
      Key fingerprint = FF1E A313 F3DA 256B A40E  FB3E 0749 613D F155 42E1
uid                  devops (DevOps stuff) 
sub   2048R/024EC2A2 2012-11-30

Create public GPG key

Now the key is already created and in the keychain. You may list it with

root@agent1:/home/alex# gpg --list-keys
/root/.gnupg/pubring.gpg
------------------------
pub   2048R/F15542E1 2012-11-30
uid                  devops (DevOps stuff) 
sub   2048R/024EC2A2 2012-11-30

Create the gpg key file that will be shared publicly via the webserver.
root@agent1:/home/alex# gpg --armor --output secure.gpg.key --export 024EC2A2
please note 024EC2A2 comes from the gpg --list-keys above!

Configure the Repository

Create the directory structure
mkdir -p /var/www/repos/apt/debian/conf
cd /var/www/repos/apt/debian/conf
Create the file "distributions" in the cwd and make sure the gpg key is used to sign the repository, add the following to the file
Origin: Alex Debian repo
Label: alex
Codename: precise
Architectures: amd64 i386 source
Components: main
Description: alex apt repository
DebOverride: override.precise
DscOverride: override.precise
SignWith: 024EC2A2

Create a file called "options" with the following content:
verbose
basedir .
ask-passphrase

Now create an empty file called "override.precise"
touch override.precise

Signing existing packages


dpkg-sig --sign builder /home/alex/demo-package-2.0.6_1.0-1_amd64.deb

Managing the repository


For this task we will use the tool "reprepro" which makes it very straightforward:
Install reprepro:
sudo apt-get install reprepro
Add a package:
reprepro -Vb . includedeb precise /home/alex/demo-package-2.0.6_1.0-1_amd64.deb
Remove a package:
reprepro -b . remove precise demo-package

Please note that when removing we are using the package name as it is described in the package manifest and the the filename itself

Friday, September 21, 2012

Encryped private keys

Protecting your private ssh-keys


I've noticed that most people are content just generating a keypair via ssh-keygen and using it as it is, but it is extremely important that the private key itself is encrypted. (I am not talking about the passhphrase... I am taking about encryption here). This can be achieved this way


openssl genrsa -aes256 -out raal.pem 2048

This will generate an encrypted .pem file, protected with the password you entered. This pemfile contains both your public and private keys. To extract your public key you need to do this:

chmod 600 raal.pem

ssh-keygen -y -f raal.pem > raal.pub


Tuesday, June 26, 2012

Counting occurences of subclasses in Django

Counting occurences of subclasses in Django

As a Django learning project I have began CONTMAN, a simple mobile content distribution system, and as expected I have ran into many different kinds of problems that I have thought it would be interesting to keep a log of... and this is it.

This might be the classic case of "When all you have is a hammer everything looks like a nail" as when I was thinking on how to design the project I came across Django inheritance and polymorphism features. "Aha! this is EXACTLY what I need" I said to myself. Now I am not so sure, but I am perhaps one of the most stubborn people in the world, so I kept going in that direction.

So I thought. I have two, maybe three different kinds of content I want to be able to distribute with this platform, for now I have "Ringtones" and "Wallpapers" (NB: I know it is not bleeding edge stuff, but keep in mind this was for learning, and I could not think of anything else at the time), and both of them are Content.

So we have a parent Content Class

class Content(models.Model):
    name = models.CharField(max_length=100)
    created_on = models.DateTimeField('created', auto_now_add = True )
    keyword = models.CharField(max_length=100)

And to children subclasses

class Ringtone(Content):
    artist = models.ManyToManyField(Artist)
    data_file = models.FileField(upload_to="uploads")

class Wallpaper(Content):
    category = models.ForeignKey(Category)
    data_file = models.ImageField(upload_to="uploads")

Ok, so there is a whole bunch of other stuff there but this is enough to get the point of this post across.

To me this was going to be very helpful in a lot of ways to mention some:

  • Delivering content would be as easy as pointing to Content.data_file (which you can't is it is clearly stated at the very end of this doc entry.)
  • The admin app would let me easily create a manager for uploading the file depending on the type (see comment above)
  • Creating reports would be very easy, just create a query set from the Content model.

This last point is the one we will be discussing. 

So it turns out that

a = Content.objects.get(pk=1)

returns a Content object, so you cannot count or fetch content using  "a.data_file".  So how can I do a simple report showing the count of each type of content available? The easy (lame) way could be to simple do two queries of Ringtone and Wallpapers as we only have those and leave Content alone. But this is not nice, in fact it reeks of bad code and self-pity. What if I later add support for "applications" and "games" Content types?

So after a nice session of Django docs + stack overflow + google I think I came across a very simple but effective solution here in stack overflow

The idea is to take advantage of the Contenttypes framework to keep track of what kind of model each object represents. This way we can aggregate easily on our query a create this type of report. So we modify the base (parent) class like this:
class Content(models.Model):
    name = models.CharField(max_length=100)
    created_on = models.DateTimeField('created', auto_now_add = True )
    keyword = models.CharField(max_length=100)
    content_type = models.ForeignKey("contenttypes.ContentType")

With this then we can easily do this:
class Content(models.Model):
>>>Content.objects.values('content_type__name').annotate(hits=Count("content_type"))
[{'hits': 1, 'content_type__name': u'ringtone'}, {'hits': 2, 'content_type__name': u'wallpaper'}]


Wednesday, February 25, 2009

Mysql and group_concat!

I'm determined to write a little more often on my blog (I've skipped 2008 altogether) because it also works as my personal notepad for the world to see. So let's get started.

Today I've discovered a wonderful new MySQL trick: group_concat and it saved me from doing tedious/slow scripting and also from trying to understand how Stored Procedures work in MySQL (which is something like arameic to me right now).

I've been working with Eventum which is a lovely open source bug tracker from the great thinkers at MySQL AB (now.. Sun). Eventum lets you add N custom fields to the issue creation and listing page, and it adds all of them to a table called eventum_issue_custom_fields. very much like this:


Each custom field has an Id, but they are all entered in different "rows" like this:
(lets say custon field "1" is the tv show name and field "2" is a short description)







IssueIdCustomFieldIdCustomFieldData
50190210
502Lame TV show
511Family Guy
512Funny Stuff


what if i wanted to select from this table the tv show name and the description in just one row?

Thinking about loops in your scripts?
Thinking about stored procedures?
Thinking it cannot be done at all?

Check this out:

SELECT IssueId,GROUP_CONCAT(CustomFieldData ORDER BY CustomFieldData SEPARATOR ',') AS value_list FROM tv_show_table GROUP BY IssueId ORDER BY IssueId

And you will get some nice stuff like:




IssueIdvalue_list
5090210, Lame TV Show
51Family Guy, Funny Stuff



How cool is that?!

the actual eventum query would be:

SELECT icf_iss_id,group_concat(icf_value order by icf_value separator ',') as values_list from eventum_issue_custom_field where icf_fld_id=2 OR icf_fld_id=1 group by icf_iss_id order by icf_iss_id;

Because i only want fields with id 1 or 2.


Bye!

Friday, February 20, 2009

Freetds, DBD-Sybase, Fedora 10


This is an update to an earlier entry

If you want to install DBD-Sybase Perl Module and use freetds in Fedora 10
you must install a patch for it to work. My versions are freetds-0.82, DBD-Sybase-1.09 and of course Fedora 10.




Find your way to the FreeTDS source directory, such that this command
works:

$ grep '\$Id' include/cspublic.h
static const char rcsid_cspublic_h[] = "$Id: cspublic.h,v 1.61 2008/09/08
17:50:25 jklowden Exp $";

Your ID will be different; it should match what's in the patch: 1.58.

Then "man patch" is your friend. Like it says,

usually just

patch
is all you need, as in:

$ patch < /path/to/your/cspublic.BLK_VERSION_150.patch

Then build and install per usual.


(shamelessly stolen from http://lists.ibiblio.org/pipermail/freetds/2009q1/024260.html)


Enjoy!!

Wednesday, October 24, 2007

Solving asterisk´s HDLC Abort Issue


Have you encountered the following msgs in your /var/log/asterisk/messages?

Oct 23 16:54:51 NOTICE[3345] chan_zap.c: PRI got event: HDLC Abort (6) on Primary D-channel of span 1
Oct 23 16:54:54 NOTICE[3345] chan_zap.c: PRI got event: HDLC Bad FCS (8) on Primary D-channel of span 1

if so... you've come to the right place. This is a very tricky one. There are mailing lists with tons of messages regarding this issue scattered throught the web, but none of the them actually follow throught what causes this and how to solve it.

The tricky part is that you system may probably seem to work, you can receive and place calls, but every now and then... all of the calls get dropped at the same time. "Must have been a quirk" you say to yourself even though you know such thing does not exist. Then a few minutes afterward... again. And that YELLOW alarm is now staring you in the eyes with that smug in his face....

PRI configuration is not for the faint of heart, that is for sure. But this message 99 times out of hundred is a harware incompatibility issue, not ISDN config.

High-Level Data Link Control or HDLC is a bit-oriented synchronous data link layer protocol, HDLC was introduced into Digium systems in order to allow data and voice to be used/routed in the same card. This is a good thing, the bad thing is that it relies on more on the system clock for timing. And new motherboards and kernels do not play nice with this settings and old telephony cards.

This may be caused due to IRQ interrupt sharing, APIC, HD params, but to put it plain and simple: YOUR TELEPHONY CARD DOES NOT LIKE YOUR MOTHERBOARD. I wish i had seen that sentence a few months ago.

This was exactly the case with my Proliant ML150 G3 server, which has an Intel Motherboard and specially an Intel Onboard ethernet card. I had a TE110p, which has been my workhorse in several other settings, so it was strange for me that it failed on me so often. As it turns out, Digium's TE110P is the picky girl type, it does not play well with others because of its chipset (TigerJet). Digium was aware of this, so they had to go back to the drawing board and came up with what they like to call "VoiceBus Technology" which basically works a whole lot better.

So here it is, plain and simple if you have a TE110P card having this problems, you MUST update your card to a newer version or get a motherboard that works with that TE110P and hold on to it, hard. They are getting harder to find by the minute. So the solution: Buy a TE120P with the new VoiceBus technology or just run to the Sangoma Camp.


I wish i had a magical bash script that solved this issue... but this time you must take the expensive road.

Luckily you may have found this blog very early in the guessing process of solving this issue and saved a ton of time. Trust me, i was seconds away of trying voodoo or any other sort of black magic.


Hope this helps!


Alex






Thursday, August 30, 2007

Flex: Checkboxes,repeaters,

Recently I've discovered this GREAT tool called Flex from Adobe, which solved one of my great problems: I can do a little bit of scripting but i am NO designer, so usually my GUIs end up giving a very bad impression of the overall app. Flex is here to save the day. Flex allows anyone to create streamlined, compatible GUIs in no time. But there is so much more to Flex than just GUIs. It uses both MXML and ActionScript so you have easy MXML interface creation along with a full Object Oriented language.

It is INCREDIBLE how all of us have being spoiled into stateful programming, I have had the hardest time trying to think stateless. So i have take baby steps.

This next Flex program is very simple, but it exemplifies some of Flex's main features.

So here it is:


xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="creationCompleteHandler();"
>


private function creationCompleteHandler():void
{
userRequest.send();
}
]]>


[Bindable]
var jailh:Array =new Array;
]]>


public function addToarray(Mymine:String):void{
var match:String = Mymine;
var isChecked:int = 0 ;
for (var i:int = 0; i < jailh.length; i++)
{
if (jailh[i] == match) {
dwindow.text="";
if (jailh.length == 1)
{
dwindow.text +="\n Will shift array"+ '\n'
jailh.shift();}
else
{
dwindow.text +="\n splice:\t"+i+','+(i+1)+'\n'
jailh.splice(i,i+1);
}
isChecked=1;

dwindow.text +="Deleted"+ '\n'
dwindow.text +="Current Length! " +String(jailh.length)+ '\n' ;
myarray.text=jailh.join("\n");
break;
}
}
if (isChecked==0){
jailh.push(Mymine);
dwindow.text="Current Length " +String(jailh.length);
myarray.text=jailh.join("\n");
}
}

]]>





































Basically this is a series of checkboxes that are pulled from an XML using an HTTPService call, then when checked they are added to an array... if the are checked again they are looked up for a match in the array, if there is a match the values are deleted.

Hopefully this will help someone, I know that if I had found such an example It would have saved me hours!


Thanks!

Alejandro

Friday, June 1, 2007

Finding out id of last inserted record using DBI+perl+MySQL

Countless times... and i mean COUNTLESS times i have encountered the pitfall of.... how to find out the value of the autoincrement field of an insert statement, or to put it in layman terms: How do i identify that last insert i did?

Well the answer had been smiling back at me the whole time. Those smart people who wrote the perl DBI::Mysql module had thought of that and came up with mysql_insertid function.

Let's get to it!

$sql="insert into sdata(somedata) values(\"somevalue\")";
$sth = $dbh->prepare($sql);
$sth->execute();
$id = $dbh->{ q{mysql_insertid}};
$sth->finish();


Now $id holds the value of Id (my autoincrement field in that table).

A thing of beauty!! Hope this helps! bye!



Saturday, April 7, 2007

Forgotten Basic Bash Tools (and some obscure tips)

Wow, i did not realize it had been so long since my last post. For all of you out there that check my blog: sorry. In my own behalf I was busy busy getting engaged and a couple of life altering ordeals. And since this is not related to Linux (Auuu Auuu! (....just watched 300, if you watched im sure you have laughed there!)) I will not extend myself there.

Ok, so I know that most people that want to become a Linux/*NIX/Darwin "expert" immediately dive into the bare bones essentials like how to change directory, rename files... and then crash course into some scripting program like php, ruby, or my weapon of choice perl, and that is that. But they miss a lot of the subtle and beautiful programs included with most distros. Some of them have been around since there very first days of UNIX like, cat or tail and some made it later. But they are powerful and elegant, just try doing some in front of your geek friends, you will earn their awe and probably some resentment along the way.

Lets get started:

tac: the evil twin brother of cat (which stands for concatenate, not the sneaky feline), and it does exactly what cat does (concatenate and print files to standard output) but with a twist. It does it in reverse. So by now like in a M. Night Shyamalan movie, things are all falling into place in your head. Just like cat, tac is the perfect UNIX philosophy example: It does ONE thing, and it does it well.

Ex:

[alex@galapago ~]$cat hello.txt
Hello
my
friends!

[alex@galapago ~]$tac hello.txt
friends!
my
Hello

Simple, elegant and functional, it has a couple of useful switches there. Mix it up with other bash commands, throw in some pipes and voilá you've got yourself a masterpiece.


split : Based on actual events-- Not so long ago i was asked to split a file into several files every million lines, and I thought to myself, "This is an easy job for perl" and indeed it was. Later on i found that i had missed this beautiful command named split whose function in to do exactly that (in less time)

For example

alex@alex-desktop:~/numbers$ cat numbers.txt
one
two
three
four
five
six

And we wish to split in files with three lines:

alex@alex-desktop:~/numbers$ split -l 3 numbers.txt div

div here repre

alex@alex-desktop:~/numbers$ ls
divaa divab numbers.txt
alex@alex-desktop:~/numbers$ cat divaa
one
two
three











Wednesday, February 14, 2007

Using Bluetooth with Nokia 6230i and Fedora


Sometimes I think about all those people carrying around this cool mobiles in their pockets, just because they are the newest ones, or have a nicer color... And most of the time much of the neatest features are just ignored. Take bluetooth for example. Most people don't know even what this is, or they just use it to exchange that funny ringtone... or that naughty wallpaper. But Bluetooth gives you so much more. Other good example is SyncML... and we could go on like this for ages.. as mobiles get more more advanced by the hour.

But right now we are here to create a simple connection with your distinguished, trustworthy and able Linux box and that sexy mobile of yours.

I am using a Bluetooth USB Dongle from D-link, and it works like a champ.

Just plug it into the linux box, and then type (in Fedora...)

#service bluetooth start

So the scenerario is set, lets move on.

Let's see if the dongle was correctly recognized:
#hciconfig -a
hci0: Type: USB
BD Address: 00:15:E9:69:F4:78 ACL MTU: 192:8 SCO MTU: 64:8
UP RUNNING PSCAN ISCAN
RX bytes:8070 acl:192 sco:0 events:481 errors:0
TX bytes:6708 acl:182 sco:0 commands:169 errors:0
Features: 0xff 0xff 0x0f 0x00 0x00 0x00 0x00 0x00
Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
Link policy: RSWITCH HOLD SNIFF PARK
Link mode: ACCEPT MASTER
Name: 'Linux BOX'
Class: 0x000100
Service Classes: Unspecified
Device Class: Computer, Uncategorized
HCI Ver: 1.1 (0x1) HCI Rev: 0x20d LMP Ver: 1.1 (0x1) LMP Subver: 0x20d
Manufacturer: Cambridge Silicon Radio (10)

everything looks nice.


Now be sure to turn on your mobile's bluetooth radio.

lets see if linux can find the device:

#hcitool scan
Scanning ...
00:15:E9:69:F4:78 Alex's Nokia

That strange HEX address is the unique identifier of your mobile. Think of it as your mobile's bluetooth radio MAC address.

lets ping the mobile from the server

# l2ping 00:E0:03:58:3F:35
Ping: 00:E0:03:58:3F:35 from 00:15:E9:69:F4:78 (data size 20) ...
0 bytes from 00:E0:03:58:3F:35 id 0 time 51.84ms
0 bytes from 00:E0:03:58:3F:35 id 1 time 40.27ms
0 bytes from 00:E0:03:58:3F:35 id 2 time 27.24ms
3 sent, 3 received, 0% loss

pretty neat huh? Ok so now we are sure that they can see each other... lets get them to talk\

# rfcomm connect rfcomm0 00:E0:03:58:3F:35
Connected /dev/rfcomm0 to 00:E0:03:58:3F:35 on channel 1
Press CTRL-C for hangup


That is it!!! now your mobile and computer with a little tweaking is able to exchange contacts.. files, connect to the internet using the mobile's GPRS service, send receive SMS, and so on... but we will get into this in some other post!


Good luck!!






Friday, February 9, 2007

Finding large files in a linux filesystem

This is a small, "note to self" kind of post. Sometimes it is useful to know what files are taking up the most space in our filesystem. Very useful under stressful times like when your server has a 100% filled partition. It can be done this way:

find / -size +10240000c -exec du -h {} \;

This will find files larger than 10Megs.

Now i won't forget next time!!!

Hope this is useful for you as well!

Thursday, February 8, 2007

Hamachi!


Every few months (even years) i stumble into this piec
e of software that makes me feel like i'm receiving my Atari 2600 for Xmas all over again. HAMACHI falls just right under that category. Unlike its distant cousin Tamaguchi it is not a little device with an animation that you have to feed, take care and play with...

Quoting their website: "Hamachi gives you a LAN ove
r the internet." As easy as that. And what I like about it the most is that it plays well with others. It runs in Windows, Mac OS X, and Linux. What more can you ask for? (Ok,ok.ok... i can already hear some BSD, Solaris, Palm OS people shouting...).


Check out my current setup:


No matter where i am with my laptop... i can always reach all of my files, even from the Mac G5! So far so good. I've been testing and the speed is not that bad (no Formula 1 trophies either...).

Windows installation is pretty straight forward... so lets focus on getting hamachi running on the linux box.

You may download the package from here

As of this posting the version for linux file is hamachi-0.9.9.9-20-lnx.tar.gz

let's play:

#tar -xvzf hamachi-0.9.9.9-20-lnx.tar.gz
# cd hamachi*
#make install
#tuncfg (for MacOS users... there is an extra step involved so you can get a tun device in Darwin)
# hamachi-init
Initializing Hamachi configuration (/root/.hamachi). Please wait ..

generating 2048-bit RSA keypair .. ok
making /root/.hamachi directory .. ok
saving /root/.hamachi/client.pub .. ok
saving /root/.hamachi/client.pri .. ok
saving /root/.hamachi/state .. ok

Authentication information has been created. Hamachi can now be started with
'hamachi start' command and then brought online with 'hamachi login'.

# hamachi start

# hamachi login
Logging in ....>....... ok (this is were you connect to the hamachi network)


Now you will need to create your own network, in this example im creating the "mytestnetwork1" network with a password of "mypassword". (I've been blessed with creativity this morning).

#hamachi create mytestnetwork1 mypassword

Ok, so we should name our linux server something, lets call it CONAN (the comedian, not the barbarian).
#hamachi set-nick CONAN
#hamachi go-online mytestnetwork1
password:*******

lets get everyone names...

#hamachi get-nicks
#hamachi list

There you will notice that you get a 5.x.x.x IP address... that is your address on your Hamachi network. Now you can use that IP to use shared drives... get webpages... whatever you want from your network!


Cool huh? try it out!

Wednesday, January 24, 2007

Creating FC5 a rescue disk in USB stick from windows


All of us who love linux have this little pieces of it we do not dare to try, maybe we think we don't need to know how it is done, maybe it just looks too complicated to be bothered, maybe we are rushing to the nice, more exciting parts of our new Linux book and ALWAYS skip this one part. Why.. we will never need it?... WRONG! sooner or later we will need to know that piece of info.

In my particular case we are talking about creating a Rescue/Boot disc for linux (Fedora Core 5).

Why would you ever need to know this? I can think many scenarios. USB are for more portable and withstand more heavy usage than CDs and DVDs, so they are more likely to be ready when disaster strikes. Not all servers/desktops/laptops have CD-ROMs, even less likely they will have DVD-ROM drive. Normally I use a rescueCD+Net install from DVD. It is a fact that the more media is required on an installation, more things you have to go sour. (that LAST 4th CD of Fedora has a tiny scratch... and there goes those 30 mins of your life...).

So let's get to it:
In your distro you will find : \Images\bootdisk.img this contains ALL the necessary files required for the rescue media to be booted. Sadly it is not as easy as coying the file to the USB Drive. But it is not that hard either.

If you are on linux you could just do this:

dd if=diskboot.img of=/dev/sda1

et voilá! but as Mr. Murphy will have it, the server that is down will be for sure the ONLY one with linux and a DVD.

So, in your laptop you have windows installed, and a DVD ROM... (yes you know you have windows there!! admit it!)

Normally, you can read around and they will suggest that you use the rawrite utility, or it nice GUI cousin rawwritewin, but sadly those two
will only write to a Floppy Drive or will complain that they have no info in the sectors of that drive. So we are in trouble. Please stand up, and cheer our saviour:


dd for win which you can find here

Go ahead, download that and extract it to a directory, after that just type:

dd if=D:\diskboot.img of=\\.\E:

where D drive is your DVD-ROM and E: is your USB stick.

And you are ready.

Remember not all BIOS are created equal, be sure to check the boot order and see if USB is available at all. Else just like me you would have just wasted some time creating your own
USB FC5 rescue disk!!

Hope this help!! See ya!












Sunday, January 21, 2007

I deleted zlib in a live environment!

I really don't know what the BIG deal about RHEL is; if anything i have found it to be annoying, HARD to upgrade (rpms are scarce). Definitively CentOS is wiser choice. Try upgrading to PHP 5.2 on RHEL 4! now... just for kicks try the upgrade on a X86_64 platform. I have been going crazy about this. Some good soul posted his experiences on a 686 platform:

http://www.jasonlitka.com/2006/11/30/upgrading-php-520-rhel-centos/


I have being trying to get all the dependencies for X86_64 and it is very very hard. While i was going crazy about getting a succesful spec build:

rpmbuild -bb php.sec

I get many many many dependencies issues (sqlite,mysql-dev,libpng,etc,etc,etc,etc) I bump that it is complaing about a libc flag not being there "-fPIC", I start searching the web for references for this happening to someone else, and i find several places pointing to a solution by simply updating the zlib libraries.


Never I suspected i was about to venture into dark, scary, uncharted territory. So being as naive as i can i write

rpm -e --nodeps zlib(dont remember the full name)


Let the fun begin:
First i notice that wget, ssh, up2date,rpm or mostly anything else for that matter is working anymore, uh oh. Let me say it again: Uh oh.

Funny thing, this is a colocation server. I am i a different Country, i have no access to the server. I call up the people at The Planet, they suggest i get an OS reload. NOT a choice, there is a lot of valuable data there that would take DAYS to restore since i would have to upload everything again. (whole story being that i HAD to build the .rpm there since there is no php 5.2 rpm for RHEL and i dont have access to another server with the same characteristics).




I noticed that ftp is about the only service currently working. So i went to grab zlib at

http://www.zlib.net/

Since gunzip or tar are not working i had to extract the files in some other server and upload the files already extracted.

After that i cross my fingers and write

./configure

Nope, not working so i read further and notice that i should write for my system

./configure --shared --lib=/usr/lib64


I got away with this one easily... scared but no harm done.

I hope this helps someone. I learned that if you get a collocation server... do yourself a favor and get NAS.


Bye!


Sunday, December 10, 2006

Asterisk + Freetds +MSSQL 2000

If you are anything like my surely you like to steer clear of all things NOT opensource (i.e. Microsoft) althought I got to admit i have always had a soft spot for Solaris (mmm thinking about it I don't were they stand these days in OpenSource world...) but there comes time that it is unavoidable to work with some of this stuff.

One of the things I love about linux is that it will handle all/most things you throw at it and MSSQL Server integration is one of those, here is my recipe:

  1. freetds , an open source Tabular Data Stream implementation. TDS is the protocol that databases such as Sybase and MSSQL "speak", there are many versions of it, MS SQL 2000 version is TDS 8.0
  2. DBD-Sybase Perl Module, although the name can seem misleading, since Sybase and MSSQL both "speak" TDS it allows the Perl DBI driver to work with both. As of this writing the latest version is 1.07
In this post I am asuming you already know how to work with AGI scripts, we will use Asterisk::AGI Perl module in this examples. I will devote a post for this later on.. for now you might want to check this out.

Ok lets start cooking.

freetds part
#tar -xzvzf freetds-stable.tgz
# cd freetds-0.64
#./configure --prefix=/usr/local/freetds --with-tdsver=8.0 (we will be installing inito /usr/local/freetds dir, and since we will be using it for MSSQL we us version 8.0 of TDS)
#make
#make install

DBD-Sybase part
#tar -xvzf DBD-Sybase-1.07.tar.gz
#cd DBD-Sybase-1.07
#export set SYBASE=/usr/local/freetds
#export set LD_LIBRARY_PATH (this is REALLY really really important step, it will save you dealing with the Dynaloader.pm error which took me a LONG LONG LONG time to figure out... i wish i had this recipe in my hands a few years ago...)
#./configure
#make
#make install

Ok, now I will throw out a little example on how to use this with Asterisk::AGI this next program connects to MSSQL and checks if the callerid of the calling party is a client.

alright aaaall together now:

#!/usr/bin/perl
use Asterisk::AGI;
use DBI;
$AGI = new Asterisk::AGI;
my %input = $AGI->ReadParse(); #Read in the initial data
#Connect to MSSQL Server
$user = "user";

$passwd = "password";
$dbh = DBI->connect("DBI:Sybase:server=10.1.34.0", $user, $passwd, {PrintError => 0});
$dbh->do("use Clients");
unless ($dbh) {
die "Unable for connect to server $DBI::errstr";
}
$AGI->verbose("Checking IF client",1);
$sql = "select count(*) from clients where ClientPhone=\"$input{callerid}\"";
$sth = $dbh->prepare($sql);
$sth->execute();
while ( my @row = $sth->fetchrow_array( ) ) {
$isclient=$row[0];
}
$sth->finish();
$dbh->disconnect();
if ($isclient > 0)
{
$AGI->verbose("$input{callerid} is a client!!",1);
$AGI->stream_file('you are a client');
}
else
{
$AGI->verbose("$input{callerid} is not a client!!",1);
$AGI->stream_file('you are not a client');
}




Pretty neat huh? I thought so!! Good luck!








Thursday, December 7, 2006

/bin/rm: Argument list too long.


"what, a savvy guy like me having problems with a simple shell command like rm? Pleaaasee!!"


Linux always finds a way to make you humble again. Just when you begin to get cocky it has a way of slapping you behind the head and keeping you alert again. I just had such an experience...

while trying to delete a big directory (big as in many files....) i do this:

#rm -fr 200611*

and i get this:

/bin/rm: Argument list too long.

oh the agony... the intrigue... but don't worry... there is a way around this (as everything else in Linux).


strange as it seems most of the /bin/ commands have a limit of items it can process in order to avoid buffer overflows...so now it is time to ask our dear bash shell to help us out.

try this instead:

#find . -name '200611*'|xargs rm

this very simple script finds all files in the current directory which names starts with 200611 and then deletes them, passing the results via xargs and deleting them. xargs takes care for us to process batches of information big enough so the system may handle them without causing a buffer overflow. If more than one batch is needed, no problem xargs takes care of this.


Got slapped in the back also? kinda makes me feel in kindergarten all over again... don't eat the crayon...don't eat the crayon...



Friday, December 1, 2006

Modifying Asterisk Meetme enter/leave sounds Part 2

Ok, so im still dealing with modifying app_meetme.c enter/leave sounds. It is getting a little bit complicated.

I've found a little ms dos/windows utility called bin2h , you can find it here:

http://jonripley.com/windows/Software/bin2h/

this utility successfully converts binary files (audio, images) into a hex array that can be used in C.

Now my problem basically lies in understanding in which sound format i should record the sounds i want to be played during the enter/leave process of the conference.

The original enter.h files has this commented in the very beginning of the file:
00001 /* 00002   * U-law 8-bit audio data 00003   * 00004   * Source: enter.raw

Pretty easy huh? .raw file... 8 bit U-law? WRONG... i can't seem to get this sound file right..

with sox I'm trying the following command

sox audio.wav -r 8000 -c1 audio.ul

then from windows I do: bin2h audio.ul audio.h, replace/rename this into enter.h... recompile asterisk source... and then

NOTHING...

but we are still working on it.. so hopefully we get some results in part 3.


Bye!