Code and Philosophy

Exploring the world of development and critical thinking.

HeadlessFabric: Super easy remote command execution and file transfer over SSH

Do you…

  • …perform automated/programmatic SSH commands/file transfers?
  • …need a reliable way to do so that won’t block or exit unexpectedly (the banes of automation)?
  • …want a side dish of super easy automatic parallel execution over SSH to multiple hosts?

If you answered yes, then HeadlessFabric might be what you are looking for!

Important Note

In order for HeadlessFabric to work properly and not block execution on command prompts like login/password, installation and usage of SSH keys to the servers you are connecting to is necessary (in ~/.ssh on many Linux distributions).

Background

At work, we have a huge number of servers that we work with at any given time. Big surprise for a cloud company right? There are various tools to execute commands remotely and transfer files. I really liked Fabric because of the parallel execution (which reduces execution time by 10x or more easily depending on number of hosts) and ease of use.

I started trying to automate some things programmatically with Fabric and found it to be configured very much for command line usage by default. Some configuration required a bit of research to get right so I thought it might be worth while to write a “headless” (i.e. nobody controlling/monitoring execution) wrapper around Fabric for others to benefit from.

Code on Github

HeadlessFabric is released under the Apache 2 license (in github below).

https://github.com/PaulMontgomery/headless_fabric

See example.py for an example of how one might use the module in a program.

Quick Examples

Want to perform an “ls” command on a remote system (ok, it is “localhost” for this example but it can be and IP address)? Here you go:


from headless_fabric import HeadlessFabric

ssh = HeadlessFabric(conn_attempts=3, cmd_timeout=120, net_timeout=120)
data = ssh.execute("ls", ["localhost"])
print(data)

Want to do that on multiple hosts/servers at once? No problem this will execute ls on “localhost” and “127.0.0.1”:


from headless_fabric import HeadlessFabric

ssh = HeadlessFabric(conn_attempts=3, cmd_timeout=120, net_timeout=120)
data = ssh.execute("ls", ["localhost", "127.0.0.1"])
print(data)

Download file “remote_file_name” from “localhost” to local file “new_local_file_name”:


from headless_fabric import HeadlessFabric

ssh = HeadlessFabric(conn_attempts=3, cmd_timeout=120, net_timeout=120)
ssh.get_file("localhost", "remote_file_name", "new_local_file_name")

Note that there is no parallel file transfer capability built in.

I hope you find this tool as useful as I have! I may post later about some nice uses of HeadlessFabric and the PyTest testing framework.

 

VisualBlackBox: Example of real time push driven data visualization

Apologies for the long delay in posts; I have been busy learning about Big Data/Hadoop/Spark/etc infrastructure lately… which leads me into a perfect introduction for this post.  Data scientists who can create compelling big data visualizations are in extreme demand from my experience (not that I consider myself particularly capable in either of those areas at this point, just getting started).  Being the curious programmer that I am, I wanted to delve into this area a little more on my own.  Knowing that I am a very goal driven person, I created a little project to basically train myself on the new data visualization technologies and as a bonus I get to help others who are interested as well.  So along came…

Visual Black Box – https://github.com/PaulMontgomery/VisualBlackBox

VBB is an open source/Apache 2 licensed, push driven, real time, HTML5 data visualization tool (like line graphs, bar charts, heat maps, US election result maps, etc).  VBB can logically multicast a streaming SVG to all web browser listeners.  This easily integrates the data visualization widget into the web page/dashboard look and feel as it is not sending a whole web page.  The relatively new technologies that I wanted to learn/use were:

  • d3.js – Trust me, just click that link and gaze in awe at the amazing data visualizations.  This is what really opened my eyes about the current state of web browser visualization abilities.
    • Which includes SVG (ok, not very new but still cool and underutilized until recently in my opinion)
    • I also wanted to brush up some on my Javascript
  • Node.js – I’ve used many web frameworks and the simplicity and ease of use of this project pulls me back every time.  While it isn’t good for “long” running server/compute-intensive tasks (which hold up the incoming connections potentially), I would argue that much of that deficiency can be offset through use of asynchronous communications (socket.io for example) and AMQP+compute farms.

The idea behind VBB is to take the complexity out of data visualization.  Imagine the skills needed to create scalable big data visualizations:

  • Data Scientist – To understand the structure and meaning of the data results (not to mention creating them to begin with)
  • Web Administrator – Host the data visualization web site, create a scalable infrastructure
  • Client Side/Web Developer – Create the web pages, data visualizations and all client side content
    • Note that the HTML developer and the data visualization (like d3.js) developer may often be different people as the skill sets are fairly different and yet ironically somewhat related.
  • Server Side Developer/Operations – Create the infrastructure to ingest the data, transform the data (optional), send the data to a centralized data repository, set up a monitoring system and if they are really good… they’ll do all of this securely.

I won’t claim that VBB can replace all of those roles but it has the potential to reduce them considerably with a full set of “GUI widgets” (I use that term for individual GUI/SVG visualizations; like 1 line graph or 1 bar graph).  VBB can read a TSV file (simple file format, supported by Excel, etc), broadcast a message to all web browsers viewing the data visualization that an update is ready, push the data updates to all browsers and all browsers update their real time graphs.  So if you can write a TSV file, you can make a real time data visualization. I tried to add lots of helpful comments in the code to make it easy to learn.  It is also structured to make adding new GUI widgets very simple and self contained via JSON configuration files.

Along the way I found several similar technologies and ideas which are obviously much more polished/developed but may not be quite as easy to learn as my examples.  So if you want to learn how to create your own real time visualizations, you might consider giving VisualBlackBox a try as learning guide.  If you just want to display some data quickly, consider using some of the tools listed below.  Disclaimer: I spent very little time examining these technologies in detail so please take my opinions very lightly and research for yourself.  At any rate, I wanted to share some thoughts on what I studied and found:

  • Google Charts – Really easy to use, has “Dynamic Data” real time capabilities, nice abstraction layers, supports most basic chart requirements.  If you don’t have super complex needs, this is a pretty good choice.  I’m really impressed with many of Google’s open source projects.
  • Chart.js – Super configurable charts, fairly good range of complex charts.
  • d3.js – This is the ultimate low level, infinitely capable data visualization framework.  There are practically no limits to what can be done with this amazing library.  Having said that, I would give a few minor warnings: this library is very unforgiving to debug (few/no warnings or help; it let’s you fail relentlessly and sometimes quietly) and it has a high learning curve (with power comes complexity and a background in Javascript, HTML5, SVG, CSS and data theory is required to get started).
  • Snap.js – This is a low level library, similar to d3.js, but is geared more towards general SVG GUIs than data visualization (which it would easily handle).  I just wanted to give this one special mention as a really amazing generic SVG library for those interested.

Python and Threading

Python is an amazing language for accomplishing tasks quickly and easily.  Python is very readable, portable and maintainable but there are a few odd issues with Python to watch out for.  I won’t dive too deeply into this topic but threading in Python is one of these non-intuitive issues that most developers will run into sooner or later.  I normally prefer to read articles rather than watch videos but this presentation by David Beazley is a must watch video in my opinion:

Understanding the Python GIL

https://www.youtube.com/watch?v=Obt-vMVdM8s

 

David delves into the Python interpreter and even some operating system code to understand the issues with Python’s OS non-cooperative threading model and up-levels the information to an easily understandable overview.  Basically, Python threading is something to be avoided unless you really know what you are doing and can carefully craft a specific use case that makes sense.

For the rest of the folks out there, I’ve found that messaging queue technology, such as AMQP, is often used in the cloud world to avoid the threading deficiencies in Python.  Tasks are placed into a queue and Python worker processes work on the tasks in the background instead of generating threads to process the work.  This actually makes the Python development world a bit easier as all of the dreaded thread development issues (deadlocks, starvation, etc) usually don’t exist.  This model also fits well into development frameworks such as Node.js where a any work processed in Node.js may be preventing new connections from being processed.  In this scenario, handing off the work immediately to a message queue can free up Node.js to handle network connections (which it is good at) in the same manner that Python may use message queues to avoid threading.

Secure Logging Architecture

Overview

Since I dabble in the security arena now and then, today’s post will focus on secure logging.  I created an OpenStack-wide architecture proposal here:

https://wiki.openstack.org/wiki/Security/Guidelines/logging_guidelines

Please read that link as my description here will be a very short “elevator pitch” of the full problem and solution space.

Importance of Logging

Why is logging important to start with?  It gives administrators and users the ability to see what is happening within the system, provide great customer diagnostic support, potentially predict/mitigate future failures, detect performance bottlenecks, etc.  In the Linux world, most logs typically go to syslog.  Log entries can just be plain text like “User Paul logged into the system with password abc123 from IP address 1.2.3.4 at 2014/06/03 01:02:03 PM.” all the way to complex JSON-like structured log entries.

Problem Statement

Logging is a strange concept sometimes.  Quite often, there will be a simultaneous lack of enough log data to root cause an issue and too much sensitive or confidential data is logged at the same time.  How is this possible?  Let’s take the simple log entry from before as an example:

User Paul logged into the system with password abc123 from IP address 1.2.3.4 at 2014/06/03 01:02:03 PM.

For sake of example, there is some weird problem suspected when a certain version of a web browser interacts with the system.  The log statement above does not provide web browser information and thus does not enable root causing without more digging into data or possibly even code changes.  At the same time, this log entry has a plain text user password “abc123” which is generally considered to be a very dangerous practice.  What happens if another user views this log and gathers credentials for other users?

Solution

There are many “band-aids” out there in the wild where poor administrators must actively monitor logs, find sensitive data and change their log filtering algorithm to sanitize the log data.  This is non-optimal since the code will change and cause log changes.  There will always be some lag between new code and an admin catching the sensitive log data.  There are even efforts in the code itself to self-sanitize log data by searching for things like “password=” text but that will not catch everything… and it may filter out necessary log entries erroneously.

My stance on this topic is that code must uniquely tag sensitive data up front to give the backend log filtering algorithm a single tag to sanitize/remove.  This is just a made up example but what if we formatted the log entry like this:

User Paul logged into the system with password —{abc123}— from IP address 1.2.3.4 at 2014/06/03 01:02:03 PM.

By adding some arbitrary tag around the sensitive data, filtering becomes unambiguous and easy.  The example used “—{}—”  as a tag but in most cases a JSON dictionary is a better structure (at least logically).

It does take some effort up front to make sure that logs are sanitized (code gate reviews) but the benefits are enormous for security, ease of operation and customer support.

PS: Please note that I do not condone logging passwords (especially in plain text) in general.  This was just a handy example.

OpenStack Messaging and Workflow

Recently, our project started exploring the OpenStack messaging and workflow libraries available.  Being visually oriented and preferring to understand the interconnection between components, I created a diagram to capture my understanding of the OpenStack workflow and messaging capabilities:

OpenStack Messaging and Workflow

OpenStack Messaging and Workflow

Unfortunately draw.io output does not seem very importable into WordPress so the PNG diagram links are not click-able.  Here they are:

Note: This is accurate as of 2014/05/27 to the best of my knowledge but OpenStack moves fast so don’t expect this to remain accurate forever.

 

Humorous Systems Programmer Article

http://research.microsoft.com/en-us/people/mickens/thenightwatch.pdf

This is a classic that everyone should read when running into an insanely difficult bug to root cause.  With lines like this:

“When it’s 3 A.M., and you’ve been debugging for 12 hours, and you encounter a virtual static friend protected volatile templated function pointer, you want to go into hibernation and awake as a werewolf and then find the people who wrote the C++ standard and bring ruin to the things that they love.”

… who can resist!?

Yes, I lived this life in short stints over my career.  I’ve spent hours trying to determine the blink rate of a little LED that was the only useful form out output/debugging available for new firmware on new microcontrollers for example.  When even the very hardware and/or compiler being used is so new and experimental that bugs are not only likely but almost certain to happen, imagine root causing weird behavior with all of the various potential contributing factors.

Yes, it was painful but it was also very valuable to understand what happens “under the hood”.  I sometimes fear that this expertise is being lost in a world where programmers may go their entire careers in higher level languages.

 

HTML5 Canvas Training Course 2: Mouse Interactions

Prerequisite Reading

Please read
https://paulmontgomerycode.wordpress.com/2014/05/09/html5-canvas-training-course-1/
before continuing…

Overview

This course continuation incorporates several new concepts including:

  • Basic event handling
  • Capturing mouse events (mouse down, mouse up, drag and drop)
  • Basics of preloading external content such as images and sounds
  • A CreateJS Tween example

Basically this creates two different colored filled circles which are drag and droppable.  Right clicking will cause the alpha is cycle and then return back to 50%.  All mouse events are also logged to console.

Code Repository

https://github.com/PaulMontgomery/html5_canvas_training/blob/master/canvas_training_2.html

To view this demo, click here:

https://github.com/PaulMontgomery/html5_canvas_training/blob/master/canvas_training_2.html

 

Detailed Code Analysis

Much of the code is the same as the previous example so I will focus on the deltas primarily.

In demo_preinit()…


                /* Example: Loading multiple external resources like images
                queue = new createjs.LoadQueue(false);
                queue.addEventListener("complete", demo_init);
                queue.loadManifest([
                    {id:"image_name1", src:"images/image1.png},
                    {id:"image_name2", src:"images/image2.png}
                    ]);
                */
                demo_init();

Commented out lines 1 – 8 show an example of preloading external resources in CreateJS.  Please see the official documentation on these functions but line 3 takes responsibility for calling the demo_init() function once the resources are fully loaded.  This prevents page errors due to use of a resource before it is fully loaded which is why this is a good way to structure programs in general.  In order to load a resource, like a PNG image, add lines such as 5 and 6 which give the image a user friendly name as the first parameter and where the resource is located (in a local images/ directory in this example).  If this code is uncommented, the demo_init() on line 9 is not needed/should be removed.  Since these demos are self contained for ease of use and there is no need to load external resources, I am manually calling the demo_init() function to continue execution.

In demo_init()…

                create_draggable_object(canvas_width * 0.25,
                    canvas_height / 2, "#BB00BB");
                create_draggable_object(canvas_width * 0.75,
                    canvas_height / 2, "#00BBBB");

 

demo_init() is smaller than the previous example as most of the functionality was moved into another function to D.R.Y. up the code a bit.  Each call to create_draggable_object() creates a new circle on the screen at the given x, y coordinates and with the specified web color.  You may experiment and add new objects or manipulate existing objects to understand how this works.

Note also that the demo_tick() function only performs a stage.update() now.  This is because instead of manually manipulating object locations to create movement, this demo uses the CreateJS Tween library (explained further down).

            function create_draggable_object(start_x, start_y, color) {
                /* Example of using a preloaded image
                var image1 = new createjs.Bitmap(
                    queue.getResult("image_name1"));
                */

                var graphics = new createjs.Graphics();
                graphics.beginFill(color);
                graphics.drawCircle(0, 0, circle_radius);
                circle_shape = new createjs.Shape(graphics);

                var dragger = new createjs.Container();
                dragger.x = start_x;
                dragger.y = start_y;
                dragger.alpha = 0.5;
                dragger.addChild(circle_shape);

                dragger.on("pressmove", function(evt) {
                    evt.currentTarget.x = evt.stageX;
                    evt.currentTarget.y = evt.stageY;
                });

Lines 2 – 5 provide a matching example to the commented out preloading routine discussed earlier.  This is an example showing how something like an image is basically treated/handled in the same fashion as the circle shape being used.  The queue.getResult() function uses the user-friendly name given to the resource.  This bitmap may then be placed into the same dragger that the shape is placed into.

Lines 7 – 10 make the circle much like the previous training example.

Lines 12 – 16 create a container which is the actual drag and drop object.  This holds the circle shape that was just created by using dragger.addChild() so that we can just focus on manipulating the dragger object.  Note that the x and y coordinates are set on the dragger to position it since the circle shape follows the dragger now automatically.  Warning: Trying to set the circle shape x and y coordinates directly will likely make the circle invisible in the container (“off screen”) as the coordinate system will be local to the container holding it.  Line 15 sets the alpha of the circle to 50% just to enable some nice color mixing when circles overlap.

Hint: CreateJS has many mouse interaction events and a good list is at the bottom of this page in the “Events” section: http://createjs.com/Docs/EaselJS/classes/DisplayObject.html

Lines 18 – 21 are the magic to enabling drag and drop capability for each circle.  This is setting up an event handler on the pressmove event.  The function returns the event object aka evt which is being dragged and dropped.  This pressmove event is called MANY times a second so logging in here is discouraged.  All that is needed to complete the drag and drop is to set the manipulated object’s (evt.currentTarget) x and y coordinates to where the mouse pointer is (stageX and stageY).  It is that simple!

                dragger.addEventListener("mousedown", function(evnt) {
                    if (evnt.nativeEvent.button == 2) { // right mouse button
                        console.log("Right click down on object id: " +
                            evnt.currentTarget.id);
                        createjs.Tween.get(evnt.currentTarget)
                            .to({alpha:0.10}, 2000)
                            .to({alpha:1}, 2000)
                            .to({alpha:0.5}, 1000);
                    } else {
                        console.log("Left click down on object id: " +
                            evnt.currentTarget.id);
                    }
                    evnt.addEventListener("mouseup", function(evt) {
                        console.log("Mouse up on object id: " +
                            evnt.currentTarget.id);
                    });
                });

                stage.addChild(dragger);

This code adds the ability to detect the other common mouse events.  In each case, the event is logged to console to help keep track of what is happening and when.

Line 1 sets up an event handler for the mousedown event and the evnt variable will hold the event object in evnt.currentTarget (which is the dragger object for a given circle).  Once this event handler is called, line 2 shows how to differentiate between a left and a right click.  In order to visually show a right click event, the object clicked will cycle through various alpha values before settling back to 50% alpha due to lines 5 – 8 which call CreateJS Tween.  The documentation on Tween is very good so I won’t dig too far into this topic.  Line 6 tells Tween to move the current object’s alpha to 10% over 2 seconds.  Line 7 changes alpha to 100% over 2 seconds and line 8 finally changes the alpha value back to the original 50%.  Tween can move objects, change colors, rotation, alpha, etc… it is quite powerful and very much a “fire and forget” model.

One very key point to make is that the mouseup event seemingly must be wrapped inside of a mousedown event as shown on line 13.  This may be an artifact of CreateJS or some other reason but attempting mouseup detection without the mousedown event wrapping it simply caused missing events and a lot of debugging.

Finally line 19 causes the dragger container to be added as a child to the stage which enables it to become visible and participate in events.  The stage holds everything even if it is via a nested structure of children (stage holds the dragger container which in turn holds the circle shape for example but stage doesn’t directly hold the shape).

That concludes this training course on mouse interactions.

Watch for new courses in the future!

HTML5 Canvas Training Course 1

Prerequisite Reading

Please read
https://paulmontgomerycode.wordpress.com/2014/05/09/html5-canvas-introduction/
before continuing…

Overview

This course will demonstrate a very simple animated circle which bounces right and left across the canvas using HTML5 Canvas via CreateJS.  I conceptually think of the HTML page as an application which happens to run in a web browser.  This demo is completely self contained within the single HTML file (aside from the CreateJS CDN).

Code Repository

https://github.com/PaulMontgomery/html5_canvas_training

… for the full source of the working demo.

To view the demo, click here:
https://github.com/PaulMontgomery/html5_canvas_training/blob/master/canvas_training_1.html

Detailed Code Analysis

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>HTML5 Canvas Training Course 1</title>

This is just basic HTML, moving on.

        <script src="http://code.createjs.com/createjs-2013.12.12.min.js"></script>

This is the CDN link for the CreateJS version that I am using.  This is handy for development but you take a dependency on network accessibility to run the demo.  In production systems, I would suggest downloading a local copy of CreateJS for reliability.

        <script>
            // Draws an animated bouncing circle on the canvas
            // Paul Montgomery (paulmontgomery.code@gmail.com) 2014/05/09
            // Descriptions and explanations are at:
            // https://paulmontgomerycode.wordpress.com/2014/05/09/html5-canvas-training-course-1/

            var stage, canvas_width, canvas_height, circle_shape, circle_radius = 50;

The script tag indicates that JavaScript follows. These are some global variables that are useful for the demo:

  • stage – This is the “stage” on which all objects are placed
  • canvas_width – This will later hold the width of the canvas as defined by the HTML at the end of the code
  • canvas_height – … height of the canvas
  • circle_shape – The CreateJS Shape object which holds the circle graphic that will be drawn later
  • circle_radius – The radius of the circle; changing this will cause the circle to increase or decrease in size (50 pixel default)
            function demo_preinit() {
                console.log("demo_preinit() called");
                demo_canvas = document.getElementById("demo_canvas");
                canvas_width = demo_canvas.width;
                canvas_height = demo_canvas.height;
                console.log("demo_canvas is " + canvas_width + " by " +
                    canvas_height + " pixels in size");
                demo_canvas.oncontextmenu = function(e) {
                    e.preventDefault();
                }

                stage = new createjs.Stage(demo_canvas);

                demo_init();
            }

This is a common pattern in all of my code to create a preinit() function which then calls an init() later. It is not apparent why this is important yet but it relates to loading of external media such as images or sound (which is not done in this demo).  Later demos will explain this in more detail but it gives the media a chance to load fully before trying to use them (which would cause an error if they are not loaded yet).  See CreateJS Preload for more details and examples.

Line 2 is just a common debug/diagnostic method that I use to show progress of an application.  Browsers are all different but in Firefox you may right click the HTML screen and “Inspect Element” and then click the “Console” button to see these messages.

Line 3 will be in most any HTML5 Canvas code in that it associates the HTML canvas defined at the bottom of the HTML example with the CreateJS library in order to control the canvas directly.  Just make sure that the name in the HTML is the same or an error will occur.  This same method may be used to access almost any HTML/DOM entity that has a unique id.

Lines 4 and 5 show access to the canvas by obtaining the HTML defined canvas and finding out what the x and y dimensions of the object are.

Lines 8 to 10 prevent right clicks on the canvas from bringing up a web browser menu.  It isn’t always necessary but this will be useful later in this course.

Line 12 associates the canvas with the stage where everything “acts”.  Again, this or something similar will likely be in most any project.

 

            function demo_init() {
                console.log("demo_init() called");
                var graphics = new createjs.Graphics();
                graphics.beginFill("#BB00BB");
                graphics.drawCircle(0, 0, circle_radius);
                circle_shape = new createjs.Shape(graphics);
                circle_shape.moving_right = true;
                circle_shape.x = canvas_width / 2;
                circle_shape.y = canvas_height / 2;
                stage.addChild(circle_shape);

                createjs.Ticker.setFPS(30);
                createjs.Ticker.addEventListener("tick", demo_tick);
                console.log("Starting animated circle...");
            }

This function begins the “real” work of the demo.  By the end of this function, a circle will be drawn in the center of the canvas and everything will be set up to enable movement.

Lines 3-5 create a purple circle with radius of circle_radius (or 50 pixels by default).  For this and all CreateJS functions, I would highly recommend reading the online CreateJS documentation to understand functionality and parameters.  Please note that this will not actually do anything until we stage.addChild().

Line 6 creates a CreateJS Shape object which is what holds all graphics typically.  This associates the circle graphics with the shape.  This is very common to see in CreateJS code.

Line 7 is a simple Boolean method to indicate what direction the shape should move (to the right to start).  More on this within the demo_tick() function.

Lines 8 and 9 simply move the shape to the center of the canvas using the x and y values previously stored.

Line 10 finally adds the shape to the stage.  Any object that will be displayed or manipulated on the stage must be added to be part of the event chain.

Line 12 sets the canvas frames per second to 30.

Line 13 sets up events to be called 30 times (or whatever the FPS) a second and to call demo_tick() function each time.

            function demo_tick() {
                if (circle_shape.moving_right == true) {
                    circle_shape.x += 5;
                    if (circle_shape.x >= (canvas_width - circle_radius))
                        circle_shape.moving_right = false;
                } else {
                    circle_shape.x -= 5;
                    if (circle_shape.x <= circle_radius)
                        circle_shape.moving_right = true;
                }

                stage.update();
            }

Lines 2 and 6 basically funnel the workflow into a circle moving right or circle moving left branch of code.  This is surely horribly inefficient and needlessly complex but I wanted to show how manual movement of objects may be accomplished.  For a much easier way, please see CreateJS Tween documentation which is dedicated to moving objects around.

Lines 3 and 7 increment or decrement the shape location by 5 pixels each tick (remember, 30 ticks per second in the current configuration).

Lines 4, 5 and lines 8, 9 keep the shape from moving completely off of the canvas.  At the point where it would leave the canvas, the shape changes direction and starts moving the other way.

Line 12 is the key to almost anything happening in this demo.  The stage (and everything on the screen) won’t move or change in any way without a state update to redraw the screen.  If you find a tick()-like function without stage.update(), something is likely wrong.

        </script>
    </head>

    <body onload="demo_preinit();">
        <h1>HTML5 Canvas Training Course 1</h1>
        <canvas id="demo_canvas" width="500" height="300" style="background-color:#EEEEEE">
            <p>Your browser does not support HTML5 Canvas which is required to see this content.</p>
        </canvas>
    </body>
</html>

Line 1 ends the JavaScript section.

Line 4 is super important for the demo operation.  There are many ways to kick-off the JavaScript code but I chose to use the onload ability of the body tag to call demo_preinit().  Without this, the page would sit there statically doing nothing (no circle or anything).

Lines 6-8 is where the canvas is defined for the JavaScript to manipulate, it defines the canvas dimensions and color (I made the canvas slightly grey for visibility, usually the canvas is “invisible”) and the line 7 text will automatically show up on any web browser that does not support the HTML5 canvas feature.  This is really nice so that a user doesn’t sit at a blank screen waiting for action; there is immediate notification.

That is pretty much it for the first demo; not too hard at all is it?  The code could obviously be much smaller but this is a great template to use when creating other projects.

 

Please see the next course: HTML5 Canvas Training Course 2: Mouse Interactions

https://paulmontgomerycode.wordpress.com/2014/05/14/html5-canvas-training-course-2/

 

HTML5 Canvas Introduction

Overview

Recently, I had the simultaneous interest and opportunity (love it when that happens!) to work with HTML5 Canvas to create an interactive drag and drop animated GUI.  I am quite astounded at the amazing capabilities integrated into most all modern web browsers and yet I hear/see relatively little use of these capabilities.  When others saw the ease of creating fairly complex demos, I received many requests for training sessions.  So, I plan to post my experiences and share example code publicly in a series of articles on this topic.

Background

I have a varied background in using HTML and have developed a small amount of minor JavaScript programs over the years.  I still consider myself a fairly novice JavaScript developer as the examples will surely show.  Please forgive the inefficient ways I may implement algorithms in this series but I believe it will be a great starting point for anyone interested in learning HTML5 for themselves.  I am also a novice, at the time of this article, with HTML5 Canvas and CreateJS.  With that out of the way… let’s get started!

HTML5 Canvas vs SVG

There are two main options for user interface development: Canvas and SVG (Scalable Vector Graphics).  Each option is quite impressive but they cater to different needs.  This is one of the best articles that I’ve seen describing where each shines/should be used:

http://blogs.msdn.com/b/ie/archive/2011/04/22/thoughts-on-when-to-use-canvas-and-svg.aspx

… I won’t try to improve on that.  A co-worker created some very fancy, yet simple, SVG clocks for example:

SVG Demos

https://github.com/ed-/clocks

Canvas Demos

http://the-webworker.com/10-stunning-html5-canvas-demos/

CreateJS

I chose a Canvas path and after researching many JavaScript libraries, I selected CreateJS.  The price is right and the license is very permissive (MIT license).  I also read evidence that many Flash developers moved to this library.  Why use an external library instead of basic Canvas manipulations?  CreateJS (and other libraries) help eliminate some of the deficiencies of Canvas as compared to SVG such as DOM manipulation (use SVG inside a Canvas!) and animation support (even sprite sheet support).  It even helps ensure that all web browsers on most form factors generate the exact same UI and behavior.  CreateJS can also scale up to advanced interactive games but does not get in the way of simple applications.

Just to give an impression of the power and ease of this library, I was able to:

  • 1 day: Go from absolutely no HTML5 experience to implementing clickable events, animation and sound.
  • 2 weeks: Created a bitmap drag and drop demo with animations and some minor physics features.

HTML5 Canvas Training Course 1 starts here:
https://paulmontgomerycode.wordpress.com/2014/05/09/html5-canvas-training-course-1/

Oslo Config

Note: This is still in progress and incomplete.  I will fix that soon.

Oslo Config is one of the required libraries within OpenStack for any project which needs to implement configuration file reading or command line input parsing.  This article will focus on the INI-like configuration file reading capabilities of Oslo Config and will include some of the tips/tricks that I discovered while using it.  Examples used in this article are also loosely borrowed from Project Solum and simplified where possible.

Note: WordPress code highlighting seems broken at the time of this post so please excuse the mess.  I’ll try to clean it up later.

Most OpenStack projects use Oslo Config and they create an example configuration file which is meant to be edited by the operator running the service.  In Solum, this file resides in solum/etc/solum/solum.conf.sample.  Everything except group headers are commented out by default.  It is the responsibility of the operator/administrator to edit the configuration file to match the running environment.  Default options may be used by simply not uncommenting a configuration option.  This is a snippet of the Solum [validation] group configuration at the time of this post:

<br />[validation]</p><p>#<br /># Options defined in solum.common.validate<br />#<br /><br /># The longest git pull url acceptable (integer value)<br />#git_url_max_len=255<br /><br /># The git pull url regex-based whitelist and blacklist<br /># validation dictionary. ^https?://github.com/[a-z/_-]+$ is an<br /># example which allows http(s)://github.com addresses and<br /># ^git@github.com:.*\.git$ enables git@github.com-like<br /># addresses. (dict value)<br />#git_url_restrictions=<br /><br /># Keys in this dictionary should match keys in the<br /># git_url_restrictions dictionary.  This configuration option<br /># allows each rule to be "allow", "deny" or "ignore". (dict<br /># value)<br />#git_url_state=<br />

 

Other useful links about Oslo Config:

Create your own website, free on WordPress.com.Create your own website.
Start free