Search Results: "js"

5 September 2013

Gergely Nagy: What's cooking in syslog-ng 3.5?

The first alpha of syslog-ng 3.4 was released more than a year ago, and the first stable release earlier this year, development on syslog-ng 3.5 has been going on steadlily since then, with a lot of interesting features and changes pouring in. While the 3.5 release will not bring as many overwhelming changes as the previous two releases did, the sheer number of improvements is still substantial. Our focus was on smaller developments all over the place this time, instead of big sweeping changes. In this post, we will go over most of these features, with use-cases, examples and a few words about why they are so useful and awesome.Multi-line support, new destinations, new template functions, type hinting, unit suffixes, and other things. Read on, and be amazed!These are only bigger features, there has been a lot of small tweaking going on, and of course, all of the fixes that went into prior versions will also be in 3.5 too, and there's still a chance that something else may find its way in before the feature freeze.Multi-line supportOne of the major new features in the 3.5 release will be support for multi-line messages, a feature that has been available in syslog-ng PE for a good while, and which has been ported to and improved upon to the open source edition. Two variants of multi-line are supported, which will be detailed below. Both of them are available for the file() and pipe() sources only.Indented multi-lineThe easiest variant is indented multi-line, where each line can be followed by others, indented by whitespace, and the message continues until the first non-indented line. This is the format used by the Linux kernel too, from version 3.5, for /dev/log. This type of multi-line can be used as follows:
source s_multiline   file("/path/to/file" multi-line-mode(indented));  ;
Consider that /path/to/file has the following content:
First line
 Continuation 1;
 Continuation 2;
Second line
With the indented multi-line-mode() setting, this would turn into two log messages:
First line\n Continuation 1;\n Continuation 2;
Second line
Regexp-based multilineIf multi-line input is not based on indentation, one can use the regexp multi-line-mode() instead, which makes two new settings available: multi-line-prefix() and multi-line-garbage(). These can be used to define the start and the end of a log message: any string between a the beginning matching prefix and a matching garbage will be considered a single message. That is, the prefix will be included, the garbage will not be: it will be discarded.To illustrate:
source s_multiline  
 file("/path/to/file" multi-line-mode(regexp)
                      multi-line-prefix("^prefix")
                      multi-line-garbage(" garbage$"));
 ;
If the source contains these lines:
prefix message
continuing garbage
This will turn into the following log message:
prefix message\ncontinuing
New destinationsIt would be pretty hard to do a syslog-ng release without new destinations, and with 3.5, we will have three of them!STOMPWhile we had AMQP before, we now have a STOMP destination too, so we can stream logs to any STOMP server, with a few simple lines:
stomp(
 host("localhost")
 port(61613)
 destination("/topic/syslog")
 routing_key("")
 persistent(yes)
 ack(no)
 username("someone")
 password("something")
 body("This is the body! YAY! Here's a message: $MESSAGE!\n")
 value-pairs(scope(nv-pairs, syslog-proto, selected-macros))
)
Of course, none of these settings need to be set, you can just use the defaults, and it will just work!RiemannDid you know that syslog-ng is far more than a log collector and processor? No? You do now. When you have access to a lot of logs, and a tremendous amount of power in parsing them, you can use these tools for monitoring easily! And when we're talking monitoring, riemann is a great asset in our toolbox, and with the new destination, we can easily forward metrics to it:
riemann(
 server("localhost")
 port(5555)
 host("$HOST")
 service("$PROGRAM")
 description("$PROGRAM pids")
 metric(int("$PID"))
 ttl(300)
);
Of course, the above is a very silly example, it would make much more sense to extract data from a log message instead, but this will serve as an example.New template functions
$(upper-case TEXT...), $(lower-case TEXT...)
To turn some text into *upper-* or *lower-case*, these two template functions come in handy. They simply turn all their arguments into the respecitve case.
$(delimit DELIMITERS NEW-DELIMITER TEXT)
Sometimes one has a delimited string, where one wishes to replace the delimiters. This function does just that: give it a list of delimiters (you may need to quote it, if it contains whitespace), a replacement, and a text to replace delimiters in, and it does the rest. For example, to replace tabs and spaces with a vertical bar, one could write a template like this:
template("$(delimit \"\t \" \" \" $MESSAGE)\n")
$(env VARIABLE...)
Have you ever felt the need to check an environment variable from within syslog-ng? I did, and now I can.
Type hintingWhile syslog-ng supported sending log messages into various data stores and message queues for a while (SQL at first, MongoDB, JSON and AMQP later), even when those supported different types of data than strings, we could not do anything else. Until now. It is now possible - at places where it makes sense - to annotate templates with type hints, which the destination driver can optionally use. Type hinting is implemented for the mongodb() destination and the $(format-json) template function for now. When no type hint is specified, syslog-ng defaults to string.To add type hints, simply wrap the respective template with the hinted type, like this:
mongodb(
 value-pairs(pair("date", datetime("$UNIXDATE"))
             pair("pid", int64("$PID")))
);
Currently the following type hints exist: boolean (anything that begins with a t or 1 is true, anything that begins with f or 0 is false, everything else is an error), string, literal (same as string, but not quoted if it would be quoted otherwise), int32 (int is an alias for this), int64, and datetime. Only UNIX timestamps can be type-hinted to datetime, anything else will likely result in a casting error.It is also possible to control what happens when type casting fails: syslog-ng can drop the whole message, drop the property, or fall back to string. It can also do all of these silently:
options  
 typecast(on-error(silently-drop-property));
 ;
Using this feature with $(format-json) is very similary too:
$(format-json date=datetime("$UNIXDATE") pid=int64("$PID"))
With this feature in place, you can now store your non-string values with their proper types!Unit suffixesUnit suffixes make it considerably easier to set limits and describe numbers within the syslog-ng configuration. We no longer need to spell out sizes to the byte precious, it is now enough to write: log-fifo-size(200MiB). Now, syslog-ng will understand suffixes for kilo-, mega-, and giga-bytes, (K, M, G, respectively) either in base-10 or base-2 (with an extra i after the suffix). One can also omit the trailing b from the end.So, to set the log-fifo-size() to 2097152 bytes, one can simply use 2MiB. Or, to set it to 2000000, 2Mb. That's a whole lot easier, isn't it? No more counting zeros, no more silly typos in a ten-digit number, no more pain, but easily readable units!Miscellaneous featuresApart from the features above, there have been a lot of other changes and improvements in the code base:

2 September 2013

Daniel Pocock: Australia's Labor Party exposed spying on their own members

Australia's Labor Party claims to represent the little guy, advocating the interests of a wide slice of the population over the interests of those who might supposedly exploit them. In this latest blog I'll look at just how the Victorian state branch of the party is emulating the more sinister elements of monitoring and control that you would typically expect from marketers, spammers and the NSA. It makes you wonder, if they do this to their own members, how can Australia's government ever hope to rein in spammers or other undesirable practices? Europe has tried cookie laws and the right to be forgotten, while the ALP has taken these developments almost as a guide to exploiting their own most valuable resource, their membership. The email version of invisible ink Straight out of an email attempting to recruit party members to the federal election campaign, we find that the ALP's logo itself has been turned into a sinister tracking mechanism. Looking underneath the logo, there is a hidden tracking number attached to every message:
http://gallery.mailchimp.com/3021e68df9a7200135725c633/images/Email_Header_ThisisLabor.jpg
There it is, that big long code 3021e68df9a7200135725c633. On it's own, you may think this number can't do much harm. Think again. After all, as the filename says, "ThisisLabor". Reaching the grass roots by long distance email When a party member sees any of the images in the email or clicks any of the links, their email software or web browser sends a HTTP request to the ALP's outsourced tracking server in the United States. Here is an example of what that request may contain:
TCP Headers:
  SOURCE IP ADDRESS: 198.51.100.56
HTTP headers:
  GET /3021e68df9a7200135725c633/images/Email_Header_ThisisLabor.jpg
  HTTP/1.1
  Host: gallery.mailchimp.com
  User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20130515 Firefox/17.0 Iceweasel/17.0.6
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  Accept-Language: en-US,en;q=0.5
  Accept-Encoding: gzip, deflate
  X-Forwarded-For: 192.168.1.54
  Connection: keep-alive
These codes are all transmitted from the recipient of the email back to the ALP. Notice the tracking number is in the very first line of the HTTP request? These codes send many details to the tracking server. Just what is revealed?
  • What time the message was read
  • How many times the message was opened
  • Whether the message was read on multiple computers (perhaps it was forwarded)
  • The IP addresses reveal which network was used.
    • For people reading email at work or on wifi, the IP address reveals the name of the employer, it can be easily looked up in this public database. Here is an example querying one of the ALPs own IP addresses, 203.24.72.2
    • For people using an internet connection at home, the IP address reveals the service provider. There is more to it though: if one party member regularly visits another party member and uses their wifi, they will both appear to be using the same IP address and the party will be able to deduce that there is a connection between these two people.
  • The web browser name and version and the operating system name and version.
  • The language normally used on the computer
Crunching the numbers You may think that nobody would be interested in all that data or that it is even too much data for anybody to easily study. Think again. The ALP has outsourced processing of this data to an offshore firm that specializes in bulk email, MailChimp. After lecturing everybody about the dangers of outsourcing, the ALP has literally sold the farm (their own membership data) - to a foreign marketing company. Here are some of the claims MailChimp make on their web site:
"Dig even deeper with Subscriber Activity Reports, which give you a real time report for every subscriber s email activities: when they opened, what they clicked, and when they came back for more. You can even generate a list of people who didn t open, and send them a modified campaign."
That's right: if ALP members don't read their emails fast enough, they will send even more of them. Just who has access to this data? Well, the scope is quite broad. According to these rules, it is not only the dubious officials in the party's state office, but Labor Party regulations also list a whole lot of other officials who have access to some subset of the data: branch and FEA district committees, policy committees and maybe some trade union officials too. Once you start to contemplate this, it becomes apparent that the probability of somebody profiling members at an individual level is very real. On the other hand, those rules clearly do not permit the state branch to process the member's data offshore. Double whammy In fact, even MailChimp is further outsourcing the data. When receiving an image from the booby-trapped link in the email, we receive a response like this:
HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: 407474
Connection: keep-alive
Date: Wed, 10 Jul 2013 06:25:55 GMT
Last-Modified: Tue,  03 Sep 2013 04:05:37 GMT
ETag: "df9a7200135725c6331369a22"
Accept-Ranges: bytes
Server: AmazonS3
Age: 62097
Via: 1.0 e71fe855f29513f54a41e213fe653fb1.cloudfront.net (CloudFront)
X-Cache: Hit from cloudfront
X-Amz-Cf-Id: S2V2aW4gUnVkZCBpcyBhIGJhZCBib3kuCg==
which contains more tracking numbers and clearly indicates that the data is being processed in the massive AmazonS3 (a.k.a Amazon online bookstore) cloud platform. Thanks to cloud computing, there is considerable scope for cross-referencing records across other web sites. The IP address becomes a magic key, allowing a range of sinister forces to join the dots at the click of a button and profile the whole private and professional identity of any individual ALP member. Googling ALP members It doesn't stop there however, after following these links a victim will eventually end up on one of the ALP's own web pages. Looking through the HTML code underneath http://www.viclabor.com.au is very easy, in most web browsers, you can just press Control-U to see what is hidden away in the shadows. Buried in the code, I found this little gem:
  var _gaq = _gaq   [];
  _gaq.push(['_setAccount', 'UA-35325645-1']);
  _gaq.push(['_trackPageview']);
  (function()  
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
   )();
This may be even scarier: it's a JavaScript code that channels all access to the ALP web site into an outsourced tracking system provided by Google. Google can now cross-reference ALP members against their Gmail accounts, their friends and the topics they search for to further profile the type of advertising they should be exposed to. Google, like any private company, has a loyalty to its shareholders and the laws of the country where it is domiciled. Will that coincide with the best interests of ALP members in Victoria? Australia's other parties: samples needed Do you have similar communications from Australia's other political parties? Please send them to me and I'll be happy to examine them for similar shortcomings.

Dmitrijs Ledkovs: My Debian Activities: Multiarch & upstart on kFreeBSD hacking

Looks like there is a recent trend to publicize one's debian activities, so I thought I should join in =) Not so sure if MDA acronym would work for these types of posts...
MultiarchI have been working on multi-arching additional libraries. In particular I am working on multiarching boost libraries. At the moment boost1.53 multiarched libraries are uploaded in the experimental, and I am still working out the quirks with those. At the same time I have submitted a patch to multiarch libicu-dev, which has been accepted by the maintainer and is currently waiting in new queue. This brings us closer to multiarching all of boost libraries. But as it has been pointed out at the Multiarch BOF at Debconf'13, one doesn't have to wait for dependencies (be it libs or lib-devs) to be Multiarched before multi-arching your own library. If you do it right (put all or arch-specifi headers in multiarch location, and place libraries in multiarch location, split utilities into a separate package), you can go and multiarch your libraries ahead of time. Maybe it's time to default to debhelper 9 in dh-make, and default to multiarch locations for all libraries?

Boost also has libraries which depend on mpi, and at the moment that's not multiarched. I'm not sure if there are additional considerations there given the support for alternative mpi implementations in Debian.

Boost also depends on libpython. At the moment it's shipping libboost_python-py2.7.so & libbost-py3.3.so, with a libboost_python.so symlink to libbost_python-py2.7.so. I do wonder if it's a sensible approach, or should the boosty_python library be simply shipped in arch specific & python implementation specific paths e.g. /usr/lib/pythonX.Y/config-X.Y$(abi_tag)-$(DEB_HOST_MULTIARCH)/ that way we'll be able to support python debug interpreter in python_boost. I guess I should seek expert opinion on other multiarch wizards.

In addition to boost, I've now started looking at qmake and how it handles multiarch. At the moment, it doesn't handle it much. All paths are statically copied around and hard-coded in each module qmake provides. I have now been working at abusing qmake's $$system to call into dpkg-architecture, and actually choose native or cross compiler & adjust settings and paths to Qt libraries. There are a couple of bugs to fix, but I should be able to propose a "debian-multiarch" qmake spec soon. Such that in calls dpkg-architecture & properly adjust compilers & locations for the DEB_HOST. qmake by the way has its quirks. For example all variable assignments seemed to default to be "by value" & not "by reference" (i.e. upon assignment all variables on the right hand side get expanded and the literal string is stored, instead of storing $(prefix)/lib/$(arch), and evaluating that later.) Hence my current qmakespec is less elegant than I hoped.
upstart on kFreeBSDFreeBSD 9.2 and up have implemented the wait6 and with it waitid is also exposed. At the moment there are some differences between glibc and FreeBSD waitid usage. I am not well versed in glibc, FreeBSD and POSIX, but the bug at hand & POSIX reference lead me to believe that POSIX is slightly ambiguous about it.

Why is waitid support is interesting? Well, kFreeBSD/libc maintainer in Debian is working on exposing it with/after (e)glibc2.18 is in Debian, which will remove one more blocker from porting Upstart to kFreeBSD. To this extend, I have in the mean time setup FreeBSD & kFreeBSD virtual machines and got libnih to compile on both (sans waitid on kFreeBSD). One of the optional upstart's features is to use inotify to spot & reload configuration files, at the moment I haven't ported that functionality to use native kevent/kqueues (EVFILT_AIO) instead I have cheated and packaged for Debian the Google Summer of Code 2011 project libinotify-kevent which provides inotify compatible API, implemented with kevent. Which is kind of the reverse strategy of libkqueue and/or libevent. It would be interesting to see kernels and/or those libraries to unify/standartise on common APIs. Unfortunately, it still seems like using native API for each kernel is best to avoid dependencies and leverage all features and semantics. Nonetheless I did package it for now. To further progress with actually porting upstart, I'd like to get my hands at (e)glibc 2.18 compiled for kFreeBSD with waitid patches. I got pointers to the patches, but I haven't yet succeeded at compiling (e)glibc with those applied. So no upstart booting kFreeBSD VM yet, but rather work in progress. It's quite fun. It's been years since I have touched a FreeBSD boxes and it's first time me using kFreeBSD. The semantics, differences and benefits of each do shine and it's a promising platform.
Multiarch on kFreeBSD?
Given the excellent multiarch implementation on Debian and sophisticated Linux Emulation Layer on FreeBSD kernel, I was half expecting the following to work:
  • on kFreeBSD enable linux i386/amd64 repository
  • apt-get install hello:i386
  • $ hello
But unfortunately this confused kFreeBSD, since it didn't find ELF tags and linker didn't seem to load the right libraries any more =( Not sure if this issue has been raised before, but I think it would be awesome if FreeBSD Linux Emulation Layer worked transparently on Debian/kFreeBSD multiarch system.

28 August 2013

Lior Kaplan: Hello free PHP JSON extension

I ve noticed that my post from three months ago ( Bye bye non-free PHP JSON extension ) was quoted quite often (thanks (: ). But I also noticed that most people didn t read the post fully, and didn t see the replacement package. Hopefully the title of this post will correct that impression. I d like to indicate the existence of the php5-json package. It s part of Debian unstable since June 2013 and testing (jessie) since August 2013. Users who wish to build the free extension on their own are welcome to download it from PECL at http://pecl.php.net/package/jsonc . It s a good chance to thank Remi Collet for his work on this replacement. I m happy that the main Linux distributions have already adopted it.
Filed under: Uncategorized

26 August 2013

Jose Luis Rivas: MongoDB: $pull from an embedded document array

TL;DR: db.collection.update( _id: 'x' , $pull: embedded_doc: _id: 'y' ) Queries are wrote for the mongo shell Dot based access If you have been using MongoDB for some time, then there are big chances that you will know the "dot-based access" on the find queries. This is the easier way to write those queries and will probably want to keep using that. Like:
db.collection.find( _id: 'x', 'embedded_doc._id': 'y' )
The thing is that does not work with everything, like: Arrays of embedded documents! Little example schema Let's suppose the following little schema (written for Mongoose): A = new Schema( w: String, x: String ); Document = new Schema( embedded_doc: [A] ); The collection of Document is called documents. Updating arrays If the arrays are not embedded documents I can actually just use a regular update like with any other field combined with a $set and change all the array like:
db.documents.update( _id: 'x',  $set:  array: [
   a: 1 , 
   a: 2 , 
   a: 3 
] )
And using conveniently $pull and $addToSet. But when it comes to embedded documents the history is very different. You can't make a simple $set because it will give you an error related to ModId which you can't change. So you really need to use $push, $addToSet, $pull and it's friends. So all those you can do it as in the manual, but what if you want to make a $pull over an array of objects and w and x are not unique? Well, that's why you probably made them an embedded document! Then you have the _id and you try to use the dot notation like:
db.documents.update( _id: 'x' ,  $pull:  "embedded_doc._id": 'y' )
And it looks good, except that it wont work. You have to use the complete syntax like:
db.documents.update( _id: 'x' ,  $pull:  embedded_doc:  _id: 'y' )

24 August 2013

Marko Lalic: PTS Rewrite Project Status

The rewrite has already achieved some of the major goals which have been set in the beginning, as well as made some changes and improvements along the way. Some of the major points of the new system implemented so far will be presented here.

    Tasks framework
    The current PTS implementation regenerates the HTML pages for all packages a few times per day. A goal of the rewrite was to make smaller incremental updates possible so that the information displayed for each package can be much more dynamic.

    In order to allow incremental updates, it is necessary to consider the situation where updating some information should trigger an update of other information.

    This is where the tasks framework comes in. It allows developers to define a task with a list of "events" that it produces. An event can be triggered by any change to shared information or anything else the task would like to signal. Each event is identified by a simple unique string name. Events can also contain arbitrary (JSON-serializable) objects. Other than events that it produces, a task defines a list of dependencies events it depends on.

    When a single task should be executed, the tasks framework uses this information to build a dependency graph (a DAG) and executes the tasks in topological sort order, making sure each task runs only after all tasks which could raise an event it depends on have finished. It automatically makes the raised events available to the task so that it can access the extra data. Tasks for which no event was raised are skipped.

    Such execution of a task along with all its dependencies is called a Job. A Job's state is persisted to the database after each task completes its operation. This allows Jobs to be continued if there is an unexpected error causing it to terminate.

    So far, the tasks framework has already proven useful. For example, there are tasks which extract some package information to a denormalized model suited for directly displaying the data in the package page after a new package version is detected in a repository. Other examples are tasks which update standards-version warnings (after a new package version is detected) and the news generation task based on various detected changes to the packages (new source version, version removed from repository, version migrated to another repository).

    Vendor-specific customizationAnother goal of the rewrite was to make the PTS less Debian-specific. This is so that derivatives could easily deploy their own versions of the PTS. The idea is to have a number of core PTS services which alternative deployments can customize and augment.

    The simplest way vendors can customize PTS is by changing some of the local settings values. An example of this would be changing the PTS_VENDOR_NAME which leads to this name being displayed in any part of the system.

    This is fairly uninteresting since the information is always static. What is more interesting is when the vendor should provide different information based on some context, e.g. package name, received message, etc. This requirement led to the concept of the vendor app with a rules module.

    Various core parts of the PTS specify hook functions which different vendors can implement to provide customized behavior of the core component. Some examples are:
    • providing URLs to a developer information site (e.g. http://qa.debian.org/developer.php in Debian's case) based on a developer's email
    • providing a URL to a bug tracker for a particular package (based on the package type and bug category type)
    • providing additional rules to tag received package mails with keywords
    • providing additional headers to be injected in the forwarded package mails
    • providing a list of bugs which should be displayed in the bugs panel
    A settings value is set giving the full dotted path to the Python module containing the implementation of these hook functions.

    Vendor-specific featuresA step beyond customizing core features is for vendors to include their own specific functionality. The already described tasks framework allows for implementing custom data update/generation processes (optionally depending on core events). Furthermore, since a vendor-specific Django app is expected, it can contain any vendor-specific models which are managed just as the core models are (syncdb, migrations, etc. all work as expected). The last piece of the puzzle is displaying this information on the package page.

    Currently, all package information is provided in various boxes (general, bugs, links, etc.) which were named panels. The rewrite has made it possible to implement additional panels in a really elegant way.

    It is required to implement a class with some properties giving:
    • the panel's title
    • position in the page (left, center, right)
    • panel importance (higher importance panels are placed above lower importance ones in the same column)
    To generate the HTML for a package, two alternatives are allowed. The first is to provide a property which gives (explicitly marked safe) HTML output which is then included in the correct position verbatim. The second alternative, which is what should cover most needs and should be preferred, is to provide a property giving a template name and a property giving the additional context variables necessary to render this template. By using the power of Python properties, the context can be dynamically generated for each package by the panel. The PTS then makes sure to pass the correct panel's context when rendering its template and to include the rendered result in the final package page.

    Various convenience classes are implemented in the panel API, but those are better left to be read about in the panels API documentation.

    Changes from current PTSSome existing features of PTS were not simply rewritten to fit into a Django project, but also improved upon.

    One of the first such changes was reducing the number of confirmation mails sent by the email control bot to only one per received control mail (as per a wishlist PTS bug).

    Work started by Markus Wanner (see this bug) was expanded on and integrated with the new News model so that any inline GPG signatures found in the content of a news item are automatically extracted and the signers name displayed in the package page.

    The existing TODO and Probems panels have been merged into a single Action Needed panel. However, besides merging their representation in the package page, all the package issues are now represented as an ActionItem Django model which provides additional meta-data (item type, date created/updated, severity level) which could be used in the future to provide additional functionality (such as all packages with a certain issue type).

    The descriptions of the action items were also shortened from their current rendition, with the detailed description being moved to a dedicated item page. If Javascript is enabled in the user's browser, it can also be displayed in a popup.

    GUIThe graphical interface has seen some changes, however I hesitate to claim improvements. In my opinion, some of it is definitely better, more polished and more "modern" (for what it's worth).

    Still, this could benefit from more people getting involved in testing and providing feedback so that the design is polished to suit the largest number of users. For example, the padding between the panels is increased, which to me definitely looks better, however, it is possible that this introduces too much whitespace and reduces the information density below what some may expect.

    RecapOverall, I am quite pleased with where the project is currently. Most of the information provided by the current PTS has been reimplemented, with only a few smaller ones remaining. For now, since we are nearly entering the final month of GSoC, the development will switch focus from porting old features to the new PTS to adding in some new ones. Namely, user registration and account management is in the pipeline for the coming week. It entails features such as managing package subscriptions via the online interface (for multiple emails associated with the account) and sso.debian.org integration for Debian Developers.

    This post aimed to provide the most notable changes and improvements made so far to the PTS. In reality, there has been quite a lot of them and not everything is covered here. For more information, check out the PTS documentation which is updated weekly (corresponding to the weekly deployments) or the source code repository.

    The latest iteration of the PTS can always be found at http://pts.debian.net. The mail control interface bot responds to mails sent to control@pts.debian.net.

    Stay tuned for updates and be sure to check out pts.debian.net on at least a weekly basis to see new deployments in action!

    20 August 2013

    Chris Lamb: Thomas Fuchs on frontend Javascript frameworks in startups

    What you end up with is building a layer cake that doesn t add any value and slows down development. Especially when you re starting out and need to stay flexible you don t want to have too much code around and Rails is great for that. But adding a JSON API layer and basically a second application that runs on the client is annihilating this advantage for you.
    Source.

    17 August 2013

    Daniel Pocock: DebConf13: breakthroughs in OTP and WebRTC

    Saturday, 17 August was a day that saw groundbreaking new work revealed at DebConf13 and may have been a watershed moment in the emergence of WebRTC for the free software community.
    Fabian Gr nbichler, Daniel Pocock, Catalin Constantin Usurelu, Emil Ivov, Yana Stamcheva Advancing the use of One Time Passwords with free software Google Summer of Code (GSoC) student Fabian Gr nbichler has spent the summer enhancing oath-toolkit and dynalogin to support a more diverse range of One Time Password schemes. dynalogin's original 1.0 release supports vanilla HOTP and TOTP authentication schemes. Fabian's work has extended the framework to support the more generic and powerful OCRA approach. To find out about all the benefits this brings, I would strongly encourage you to review his slides and video presentation, with a demo where it is explained thoroughly. While there are existing hardware tokens that support HOTP and TOTP using this open algorithm (Gooze has been kind enough to donate some which were on display), the mutual challenge-response schemes are yet to be widely supported in hardware and this means that Fabian's work is now at the cutting edge of development in this area. WebRTC: premium voice/video chat in modern browsers, no plugin required Another member of Debian's GSoC program, Catalin Constantin Usurelu helped organise and run one of the must-see sessions of DebConf13 (video available). In a demonstration that had all the hallmarks of a magic show, Catalin and I took random members of the audience and invited them to wave a magic wand over their web browsers and effortlessly turn them into Skype-busting softphones. As the grand finale, we took Wookey's blog and showed him how to add a WebRTC "call-me" page in less than 20 seconds, less time than it takes to hand over all your private data to the registration process of those rather uncomfortable alternatives. Anybody else seeking to duplicate this effort is encourage to review options like Drucall for Drupal or just directly use JsSIP Jitsi and the Jitsi Video-bridge The grand-finale of the DebConf13 real-time communications track was our guest speaker, Emil Ivov, founder of the Jitsi softphone project. Jitsi itself has recently been accepted into Debian and is easier than ever before to install and use. Emil's talk (video and slides available) went into some detail about the cutting edge development activities of his team, particularly the new Jitsi Video bridge Subsequent to the talk, we had some out-of-bands discussion about ways to potentially integrate Jitsi Video bridge with the open source dvswitch system used to produce streams and recordings from free software events such as DebConf and FOSDEM. It is hoped that this will provide an additional option for remote participation at free software events of all sizes. Upcoming events Emil and I have been invited to participate in the WebRTC Conference Paris 2013 in December. This will be an excellent opportunity to have further discussion about progress with WebRTC and do more to raise the compelling case for premium quality free software to meet the demanding needs of modern business communications. There are a series of talks for both technical and business-oriented audiences.

    13 August 2013

    Rémi Vanicat: Git annex and Calibre

    The debconf BoF about gitify all things make we to want to report some of my git-annex use cases. The problem Calibre is a ebook manager that is available in debian. I use it to maintain my library, but also to dowload every day an epub version of a French newspaper and then put it on my kobo. Configuring git annex for this I wanted to use git-annex, so
        $ git init
        $ git annex init "some useful name"
    
    But I don't want every thing in annex, because Calibre use some text file to save some metadata, so I used:
        $ git config annex.largefiles "include=* exclude=*.opf exclude=*.json"
    
    then lets add everything
        $ git annex add *
        $ git add *
        $ git commit -m "first commit"
    
    Calibre need read and write access on the its database, so let unlock it:
        $ git annex unlock metadata.db
    
    On my other computer I only need to do
        $ git clone $user@$host:Calibre\ library
        $ cd Calibre\ library
        $ git annex init "another useful name"
        $ git annex get .
        $ git annex unlock metadata.db
    
    The problem is that every time you will git annex sync, git annex will lock again the metadata.db, so lets unlock it automatically. I use git hooks, in .git/hooks/post-commit I have
        #!/bin/bash
        git annex edit metadata.db
    
    don't forget to make this file executable
        $ chmod a+x .git/hooks/post-commit
    
    Day to day operation
        $ git annex add .
    
    Will put new file into the annex
        $ git add .
    
    Will take care of the files that should no go into annex
        $ git annex sync
    
    Will make the repositories exchange informations about all this, and make remote change local
        $ git annex get .
    
    Will make remote book locally available Merge conflict You should not run calibre on the two computer simultaneously, or without syncing before it. If you do, you will have a conflict that git-annex will automatically solve by rename both of the file. You can then either:
    • Choose one. If no books have been changed or added on one of the computer, to use the other metadata.db will not make you loose any information
    • rebuild it. calibredb restore_database won't do it, but will tell you how to do it.
    Checking the library You can use calibredb check_library to check you library is correct. If you use git for it, it will always tell you that it is not correct: there is this author ".git" it doesn't know about. Just don't care about it. Maybe this can be solved by using vcsh but apparently vcsh+git annex it not well tested yet. Automatic stuff I use mr to automatically run all this, but some config could be done (I believe) to have git annex copy --auto do what it should. There are also the git annex assistant for this kind of automatic synchronizations of contents, but I don't know if my automatic unlocking of one file will break this. It might be interesting to find someway to unlock and lock the library only when running calibre, a simple script to launch calibre will do that. Note that each time you will lock and unlock, you will have a new commit in git.

    9 August 2013

    Daniel Leidert: Local link networking on Debian/Linux between server and workstation

    My network is based on wireless LAN, which is running at 54MBit/s. Transfering files between two systems therefor is not very fast. I could use wired connections, but cables would need to be pretty long to connect to the router. However the file server and the workstation are located near to each other and both have a free Gigabit LAN link. So why not connect these systems directly?Both systems run network-manager, whereas the server runs without a graphical/desktop environment. The file /etc/network/interfaces contains this entry related to the LAN devices on both systems:

    allow-hotplug eth0
    auto eth0
    To create the connection it is necessary to have the package avahi-autoipd installed. In a graphical environment is is then as easy as open the network(-manager) preferences dialog, create a new wired connection, change to the IPv4 Settings tab in its Options dialog and choose the Link local only method. Done.On the server I have no desktop environment. Therefor I wrote the necessary file /etc/NetworkManager/system-connections/LocalLink myself. The UUID value can be obtained via uuid -n 1:

    [802-3-ethernet]
    duplex=full
    mac-address=<MAC-address>

    [connection]
    id=LocalLink
    uuid=<value of: uuid -n 1>
    type=802-3-ethernet
    timestamp=0
    autoconnect=true

    [ipv6]
    method=auto

    [ipv4]
    method=link-local
    I restarted the manager via service network-manager restart on the server and the link came up too. The direct link was ready.A note: I was able to create the connection by using a patch cable because my cards are able to handle the situation. On older systems it might be necessary to use a cross-over-cable.I would really like to use bonding on the wired ethernet and the wireless devices. But the wireless connections are done via router whereas the ethernet connections are created via local link. I think, this is impossible. Any ideas/hints?

    8 August 2013

    Francois Marier: Server Migration Plan

    I recently had to migrate the main Libravatar server to a new virtual machine. In order to minimize risk and downtime, I decided to write a migration plan ahead of time. I am sharing this plan here in case it gives any ideas to others who have to go through a similar process.

    Prepare DNS
    • Change the TTL on the DNS entry for libravatar.org to 3600 seconds.
    • Remove the mirrors I don't control from the DNS load balancer (cdn and seccdn).
    • Remove the main server from cdn and seccdn in DNS.

    Preparing the new server
    • Setup the new server.
    • Copy the database from the old site and restore it.
    • Copy /var/lib/libravatar from the old site.
    • Hack my local /etc/hosts file to point to the new server's IP address:
      xxx.xxx.xxx.xxx www.libravatar.org stats.libravatar.org cdn.libravatar.org
      
    • Test all functionality on the new site.

    Preparing the old server
    • Prepare a static "under migration" Apache config in /etc/apache2/sites-enables.static/:
      <VirtualHost *:80>
          RewriteEngine On
          RewriteRule ^ https://www.libravatar.org [redirect=301,last]
      </VirtualHost>
      <VirtualHost *:443>
          SSLEngine on
          SSLProtocol TLSv1
          SSLHonorCipherOrder On
          SSLCipherSuite RC4-SHA:HIGH:!kEDH
          SSLCertificateFile /etc/libravatar/www.crt
          SSLCertificateKeyFile /etc/libravatar/www.pem
          SSLCertificateChainFile /etc/libravatar/www-chain.pem
          RewriteEngine On
          RewriteRule ^ /var/www/migration.html [last]
          <Directory /var/www>
              Allow from all
              Options -Indexes
          </Directory>
      </VirtualHost>
      
    • Put this static file in /var/www/migration.html:
      <html>
      <body>
      <p>We are migrating to a new server. See you soon!</p>
      <p>- <a href="http://identi.ca/libravatar">@libravatar</a></p>
      </body>
      </html>
      
    • Enable the rewrite module:
      a2enmod rewrite
      
    • Prepare an Apache config proxying to the new server in /etc/apache2/sites-enabled.proxy/:
      <VirtualHost *:80>
          RewriteEngine On
          RewriteRule ^ https://www.libravatar.org [redirect=301,last]
      </VirtualHost>
      <VirtualHost *:443>
          SSLEngine on
          SSLProtocol TLSv1
          SSLHonorCipherOrder On
          SSLCipherSuite RC4-SHA:HIGH:!kEDH
          SSLCertificateFile /etc/libravatar/www.crt
          SSLCertificateKeyFile /etc/libravatar/www.pem
          SSLCertificateChainFile /etc/libravatar/www-chain.pem
          SSLProxyEngine on
          ProxyPass / https://www.libravatar.org/
          ProxyPassReverse / https://www.libravatar.org/
      </VirtualHost>
      
    • Enable the proxy-related modules for Apache:
      a2enmod proxy
      a2enmod proxy_connect
      a2enmod proxy_http
      

    Migrating servers
    • Tweet and dent about the upcoming migration.
    • Enable the static file config on the old server (disabling the Django app).
    • Copy the database from the old server and restore it on the new server.
    • Copy /var/lib/libravatar from the old server to the new one.

    Disable mirror sync
    • Log into each mirror and comment out the sync cron jobs in /etc/cron.d/libravatar-slave.
    • Make sure mirrors are no longer able to connect to the old server by deleting /var/lib/libravatar/master/.ssh/authorized_keys on the old server.

    Testing the main site
    • Hack my local /etc/hosts file to point to the new server's IP address:
      xxx.xxx.xxx.xxx www.libravatar.org stats.libravatar.org cdn.libravatar.org
      
    • Test all functionality on the new site.
    • If testing is successful, update DNS to point to the new server with a short TTL (in case we need to revert).
    • Enable the proxy config on the old server.
    • Hack my local /etc/hosts file to point to the old server's IP address.
    • Test basic functionality going through the proxy.
    • Remove local /etc/hosts/ hacks.

    Re-enable mirror sync
    • Build a new libravatar-slave package with an updated known_hosts file for the new server.
    • Log into each server I control and update that package.
    • Test the connection to the master (hacking /etc/hosts on the mirror if needed):
      sudo -u libravatar-slave ssh libravatar-master@0.cdn.libravatar.org
      
    • Uncomment the sync cron jobs in /etc/cron.d/libravatar-slave.
    • An hour later, make sure that new images are copied over and that the TLS certs are still working.
    • Remove /etc/hosts hacks from all mirrors.

    Post migration steps
    • Tweet and dent about the fact that the migration was successful.
    • Send a test email to the support address included in the tweet/dent.
    • Take a backup of config files and data on the old server in case I forgot to copy something to the new one.
    • Get in touch with mirror owners to tell them to update libravatar-slave package and test ssh configuration.
    • Add third-party controlled mirrors back to the DNS load-balancer once they are up to date.
    • A few days later, change the TTL for the main site back to 43200 seconds.
    • A week later, kill the proxy on the old server by shutting it down.

    4 August 2013

    Ond&#345;ej &#268;ert&iacute;k: How to support both Python 2 and 3

    I'll start with the conclusion: making backwards incompatible version of a language is a terrible idea, and it was bad a mistake. This mistake was somewhat corrected over the years by eventually adding features to both Python 2.7 and 3.3 that actually allow to run a single code base on both Python versions --- which, as I show below, was discouraged by both Guido and the official Python documents (though the latest docs mention it)... Nevertheless, a single code base fixes pretty much all the problems and it actually is fun to use Python again. The rest of this post explains my conclusion in great detail. My hope is that it will be useful to other Python projects to provide tips and examples how to support both Python 2 and 3, as well as to future language designers to keep languages backwards compatible. When Python 3.x got released, it was pretty much a new language, backwards incompatible with Python 2.x, as it was not possible to run the same source code in both versions. I was extremely unhappy about this situation, because I simply didn't have time to port all my Python code to a new language. I read the official documentation about how the transition should be done, quoting:
    You should have excellent unit tests with close to full coverage.
    1. Port your project to Python 2.6.
    2. Turn on the Py3k warnings mode.
    3. Test and edit until no warnings remain.
    4. Use the 2to3 tool to convert this source code to 3.0 syntax. Do not manually edit the output!
    5. Test the converted source code under 3.0.
    6. If problems are found, make corrections to the 2.6 version of the source code and go back to step 3.
    7. When it's time to release, release separate 2.6 and 3.0 tarballs (or whatever archive form you use for releases).
    I've also read Guido's blog post, which repeats the above list and adds an encouraging comment:
    Python 3.0 will break backwards compatibility. Totally. We're not even aiming for a specific common subset.
    In other words, one has to maintain a Python 2.x code base, then run 2to3 tool to get it converted. If you want to develop using Python 3.x, you can't, because all code must be developed using 2.x. As to the actual porting, Guido says in the above post:
    If the conversion tool and the forward compatibility features in Python 2.6 work out as expected, steps (2) through (6) should not take much more effort than the typical transition from Python 2.x to 2.(x+1).
    So sometime in 2010 or 2011 I started porting SymPy, which is now a pretty large code base (sloccount says over 230,000 lines of code, and in January 2010 it said almost 170,000 lines). I remember spending a few full days on it, and I just gave up, because it wasn't just changing a few things, but pretty fundamental things inside the code base, and one cannot just do it half-way, one has to get all the way through and then polish it up. We ended up using one full Google Summer of Code project for it, you can read the final report. I should mention that we use metaclasses and other things, that make such porting harder. Conclusion: this was definitely not "the typical transition from Python 2.x to 2.(x+1)". Ok, after months of hard work by a lot of people, we finally have a Python 2.x code base that can be translated using the 2to3 tool and it works and tests pass in Python 3.x. The next problem is that Python 3.x is pretty much like a ghetto -- you can use it as a user, but you can't develop in it. The 2to3 translation takes over 5 minutes on my laptop, so any interactivity is gone. It is true that the tool can cache results, so the next pass is somewhat faster, but in practice this still turns out to be much much worse than any compilation of C or Fortran programs (done for example with cmake), both in terms of time and in terms of robustness. And I am not even talking about pip issues or setup.py issues regarding calling 2to3. What a big mess... Programming should be fun, but this is not fun. I'll be honest, this situation killed a lot of my enthusiasm for Python as a platform. I learned modern Fortran in the meantime and with admiration I noticed that it still compiles old F77 programs without modification and I even managed to compile a 40 year old pre-F77 code with just minimal modifications (I had to port the code to F77). Yet modern Fortran is pretty much a completely different language, with all the fancy features that one would want. Together with my colleagues I created a fortran90.org website, where you can compare Python/NumPy side by side with modern Fortran, it's pretty much 1:1 translation and a similar syntax (for numerical code), except that you need to add types of course. Yet Fortran is fully backwards compatible. What a pleasure to work with! Fast forward to last week. A heroic effort by Sean Vig who ported SymPy to single code base (#2318) was merged. Earlier this year similar pull requests by other people have converted NumPy (#3178, #3191, #3201, #3202, #3203, #3205, #3208, #3216, #3223, #3226, #3227, #3231, #3232, #3235, #3236, #3237, #3238, #3241, #3242, #3244, #3245, #3248, #3249, #3257, #3266, #3281, #3191, ...) and SciPy (#397) codes as well. Now all these projects have just one code base and it works in all Python versions (2.x and 3.x) without the need to call the 2to3 tool. Having a single code base, programming in Python is fun again. You can choose any Python version, be it 2.x or 3.x, and simply submit a patch. The patch is then tested using Travis-CI, so that it works in all Python versions. Installation has been simplified (no need to call any 2to3 tools and no more hacks to get setup.py working). In other words, this is how it should be, that you write your code once, and you can use any supported language version to run it/compile it, or develop in. But for some reason, this obvious solution has been discouraged by Guido and other Python documents, as seen above. I just looked up the latest official Python docs, and that one is not upfront negative about a single code base. But it still does not recommend this approach as the one. So let me fix that: I do recommend a single code base as the solution. The newest Python documentation from the last paragraph also mentions
    Regardless of which approach you choose, porting is not as hard or time-consuming as you might initially think.
    Well, I encourage you to browse through the pull requests that I linked to above for SymPy, NumPy or SciPy. I think it is very time consuming, and that's just converting from 2to3 to single code base, which is the easy part. The hard part was to actually get SymPy to work with Python 3 (as I discussed above, that took couple months of hard work), and I am pretty sure it was pretty hard to port NumPy and SciPy as well. The docs also says:
    It /single code base/ does lead to code that is not entirely idiomatic Python
    That is true, but our experience has been, that with every Python version that we drop, we also delete lots of ugly hacks from our code base. This has been true for dropping support for 2.3, 2.4 and 2.5, and I expect it will also be true for dropping 2.6 and especially 2.7, when we can simply use the Python 3.x syntax. So not a big deal overall. To sum this blog post up, as far as I am concerned, pretty much all the problems with supporting Python 2.x and 3.x are fixed by having a single code base. You can read the pull requests above to see how to implemented things (like metaclasses, and other fancy stuff...). Python is still quite the same language, you write your code, you use a Python version of your choice and things will just work. Not a big deal overall. The official documentation should be fixed to recommend this approach, and deprecate the other approaches. I think that Python is great and I hope it will be used more in the future.
    Written with StackEdit.

    2 August 2013

    Rapha&#235;l Hertzog: My Free Software Activities in July 2013

    This is my monthly summary of my free software related activities. If you re among the people who made a donation to support my work (167.67 , thanks everybody!), then you can learn how I spent your money. Otherwise it s just an interesting status update on my various projects. The Debian Administrator s Handbook After the successful crowdfunding campaign, I had a bunch of rewards to ship: I subcontracted most of the job but I had to take care of the books with dedication. I also dealt regularly with books/stickers coming back to the sender (due to invalid address or people not picking up their parcels in the post-office). After the rewards, we had to take care to actually finalize the liberation of the French translation. I merged the translations we had in Git and Roland updated/translated a few strings that weren t in the original book in French. Then I have put the book online. Last but not least, I started to work on updating the English book for Debian 7 (Roland started way before me) and we have put some updated chapters up for review. Debian France Elections. After Debian France s general assembly, the new board of administrators voted the officers: I have been re-elected as President, Sylvestre continues as Treasurer but we have a new Secretary in the person of Alexandre Delano . Welcome Alexandre! I did the administrative work to register the new board/officers in the Tribunal d instance and to give access to the internal git repositories to the new members. Galette. I also did a bunch of tests on Galette s new features that Debian France ordered to the upstream author. They should all land in the next upstream release due in the next weeks. \o/ Accounting. I worked on the accounting to bring it up-to-date so that Sylvestre can pick up the work from now on. We re learning how to best use ledger for our needs. PTS rewrite I continued to spend about 12 hours a week to mentor Marko Lalic who is rewriting the Package Tracking System. I m pretty happy with the results so far so I marked him as pass for the mid-term evaluation required by Google. You can have a look at the documentation and the web interface is starting to show some content. The email interface is fully working and I have configured the real PTS to forward all mails to our test instance (pts.debian.net) so that you can use the rewritten PTS for real-life work. Mail your subscription commands to control@pts.debian.net and start using it! Thanks to the test driven development methodology we re using, we re pretty confident that it works reasonably well! :-) I also packaged python-django-jsonfield (still in NEW) since Marko has been using this python module in his code, and filed bug #717900 on sqlite3 to raise a limit that we have hit with queries made by the PTS. Kali Linux I used the Calxeda Highbank node donated to Debian by Offensive Security to test the new -armmp kernel flavor on it. It seemed to work except for a missing network driver (filed in #717269). Misc Debian work Issues with social networks. With the move of identi.ca to pump.io, we don t have any possibility to auto-post status updates based on RSS feeds. Identi.ca s @debian account was also configured to push updates to the @debian account on twitter.com (and from there it was grabbed in the Debian page on Facebook). This is also gone so to limit the damage, I setup twitterfeed.com so that the twitter/facebook accounts continue to have updates). If you re looking for a development project, here s an area that is not well covered by free software! We need code to do what twitterfeed does and we need that code to also support pump.io. Dpkg work. It s been a long time since I last pushed some code to dpkg s git repository. I took care of reworking and merging a patch submitted by Steve Langasek to fix #716948 (an issue with dpkg-maintscript-helper rm_conffile messing with conffiles that the package no longer owns). Git mail notification. When I was still administrator of Alioth, I wrote git-commit-notice (a fork of Git s post-receive-email) and many packaging projects are using this hook script to send commit notices to mailing lists. This script has not been updated for multiple years and it started spewing warnings recently due to deprecated features in Wheezy s git. So I looked at updating it and while doing so I discovered a much better replacement with git-multimail. Thus I adapted git-commit-notice to work on top of this new script. The result has now been installed on git.debian.org (this is to be properly announced in the next DeveloperNews). Misc work. I packaged sql-ledger 3.0.5-1, forwarded #714739 on publican, and I participated in discussions to move the French Debian planets to planet.debian.org. Thanks See you next month for a new summary of my activities.

    10 comments Liked this article? Click here. My blog is Flattr-enabled.

    29 July 2013

    Gergely Nagy: HOWTO: JSON processing with syslog-ng

    Continuing my HOWTO series, in this article, I will explore how to set up syslog-ng to process JSON in various scenarios. We will touch the subject of interoperability, and have a look at multiple scenarios, in the hope that readers will find something similar to their own needs. There are many different ways in which one can plug JSON into their logging system, and it is very likely that I will not be able to cover it all within this HOWTO. However, I will explain the basics, and how to plug the pieces together, which should at least be a useful foundation to build even more complex systems onto.In essence, we will look at the following scenarios: raw JSON transport, JSON over syslog, JSON and syslog payload in the same stream. The documentation will cover both syslog-ng 3.4 and 3.5, where the 3.5 parts will be clearly marked as such. The 3.3 series do not have a JSON parser, and as such, is insufficient for most needs explored in this guide.In the default setting, the JSON parser will parse the MESSAGE part of an incoming log event, and place every key into a macro of the same name. If the incoming JSON is structured, it the keys will be converted to dot notation format:
    "deeper": "level": "very much so"
    In this case, one can access the value as $ deeper.level within a syslog-ng template.The parsed keys can be prefixed using the prefix() option of the json-parser. One can also change what the parser will receive as input by using the template() option.See the documentation for more information on these.Transporting raw JSONThe simplest scenario is to take a transport like TCP, and simply push raw JSON structures through, one each line, and have syslog-ng parse that to its internal representation. One can do all kinds of things with the data then: transport it further as JSON, store it in files, in a database - the possibilities are endless, but we will explore two scenarios.JSON on TCP, using syslog field namesThe first one is receiving JSON on TCP, using syslog field names, store the parsed stuff in a file (using the conventional format), and in mongodb.
    source s_tcp_json   tcp(port(10514) flags(no-parse));  ;
    parser p_json   json-parser();  ;
    destination d_file   file("/var/log/remote.log");  ;
    destination d_mongodb   mongodb(collection("remote_log"));  ;
    log  
     source(s_tcp_json);
     parser(p_json);
     destination(d_file);
     destination(d_mongodb);
     ;
    This needs a bit of an explanation: we use the no-parse flag on the source, because by default, the tcp() source expects a message that conforms to the old syslog protocol. We have raw JSON, and we need to tell the source that. The other elements should be self explanatory, I believe, with the exception of json-parser(): we give it no parameters, so it will not modify the keys in the JSON it receives, keeping them intact, as-is.For this reason, incoming messages need to have the same keys as syslog-ng normally would use internally: DATE, HOST, MESSAGE, and so on, like in the following example:
    "PROGRAM":"prg00000","PRIORITY":"info","PID":"1234","MESSAGE":"seq: 0000000000, thread: 0000, runid: 1374490607, stamp: 2013-07-22T12:56:47 MESSAGE...","HOST":"localhost","FACILITY":"auth","DATE":"Jul 22 12:56:47"
    JSON on TCP, custom field namesA more likely scenario is when we receive JSON, but not in a layout syslog-ng uses internally. In this case, we need to rewrite the message a little, and possibly use templates, depending on what kind of output we wish to use.Lets assume the incoming JSON has these fields:
    "app":"prg00000","prio":"info","id":"1234","msg":"seq: 0000000000, thread: 0000, runid: 1374490607, stamp: 2013-07-22T12:56:47 MESSAGE...","source":"localhost","timestamp":"Jul 22 12:56:47"
    As you can see, this has similar fields, but not quite, and FACILITY is missing too.In this case, we'll use a different configuration:
    source s_tcp_json   tcp(port(10514) flags(no-parse));  ;
    parser p_json   json-parser(prefix(".json."));  ;
    destination d_file   file("/var/log/remote.log"
                              template("$ .json.timestamp  $ .json.source  $ .json.app [$ .json.id ]: $ .json.msg \n"));  ;
    destination d_mongodb   mongodb(collection("remote_log")
                                    value-pairs(
                                      pair("PROGRAM" "$ .json.app ")
                                      pair("HOST" "$ .json.source ")
                                      pair("PID" "$ .json.id ")
                                      pair("MESSAGE" "$ .json.msg ")
                                      pair("DATE" "$ .json.timestamp ")
                                      pair("PRIORITY" "$ .json.prio ")
                                      pair("FACILITY" "auth")
                                    ));  ;
    log  
     source(s_tcp_json);
     parser(p_json);
     destination(d_file);
     destination(d_mongodb);
     ;
    
    We use the prefix() option of json-parser(), to avoid collisions with the default syslog-ng namespace. Then, we use a template for the file destination, and value-pairs() for the MongoDB one. Doing all this, we get similar results as we did in the first scenario.JSON over syslogAn even likelier scenario is when we have JSON payload in the message part of a normal syslog message. This is useful because the logs themselves remain syslog compatible, and can be transported through devices that know no better.Thankfully, if we do not tell syslog-ng that we do not want any parsing on the input, the json-parser will receive the MESSAGE part of the log, so if we have JSON payload there, things will just work:
    source s_tcp_json_payload   tcp();  ;
    parser p_json   json-parser();  ;
    destination d_file   file("/var/log/remote.log");  ;
    destination d_mongodb   mongodb(collection("remote_log"));  ;
    log  
     source(s_tcp_json_payload);
     parser(p_json);
     destination(d_file);
     destination(d_mongodb);
     ;
    Again, this assumes that the JSON payloads uses field names compatible with syslog-ng's defaults. Adapting it to use templates or value-pairs can of course be made, as shown in an example above.As an example, here's how a syslog message with JSON payload would look like:
    <38>2013-07-22T13:45:54 localhost prg00000[1234]:  "MESSAGE": "foo", "PROGRAM": "bar" 
    This would, of course, override the MESSAGE and PROGRAM fields, but the rest would be kept intact.Mixed JSON and syslog streamIn order to parse JSON that is intermingled with normal syslog streams, we can use a new feature of syslog-ng 3.4: junctions. These allow us to create branches, and tell syslog-ng something along these lines:
    If there's an incoming message, that begins with @json:, parse it as JSON, otherwise treat it as a normal syslog message.
    We can, of course, skip the part that mandates an in-stream marker, and things will just work, but in that case, for each JSON message, an error will get logged too, which is undesirable. Therefore, if one wants to intermingle JSON and syslog traffic on the same wire, it's best to do so with the JSON having a marker prefix. The marker, however, is not going to be part of the string the json parser receives, so setting it to an opening curly bracket will not work, unless the template is modified accordingly.The config to do this looks like this:
    block parser mixed-json-parser()  
     channel  
      junction  
       channel  
        parser   json-parser(marker("@json:"));  ;
        rewrite   set-tag(".json");  ;
        flags(final);
        ;
       channel  
        flags(final);
        ;
       ;
      ;
     ;
    source s_mixed  
     tcp();
     parser   mixed-json-parser();  ;
     ;
    A more elaborate example can be found in a post by Bazsi.Closing thoughtsThat covers most of the use cases I saw for the JSON parser, if there are cases uncovered, or questions unanswered, I can be reached via twitter, email and a whole host of other ways, and I will happily expand this tutorial if there's enough demand for more.

    Thomas Goirand: OpenStack Havana b2 available, openstack-debian-images approved

    I have finished preparing the beta 2 of the next release of OpenStack. It is currently only available from out Git on Alioth (in /git/openstack), and directly from my jenkins repository, which creates Wheezy backports for it:
    deb ftp://havana.pkgs.enovance.com/debian havana main
    deb http://archive.gplhost.com/debian havana-backports main
    As for every OpenStack release, a large number of Python modules needed to be packaged and are waiting in the FTP master NEW queue to be approved: oslo-sphinx, python-django-discover-runner, python-hacking, python-jsonrpclib, python-lesscpy, python-neutronclient, python-nosehtmloutput, python-requestbuilder, python-termcolor, sphinxcontrib-httpdomain and sphinxcontrib-pecanwsme. Let s hope that they will be approved before the next beta release in september (time where OpenStack Havana will be in feature freeze). The total number of packages maintained by the OpenStack team (on which I really am the only active maintainer for the moment ), there s 53 packages, plus these 11 packages waiting in the NEW queue. That s a big number of package, and I wouldn t mind some help One thing that annoyed all the community is that Quantum, the OpenStack network virtualization module, had to be renamed as Neutron, because of a trademark from Quantum (you probably remember the Quantum Fireball hard drives? Well, it s the same company ). Another good news is that my openstack-debian-images package has just been approved and landed in Sid. With it, you can automate the process of building a Debian image for OpenStack with a simple shell command (there s a man page that I wrote with it: read it if you need to build images). It is made of a single shell script to build the image, using kpartx, parted, mbr, debootstrap, extlinux and friends. I tried to keep it simple, not involving a huge amount of components. With the release of cloud-init 0.7.2-3, I have fixed a few bugs (3 important bugs, out of which 2 where RC bugs), thanks to contributions in the debian-cloud@lists.debian.org mailing list. This includes adding new init.d scripts, so we now have support for user data. This doesn t only benefits OpenStack images, but anyone willing to start virtual machines in the cloud (nowadays, every cloud implementation needs cloud-init installed in the virtual images). This means you can include a script in the metadata of the virtual machine you start it, and it will be executed at startup. If everything goes as planned (that is, no new RC bug), I will upload an update of cloud-init to backports in 5 days (there is already a version there, but it doesn t have the necessary init.d scripts to execute the user data scripts), and openstack-debian-images in 9 days. Then it will be possible to build OpenStack images with absolutely all the tools available from Wheezy (and backports). I hope to be able to discuss that during Debconf 13.

    25 July 2013

    Evgeni Golov: Say hello to Mister Hubert!

    Some days ago I got myself a new shiny Samsung 840 Pro 256GB SSD for my laptop. The old 80GB Intel was just too damn small. Instead of just doing a pvmove from the old to the new, I decided to set up the system from scratch. That is an awesome way to get rid of old and unused stuff or at least move it to some lower class storage (read: backup). One of the things I did not bother to copy from the old disk were my ~/Debian, ~/Grml and ~/Devel folders. I mean, hey, it s all in some kind of VCS, right? I can just clone it new, if I really want. Neither I copied much of my dotfiles, these are neatly gitted with the help of RichiH s awesome vcsh and a bit of human brains (no private keys on GitHub, yada yada). After cloning a couple of my personal repos from GitHub to ~/Devel, I realized I was doing a pretty dumb job, a machine could do for me. As I already was using Joey s mr for my vcsh repositories, generating a mr config and letting mr do the actual job was the most natural thing to do. So was using Python Requests and GitHub s JSON API. And here is Mister Hubert, aka mrhub: github.com/evgeni/MisterHubert. Just call it with your GitHub username and you get a nice mr config dumped to stdout. Same applies for organizations.
    • Authentication for private repos? (-p)
    • Other clone mechanisms? (-c)
    • A help function? (-h)
    • Other features?
    As usual, I hope this is useful :)

    21 July 2013

    Rog rio Brito: Beginning Ruby

    These are some very rough/sketchy notes that I took while doing the exercises on the introductory track of the Ruby language at codeacademy. They were written from the point-of-view of an amateur programmer in C and Python (read: "me"). Since this is my first time with Ruby and I only have about 1 week of experience with it, these notes are likely to contain many mistakes, many simplifications, many omissions or simply gross errors. I would love to be informed of such facts so that I can fix them and not write code that is burdensome for others to maintain. Operators
    • Math operators: +, -, *, /, %, ** (just like Python)
    • Relational operators: ==, <, >, <=, >= (just like other languages)
    • Boolean operators: &&, , ! (just like C/C++/Perl)
    • The combined comparison operator ("spaceship operator", like Perl): <=> (follows the spirit of what strcmp in C does)
    • Conditional assignment operator ( =) only assigns a value to a variable if that variable is bound to nil.
    Numbers
    • You can write number literals embedding an underscore (_) for readability purposes.
    Basic I/O
    • Output: print and puts. Both print strings to stdout, but puts also appends a new line to the end.
    • Input: gets accepts an input from stdin and returns a string.
    • To convert a string foo to an integer, use the Integer(foo) constructor. It throws an exception if it cannot convert the value.
    Strings
    • Strings have at least some methods: .length, .reverse, .upcase, .downcase, .capitalize, .chomp (like Perl, removes the trailing endline)
    • .upcase seems to have problems with non-ASCII characters, like .
    • Interpolation is performed by putting the name name of the variable inside a string and delimited as # name at the place we want the interpolation to occur.
    • Methods like .capitalize don't change the string (they return a new string capitalized). To change the string, you call the method .capitalize! (with a ! at the end of the name of the method).
    • Other useful methods: .gsub for globally substituting a regular expression (and its variant .gsub! for inplace modification), and .include? to verify if the first string includes another.
    • Another method: .split(" "), to split on the string specified as argument.
    Control flow If
    • The syntax of a if is:
        if expression1
          block1
        elsif expression2
          block2
        else
          block3
        end
      
      note that it ends with the word end, there are no need for parentheses, no braces, no colons, and the keyword for "else if" is elsif (different from Python's elif).
    • The "if" can also be started with the keyword unless instead, which checks if the expression is false rather than true (as is the case of if).
    While
    • The syntax of the while is similar to other languages:
        while condition
          block
        end
      
    • A variation of the while is the until, with the same syntax, except for the until in place of the while, and that it iterates when the condition is false, instead of true.
    For
    • The simple case of iterating over a range of numbers is:
        for i in 1...10
          block
        end
      
      Like ranges in Python, the 10 is not included (the variable i iterates from 1 to 9). For an inclusive range, we use two dots (1..10), instead of three dots (1...10).
    Loop
    • To iterate a block, we can use the loop keyword, as in:
        loop   block   # with braces
      
      or as in
        loop do # note the pair do/end in place of braces
          block
        end
      
    • It is useful to use break when using loop to break out of the infinite iterations.
    • Similarly, we can use next as in other languages (the same as continue in C or C++).
    Arrays
    • The equivalent to Python's lists are arrays and they are declared in the same fashion:
        my_array = [1, 2, 3, 4, 5]
      
    • Arrays in Ruby are 0-based.
    • Every array has an iterator called the .each method. The basic syntax is:
        object.each    item  block   # do something
      
      which can be written as:
        object.each do  item  block end
      
      where the name between is bound to (a copy of?) each element of object in turn. The equivalent in Python would be:
        for item in object:
            block
      
    • Arrays can be sorted with the .sort method (or its sibling .sort!). When passing a parameter, it is useful to use the spaceship operator (<=>) (like Perl) to specify a custom order (similar in spirit to what we do with Python's key argument to the sort method of a list). Example:
         my_array.sort!  a, b  a <=> b  # Ascending order
         my_array.sort!  a, b  b <=> a  # Descending order
      
    • The .push method appends an element to an Array (similar to Python's .append).
    • The empty Array is denoted by [], like an empty list in Python.
    • An iterator (like (1..10)) can be converted to an array with the .to_a method.
    Hashes
    • A literal hash is defined by the syntax:
        my_hash =  
            "key1" => "abc",
            "key2" => 2,
            "key3" => false
         
      
      Quite similar to the version in Python:
        my_hash =  
            "key1": "abc",
            "key2": 2,
            "key3": False
         
      
      In fact, in Ruby 1.9, you can write, instead:
        my_hash =  
            key1: "abc",
            key2: 2,
            key3: false
         
      
      which is very similar to Python or JSON.
    • The empty hash, OTOH, is defined by calling the constructor .new of the class Hash:
        my_hash = Hash.new
      
      The syntax used by Python can also be used: my_hash =
    • Iterating over a hash is done the same way as done for an array, but the .each method gives both the key and the value, as in:
        my_hash.each do  k, v 
          puts "# k : # v "
        end
      
    • To iterate only on keys, we use the method .each_key. To iterate only on values, we use the method .each_value.
    • A hash can be sorted with the .sort_by method (to sort by keys, values or any expression involving them) and since it can be ordered, we can reverse (in-place) the order of its elements with the .reverse! method. This makes Ruby's hashes to "taste" like Python's OrderedDict's.
    • When one initializes a hash, one can specify a default value to the .new method (e.g., foo = Hash.new(0)), which makes it convenient to do the equivalent of Python's defaultdict or Counter.
    • You can select part of a hash by using the .select method and giving it a block. For example:
        good_movies = movie_ratings.select k, v  v > 3 
      
    Functions/methods
    • Functions in Ruby are defined with the word def (as in Python) and end with the word end, as other composite constructs. Example:
        def square(n)
          return n*n
        end
      
    • Parentheses are optional in Ruby, unless they create ambiguity. So, to call the function above, one can use any of the following:
        square(2)
        square 2
      
    • A function can take a block as a parameter (and this is what .each does, for instance).
    • Functions can take a variable number of elements with the splash operator (denoted by *), which puts the extra parameters in an Array (like Python).
    • Functions can have default parameters, which are set in the "prototype", just like in Python or C++.
    • If the return keyword is omitted from the method, Ruby uses an implicit return, where the value of the last executed expression is returned to the caller of the method.
    Symbols
    • Any instances of a given symbol share the same ID. This is due to the fact that they are immutable.
    • Symbols start with a colon (:) and they can contain any character that is valid for a variable name.
    • It is possible to convert between a symbol and a string with the methods .to_s and .to_sym.
    Comments
    • Single line comments use the hash symbol (#).
    • Ruby also has multiline comments, which are delimited by a line beginning with =begin and a line beginning with =end.
    Lambda functions
    • A lambda function in Ruby is defined, as expected, as, for example:
        foo = lambda    x  x.to_sym  
      
    • The basic differences between a lambda and a proc is that:
      • A lambda checks the number of elements that it receives, while a proc doesn't and assigns nil to parameters that it didn't receive (a proc seems to ignore extra parameter that it wasn't expecting).
      • When a lambda returns, the control goes back to the function that called the lambda, while when a proc returns, the control is returned also from the function that called the proc.
    Classes
    • "Everything is an object in Ruby." (At least one exception are blocks).
    • To test if an object is of a given class, you use the method .is_a? on the object and the type as argument (e.g., foo.is_a? Integer)
    • The "null" value in Ruby is nil. It is equivalent to None in Python.
    • The only "falsy" values in Ruby are false and nil. The others are "truthy", differently from C/C++/Perl/Python.
    • For a given object, the method .object_id returns what is the "address" of that object.
    • Classes in Ruby are created with the syntax
        class ClassExample
            # body
        end
      
      (That is for a class that has is not derived from other regular classes).
    • Constructors in Ruby are called initialize. An instance of a class is created by calling the method .new on the class name (and passing parameters as needed for the initialize method).
    • Instance variables are named with 1 at sign (@) as a prefix. Class variables are named with 2 at signs (@@) as a prefix. Global variables are named with a dollar sign ($) as a prefix.
    • Class methods are declared inside a class prefixed with self. and they are called with the class name suffixed with the name of the method. For example, for a class MyClass, with a class method class_method, we call it as MyClass.class_method.
    • When overriding a method in a subclass, one can call the method from the parent class with the keyword super, as in super(arg1, arg2).
    • Ruby doesn't support multiple inheritance. In place of multiple inheritance, Ruby offers mixins.
    • To access one attribute, say @my_attrib, in Ruby classes, one usually creates two methods to manipulate it: a method with the name my_attrib, that returns the value of @my_attrib (a getter) and a method with the name my_attrib= that accepts a parameter to set @my_attrib to (a setter). There is syntatic sugar for creating both getters or setters. For a getter, you declare attr_reader :my_attrib (the member name as a symbol). For a setter, you declare attr_writer :my_attrib. If you need both a getter and a setter, then you can abbreviate them with attr_accessor.
    • All methods, by default, are public in Ruby. To explicitly mark something as public, you use the keyword public. To mark something as private, you use the keyword private.
    Modules
    • You can import a module with the keyword require (as in Perl) and the name of the module in quotes.
    • One example of a module is the benchmark module, which provides the Benchmark class, which has the method .realtime, which takes a block and reports how much time it used.
    • To create a module, use a syntax similar to that of a class, but substituting the keyword class with module.
    • The scope resolution operator in Ruby is the double colon (::), like in Perl.
    • To create a method inside a module, you have to prefix it by the name of the module with a dot or with self., if you want to create a method to be called outside the module. The same also holds for creating class methods (as opposed to instance methods): they can be simply named self.foo to get a class method called foo.
    • While some modules are already "preloaded" by the interpreter (e.g., Math), others need to be explicitly loaded. We do this by using require 'foo' to load the module (in the file foo?).
    Mixins
    • A mixin is the use of a module to "enrich" a class, adding "instance" methods of the module to the class. It is, in a sense, a way to have some of multiple inheritance in Ruby (without its headaches?)
    • Using the word include Foo imports the items of the module Foo in the current namespace for instances of a class.
    • Using the word extend Foo imports the items of the module Foo in the current namespace as class methods/attributes.
    Conventions
    • Local variables are named in lower case, with parts separated by underscores, as in my_name.
    • Methods that return boolean values have a question mark (?) at the end of their name.
    • Methods that have destructive side-effects (like changing their input) have an exclamation mark (!) at the end of their name.
    • Code is indented by 2 spaces.
    • Like other languages, constants are written in all caps, with words separated by underscores. For example, MAX_VALUE.
    • Global variables are prefixed with a dollar sign (e.g., $Foo).
    • Classes are named in camel case (no initial lowercase).
    • The "poetic mode" in Ruby recommends one to omit the parentheses on function calls (whenever unambiguous) and, in essence, to write as little "bureaucracy" (like the explicit return keyword in methods).

    11 July 2013

    Joachim Breitner: Running Circle Packing in the Browser using Haste

    Half a year ago, I wrote a small Haskell library called circle-packing to pack circles in a tight arrangement. I used this to experiment with the fay compiler, which compiles Haskell to JavaScript, and the result was quite nice. Recently, I was pointed to haste, another Haskell-to-JavaScript-compiler, and gave it a shot. It required no changes to my code, and after a bug in the compiler was fixed, I could successfully run the example compiled with haste. Some observations:
    • Haste provides more features that I consider necessary for it to be used seriously. In particular its support for Cabal (so I could just write haste-inst install circle-packing) and its support for a much larger subset of Haskell, including type classes, as it builds on GHC.
    • Interfacing with JavaScript is not as smooth as in fay. Especially having to write JS code in a separate helper file is annoying.
    • A quick unscientific comparison of the two results indicates that the code produced by haste is a bit faster (although I should maybe compile the fay variant with the latest version).

    Russ Allbery: kadmin-remctl 3.4

    kadmin-remctl is a wrapper in front of the Kerberos kadmin protocol that exports many operations via remctl and adds some additional synchronization functionality. The primary purpose of this release is to add disallow-svr to the default flags for all newly-created principals. This prohibits obtaining service tickets for the principal, which provides some hardening against brute force attacks. Since the create command is designed for creation of user principals, not service principals, and use of service tickets for user principals is quite obscure and rare in Kerberos, this seems like a better default. This release also relaxes the default allowed principal regex to allow two-character user principals. We mostly prohibit them, but we had some old, disabled ones and at least one of those users returned. This is just a default that can be overridden by other sites. This package, as I say most times when I release it, is badly in need of a complete overhaul, a switch to JSON for the attribute format, conversion to a saner Perl kadmin API, and various other improvements. One of these days.... You can get the latest version from the kadmin-remctl distribution page.

    8 July 2013

    Olivier Berger: Experimenting with Linked Open Data about FLOSS projects : matching Debian upstream projects

    I ve been experimenting with Linked Open Data about FLOSS projects harvested from different sources of DOAP or ADMS.SW descriptions. I ve tried and match upstream projects of Debian packages with upstream projects hosted at Apache, Gnome, or Alioth.debian.org, or catalogued on Pypi. I m matching them on identical values of the Homepage field (comparing the Homepage Control field set by Debian packagers with the doap:homepage meta-data in the RDF documents harvested from the upstream project catalogues). Here are initial results of my little experiment, for number of matched projects, and results on project name s similarity :
    Upstream catalogue Total matching projs Exact same project name Same project name (case independant)
    apache 31 0 (0 %) 0 (0 %)
    alioth 16 13 (81 %) 13 (81 %)
    pypi 439 217 (49 %) 273 (62 %)
    gnome 21 0 (0 %) 7 (33 %)
    Total 507 230 (45%) 293 (58 %)
    The data set contains tens of thousands of projects, with probably many duplicates, but from all of these, only 507 have common homepages. As you can see, in some cases, the Debian source package names match the upstream project name (sometimes with lower/upper case variants), but in general, the project names aren t identical, so it is interesting to try and match them by homepage. For the curious ones, the Apache, Gnome and Pypi project catalogues use to provide RDF meta-data for quite some time. More recently have we introduced ADMS.SW meta-data for Debian source packages, and even more recently for the Alioth projects (through the ADMS.SW exporter plugin for FusionForge). There are still some ways for improvements, for instance to normalize homepage URLs which tend to vary (trailing slashes, or different HTTP/HTTPS schemes). Stay tuned for more details.

    Next.

    Previous.