Wednesday, November 25, 2015

Mongo Performance Monitoring

A basic database top for Mongo is
> & 'mongostat' /host:localhost /port:27014 /username:mongoMonitor /password:<> /authenticationDatabase:admin

insert query update delete getmore command % dirty % used flushes  vsize    res qr|qw ar|aw netIn netOut conn     time
    *0    *0     *0     *0       0     1|0     0.0   34.2       0 641.0M 562.0M   0|0   1|0   79b    15k    1 15:25:26
    *0    *0     *0     *0       0     1|0     0.0   34.2       0 641.0M 562.0M   0|0   1|0   79b    15k    1 15:25:27
    *0    *0     *0     *0       0     1|0     0.0   34.2       0 641.0M 562.0M   0|0   1|0   79b    15k    1 15:25:28
insert query update delete getmore command % dirty % used flushes  vsize    res qr|qw ar|aw netIn netOut conn     time
    *0    *0     *0     *0       0     1|0     0.0   34.2       0 641.0M 562.0M   0|0   1|0   79b    15k    1 15:25:36

This is very console driven and and requires writing the console output to stdout for trend analysis.

There are a number of for costs solutions for Monitoring Mongo. Most monitoring platforms have some way to hook into Mongo's built in performance metrics. Solarwinds uses a powershell wrapper (on Windows, probably bash on Linux) in their Mongo template. This was interesting because it showed a clear pattern for building your own monitor if you do not have really really nice monitors like we do.

The path to writing your own monitor is creating a connectionadding a polling interval
creating an object to load the json stats in
parsing the object into discrete  KVP
associate the measures with date and time
adding aggregates to the measure
storing the metric in a database or file

The basic query you can run would be
    db.runCommand( { serverStatus: 1} )

A more discrete monitor call (for queue exhaustion in this case) would be
    db.runCommand( { serverStatus: 1, metrics: 0, locks: 0, globalLock: 1, asserts: 0, connections: 0,  network:0, cursors: 0, extra_info:0 , opcounters:0, opcountersRepl: 0, storageEngine:0, wiredTiger:0})

Using discrete calls per metric group increases the number of connections, queues, and I/O. However it allows you to poll individual metric groups at different intervals.

The GlobalLocks stats look like this.
 {"totalTime":1048003623000,"currentQueue":{"total":0,"readers":0,"writers":0},"activeClients":{"total":10,"readers":0,"writers":1}}

globalLock:
 totalTime: 1048003623000
 currentQueue:
 total: 0
 readers: 0
 writers: 0
 activeClients:
 total: 10
 readers: 0
 writers: 1
 Polling this on a 1 minute interval can give you really detailed utilization patterns when you first implement applications with Mongo. However over time you should be able to scale back to 5 or 15 minute intervals as your average utilization levels out. 

Monday, October 5, 2015

Database Scaling Projections




Metric Current Last Year Monthly Growth 12 Month
Database Size (GB, TB, PB)
Average Stored Record Size
Average Collection or Table Size
Largest Collection or Table
Writes / Day
Reads / Day
% Queries Using PK
% Queries Using Non-PK Idx
% Queries Using Aggregations (sort of Mongo or Hive Specific)
% MapReduce Jobs
Avg Records Returned per Query
Avg Record Size Returned per Query
Avg Hash Table Size for UNION or JOIN operations

Tuesday, September 22, 2015

Running ETL Code in Powershell Workflow

I needed a test harness to run multiple concurrent versions of the same Pentaho job. I wanted to test that the pid file feature I added prevented subsequent executions while the job was already running.

Create a file named ConcurrencyTest.ps1 with the following content
param(
 [Parameter(Position=0,
      Mandatory=$True,
      ValueFromPipeline=$True)]
    [INT]$Attempts=$(throw "You did not provide a value for Attempts parameter.")
    )

function DoStuff
{
    param(
    [Parameter(Position=0,
    Mandatory=$True,
    ValueFromPipeline=$True)]
    [int]$Iter
    )
    $root ="$env:programfiles"
    Set-Location $root\Pentaho\design-tools\data-integration
    cmd /c .\Kitchen.bat /file:C:\Source\Trunk\Transforms\Job_Ods_AggregateMongo.kjb /Level:Detailed | Out-File out.$Iter.log
}

workflow RunStuffParallel
{
    param(
        [Parameter(Position=0,
        Mandatory=$True)]
        [int]$MaxIter
    )

    $ExecutionAttempts=@(1..$MaxIter)
  
    ForEach -Parallel ($Attempt in $ExecutionAttempts)
    {
        DoStuff -Iter $Attempt
    }
}

RunStuffParallel -MaxIter $Attempts

Execute the test using .\ConcurrencyTest.ps1-Attempts 5

Wednesday, September 16, 2015

Microsoft Web API Custom Model Binding

Web API is great. It is easier than WCF service creation and costs 100% less than Service Stack (service Stack is more feature rich, FWIW). There is a ton of documentation on line for Web API and I like it better than the Service Stack documentation available outside of Pluralsight (my opinion, not a huge deal).

One topic I found annoyingly less well documented we how to parse the query of URI query string, validate the values, and build a conditional filter (or where clause) for the query string in the repository class. The link below has a really good article showing some of this.

using System;
using DemoService.Common;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using Newtonsoft.Json;

namespace DemoService.Models
{
    public class ServiceOptionsModelBinder : IModelBinder
    {

       
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {

            var key = bindingContext.ModelName;
            var val = bindingContext.ValueProvider.GetValue(key);
            List<KeyValuePair<string, string>> requestValuePairs;
            var request = actionContext.Request;
            var requestMethod = request.Method;
            var requestHeader = JsonConvert.DeserializeObject<QueryObj>
                  (request.Content.Headers.ToDictionary());
           

            //Check and get source data from uri
            if (!string.IsNullOrEmpty(request.RequestUri.Query))
            {
                //also consider using QueryStringValueProvider
                requestValuePairs = request.GetQueryNameValuePairs().ToList();
            }
            //TODO: when we need to create a POST request, fix the type mismatch below
            //Check and get source data from body
            else if (request.Content.IsFormData())
            {
                var requestBody = request.Content.ReadAsStringAsync().Result;
                requestValuePairs = null;
                //requestValuePairs = Parsers.ConvertToKvp(requestBody);
            }

            else throw new NotSupportedException("Not supported, Aint HTTP compatible");
            bindingContext.Model = requestValuePairs;          

            return true;
        }
    }


}


REFS:
http://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/
http://www.codeproject.com/Articles/701182/A-Custom-Model-Binder-for-Passing-Complex-Objects
http://stackoverflow.com/questions/29393442/custom-model-binder-for-a-base-class-in-web-api

Reading List

Tuesday, July 21, 2015

C# Notation Reminder

I often forget the nomenclature of a few C# coding constructs. Maybe writing them down will help.

In C# 2.0, generics were introduced. For a generic there is a <T> which stands for Generic Type Parameter. The generic type is a blueprint for what you actually want to implement. An example is the code below where I want to implement an IoC container to write session details to Redis.


            /// <summary>
            /// funq IoC container for in memory cache client like Redis
            /// used for Auth
            /// </summary>
            /// <param name="container"></param>
            public override void Configure(Container container)
            {
                Plugins.Add(new AuthFeature(
                    () => new AuthUserSession(),
                    new IAuthProvider[] {new BasicAuthProvider(), }));

                container.Register<ICacheClient>(new MemoryCacheClient());
                var userRepository = new InMemoryAuthRepository();
                container.Register<IUserAuthRepository>(userRepository);
            }
        }

The other thing I forget is what () => means in for lambdas. To create a lambda expression, you optionally specify input parameters on the left side of the lambda operator =>, and you put the expression or statement block on the other side. I always forget that () is just an empty parameter list. I am not even sure why I used an empty list in the delegate above. Why!?

For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared.

REFS:
https://msdn.microsoft.com/en-us/library/0zk36dx2.aspx
https://msdn.microsoft.com/en-us/library/bb397687.aspx

Thursday, July 9, 2015

NodeJS - Concurrency Model

NodeJS is magical. It is fast and easy and monolingual from UI to DAL. It is the purest unicorn of technology. It supports concurrency but is single threaded.So your code executes in the single thread, However, all I/O is evented and asynchronous, so the following won't block the server. The callback and the promise abstractions provide easy access to the event loop. Any I/O call saves the callback and returns control to the node runtime environment.One key idea is "CPU-intensive work should be split off to another process with which you can interact as with events, or by using an abstraction like WebWorkers." Competing ideas to ponder are the use of the cluster module presented in Portland's use group Chris McDonald's example or using PM2 as outlined here clustering made easy managing eventing

Basic Concepts
  • Continuation passing style functional programing paradigm where each function provides an extra argument to pass a return value to it. That means that when invoking a CPS function, the calling function is required to supply a procedure to be invoked with the subroutine's "return" value. Expressing code in this form makes a number of things explicit which are implicit in direct style. Procedure returns become apparent as calls to a continuation; intermediate values, which are all given names; order of argument evaluation, which is made explicit; and the final action of the called procedure, which simply call a procedure with the same continuation, unmodified, that was passed to the caller.
  • Streams Readable and writable streams an alternative way of interacting with (file|network|process) I/O.
  • Buffers Buffers provide a binary-friendly, higher-performance alternative to strings by exposing raw memory allocation outside the V8 heap.
  • Events Many Node.js core libraries emit events. You can use EventEmitters to implement this pattern in your own applications.
  • Timers setTimeout for one-time delayed execution of code, setInterval for periodically repeating execution of code. See http://book.mixu.net/node/ch9.html

Cautionary Tales and Coding Practices
http://callbackhell.com/
http://becausejavascript.com/node-js-process-nexttick-vs-setimmediate/
http://howtonode.org/understanding-process-next-tick

PayPal has a lot of data and a lot of concurrent users. This is a problem I want to have, so when I see them move from Java to Node, I pay attention. Paypal developed Java and Node pages side by side to benchmark performance. To quote, the node.js app was:
  • Built almost twice as fast with fewer people
  • Written in 33% fewer lines of code
  • Constructed with 40% fewer files

Both CRUD apps were simple (few routes, few API calls). Node outperformed Java, even given the fact that the Java app had a two month head start. You can see the performance benchmarks here
https://www.paypal-engineering.com/2013/11/22/node-js-at-paypal/

I care about Node because I want an easier path to building a site to secure access to business intelligence assets. Most data services teams I work with have no web developers at all, and rely on Sharepoint and Power BI to deliver what-if analysis. Based on my review of Express with templating and the elegance of D3 on Angular for charting, I think Node becomes less "too hard" to implement for a reporting application team.

I wanted to understand the concurrency model as compared to using the actor pattern implemented in Hadoop via Akka.



Some ideas I liked
"

It is useful to understand how node and V8 interact. Node handles waiting for I/O or timers from the operating system. When node wakes up from I/O or a timer, it generally has some JavaScript callbacks to invoke. When node runs these callbacks, control is passed into V8 until V8 returns back to node.
So, if you do var ii = 1; ii++;, you will never find that ii is anything other than 2. All JavaScript runs until completion, and then control is passed back to node. If you do doSomething(); doSomething(); that will always run doSomething twice, and it will not return to node's event loop until the second invocation of doSomething returns. This means you can completely lock up node from a simple error like this:
for (var i=0 ; i >= 0 ; i++) {}
It doesn't mater how many I/O callbacks you have registered, timers set to go off, or sockets waiting to be read. Until V8 returns from that infinite loop, node does no more work.
This is part of what makes programming in node so nice. You never have to worry about locking. There are no race conditions or critical sections. There is only one thread where your JavaScript code runs."

REFS
https://www.paypal-engineering.com/2013/11/22/node-js-at-paypal/
http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
http://stackoverflow.com/questions/5153492/models-of-concurrency-in-nodejs
https://creationix.com/jsconf.pdf
https://github.com/xk/node-threads-a-gogo