Thursday, June 13, 2013

More Visual Studio shenanigans

I just received an email with some light detail about Visual Studio 2012 update 3 RC.  After having a look at the lean list of fixes included and the news that MS is prepping for VS2013... well I was pretty disapointed.

Suffice to say that effectivly I have not been able to use VS2012 for much of anything.  Its either been feature incomplete or buggy as shit to the point of unusability.  So apart from not progressing a couple of projects... I will essentially have to skip a whole version before (hopefully..) I can make some progress.  Talk about stealing momentum.

While I understand that VS is an "everything and the kitchen sink" type toolbox and getting it to all work is a herculean task... it seems like this version has just sucked constantly.  Its been such a political release with MS trying to strong arm their agenda for Win8 down my throat that I am just disgusted by the whole experience. 

The sad thing is that Win8 would have been picked up and used quite happily as part of the natural cycle and no one would have mentioned it.  We would have migrated everything in our own time and at a comfortable pace. But the whole "forced adoption" policy just broke too many things all at once and really did not leave me with a path forward.  And that left me holding the bag and trying to explain to a lot of clients why I could not deliver what seemed to be a simple update for a new Microsoft Platform.   You just cannot do that and not expect to cop some flack for it.

Diversification is the only way to manage risk across a broad portfolio.  So now, I have to diversify and spread my position away from Microsoft.  I have to maintain a number of possible solutions on a range of platforms and middle ware rather than relying on MS to be both platform and middleware provider.  The trust is gone.  I have spent more time reviewing tools sets and API's from other platforms over the past year than any time previously.  I have had to develop on a dozen different middle ware packages and push more projects into the cloud that otherwise would have been on the MS desktop.  All because they moved my cheese and pissed all over it.

And for what?  Has the MS position in the market place been strengthened?  Hardly.  I still can't find a supplier in the city who cares about selling surface tablets. There are now just as many Mac products amoung my clients as there are PC.  Chrome books and Android tabs are breeding and market place apps are spawning like crazy salmon.  The monopoly is gone; panicing is just making it worse.






Friday, June 7, 2013

Visual Studio Update fixed flickering bug

Today I happened to start Visual Studio 2012 for an indirect reason and it told me there was an update for NuGet availible.  I let the update install... and then restarted and....   the horrible flickering and endless instability were gone.  

This behaviour has been paralysing my use of Visual Stuido for months.  I guess I can finally get back to the job I have had on hold... once I finish all the others that have filled the vacumme. 

Whoot!

(So, in hind sight... I guess its been the best part of 18 months since I have been able to make meaningful progress on that job due to all the f@#% ups with Visual Studio, Win7/8 and the features that were missing and finally showed up in service pack 1.  While my disgust knows no end... I have been using a bunch of other developement tools recently and know just how polished VS really is... despite some of its crippling flaws)  What a frustrating life we get to lead....

MATLAB Refactoring

Today I hate Matlab. 

My problem is that I have inherited a pile of scripts that have been hacked on by a range of researchers in multiple countries over multiple years to do multiple experiments.... (I hope you get just how ugly that is).  Each of these researchers is a gifted amateur. That is to say, they are very good at hacking in a fairly oldschool procedural style of coding. Which is precicely where everyone starts... no problem there.  The problem is the scaling issue, lack of discipline, quite varied use of idiomatic styles and all the usual code-rot problems of a codebase that has been recycled multiple times without any particular clean-out or clean-up.  Its got gunge!

Where do I start?

Firstly, get my tools lined up. get it under source control, create a working copy...

Tools
Matlab and Notepad++

Now start reading to see what I have to deal with....

As per Matlab convention... they are basically one massive function per file.... some very rudamentary decomposition but still about 5kloc over 4 files.  Shit....

Scads of cryptic variables.  Lots of them seems to be allocated within complex calculations and then used here and there.... then turn into arrays and cell arrays or just get dumped to files where they die.

Lots of magic numbers.....

Lots of one line calculations doing multiple things with multiple cryptic variables and a scatter of magic numbers.

Did I mention the abysmal lack of whitespace.
Did I mention the oldschool style of keeping all names in lower case and minimising the number of characters (looks like they were trying to keep it under 5 characters for some insane reason??/)
Did I mention the lack of meaningful documentation?
Did I mention the lack of any verifiable test for anything?

The only documenation of intent ("Intentional" descriptions) is a bunch of research papers that have been written off the back of this snarl that document what the researchers think they were doing.... which scares me when its very hard to tell if the code actually did that...reliably.

Now to start the refactoring.

Step 0.  Format the Code for readability.

In Matlab (Ctrl+A, Ctrl+I) for the auto-indent function. This works nicely and I have not found any problems with it.

Make sure your functions have the matlab "optional" "End" keyword.

Now where are the styleing tools????  WTF? There are no whitespace tools for matlab... you must be F@#@$% kidding.

Here is the .m file I wrote to fix that.  http://duncanstools.blogspot.com.au/2013/06/matlab-fix-style-tool-to-fix-formating.html

Step 1.  Name stuff. 

Name the functions as meaningfully as you can. 

 This will change as you work through the codebase. But name them to describe their "function" as much as you understand it.

Start naming the variables to describe what they are doing.  

Matlab has some fairly handy tools to rename variables... they are a little flakey and sometimes fail which means manually undoing what you have done.  When this happens I use the find tool to work backward up the file until I find the first instance of that variable and try to rename it at that point. Usually this works.  If all else fails use find and replace....

Step 2. Group Stuff. 

Use the matlab code cells (use a double percent characters with a following space to start a comment "%% " and it will create a different "region" in the code. This is an easy way to "soft" group a region of code that you think is a candidate for extracting into a function.

Start looking for any variables that are "recycled" and split them up.

Start looking at where variables are allocated, initialised and used. Group them together and see if you can package them up into a nice little unit of functionality.

Break out all the repetitious code and sketch out a reusable block that might work to replace them.  Make an class if it will need to hold state data or a function if its just needs some scope.  Beware of Matlabs scope rules... they are a bit weird if you have come from other languages.

Matlab allows you to have multiple functions in the same file.  Just start the file with the "big" function and the put "helper" functions below.  There are no refactoring tools to help you with this but the syntax highlighting and variable highlighting are pretty good and help alot when extracting sections of code manually.

Package up related material and then clean up the packages.  The exercise of packaging is really an exercise of breaking the total "scope" of the code into small managable bits that you can hold in your head all at once.

By driving a structural "fence" through a large peice of code (using functional decomposition), and managing what crosses the fence (passes into and out of functions), you are immediatly simplifying your mental schema. Once you have the system decomposed into chunks of a size that you can hold in your head comfortably, you are done.  Now just look at each chunk and clean it up.   

Step 3. Write Stuff. 

Write comments to document what you think a variable is for.
Write comments to document what a function or group is doing.

The more you write the more clearly the code will come out and the less you need to hold in your mental schema at any point in your coding. This is the objective of all refactoring.  Unload your mental schema of the code so you can get a handle on the whole game. 

Setp 4.  Delete Stuff. 

This is the most pleasant step.  Delete all the crap comments,  bad formatting, irrelevant and duplicate code, old style idioms, bad names, unwanted functionality and anything else you can find that in not being used NOW.  Kill it all.  Make your code shiny and clean.  If you need something later, add it back in... don't try to carry it forward based on a "maybe useful later" kind of logic.  This does not pay off.  Go back to the code in the repository and have a look if you want to refer to something that was in an old version.  Be ruthless.  Get rid of everything that is not "Shiny" and "clean smelling" (to borrow from Fowler et al.)


Does Matlab help or hinder refactoring?

Don't get me wrong, Matlab is a powerful toy with a shiny shell and a big price tag, but its not a productive toolset for larger projects.  Then again, I doubt its intended to be.  So maybe this is just me thinking about it in a way thats inappropriate.

There are some good features built in that provide some basic tools for the refactoring process, but there is little beyond that.

Find and replace Tool.  It's good, but not great.
Block Comment/Uncomment.  It's there and works without mangling the code
Auto-indent.  It's good.
Auto-Style.  NONE.  Check out AStyle or Profactor StyleManager, PolyStyle if you don't know what I mean. Also this article on CodeGuru - MakeCodeNicer by Alvaro Mendez (Took me a lot of effor to find this references. I havn't used this code in 5 years but it sticks in my memory as part of my essential toolkit back then...)

Higher level refactoring.  NONE. Is this a problem or am I just applying Matlab to bigger things that its ready for?

Later all...


Friday, April 19, 2013

Plane hacking or not?


Article about the security presentation 
http://www.net-security.org/secworld.php?id=14733

The denial from the Aviation Authorities
http://www.net-security.org/secworld.php?id=14749

Well meaning clarification from pilot
http://www.askthepilot.com/hijacking-via-android/


This is both a fascinating research paper and a social comedy.

The researcher has demonstrated an interesting exploit against aircraft.  Ok, yet another insecure system. Interesting but only comment worthy for the novelty of the target.

The clearly bullshit ridden  denial from the Aviation Authorities is a nice attempt to damp down the expected alarmist crap from the usual suspects in the media.  However, the denial smells exactly like a denial.  There is really nothing that the FAA etc could say that would be beleived either by the ignorant masses, the ignorant media or technical experts. But its nice that they cared enough to make a statement. 

Finally, the well meaning clarification by the pilot.  Hmmm what can we say here?  Apart from pointing out how well meaning he is.  To put it simply, the guy is an egotistical fucking imbecile.  The whole point of hacking is to take command of a system.  This guy has not understood that pilots are part of a system.  He is arrogant enough to think that pilots are some how "above" it all.  They are uncorruptable, omnipotent and benevolent.  And like all generalisations... this one too is crap.

The evidence is easy to find. Start watching "Air Crash Investigators" or any similar program.  Pilots are human just like everyone else.  Air crews make catastrophic mistakes every day.  Sometimes they survive and sometimes they dont.  The point is that they respond with training and skill, under pressures, time limits and equipment limits.  They trust all sorts of automated systems, instruments and processes.  The point that this research has shown is that some of these automated systems may no longer be as trustworthy as the suppliers and the FAA would want the traveling public to think.

The fact that any system is hackable (read corruptable) is always simply a matter of time and resources.  Every system has weaknesses.  Most people do not have the resources to corrupt the systems around them.  Most of the time the users of those systems "trust" them.  However, the more these systems are revealed as being potentially untrustworthy, the more people are forced to consider what the systems tell them, to pay attention to inconsistencies and be aware of the big picture.  In the case of pilots, it will hopefully make them a little more aware of where the manual controls and old school instruments are located.  It may make them a little more dilligent in keeping their hand-fly skills polished.

Trust in automated systems should have limits.  Robots are only going to take over the world when we let them.  Once humans are totally redundant and a completely automated system that everyone trusts is availible, the human will be fired.  Look at the manufacturing industry.  Look at any industry where data processing has replaced people.  Once we take humans out of the loop and trust the machines there will be a much longer unemployment line.

Its disturbing to see just how many people are no longer needed to keep many large organisations opperating.  Look at all the industries that are down-sizing across the US.  White collar workers are the current ones who are being made redundant simply because knowledge can be managed by software robots. 

Showing this kind of exploit will sharpen a couple of pilots up and perhaps make them a little more paranoid for a while.  It will force the FAA etc to consider the possibility that there are exploitable systems on planes... but the other side of the arms race, the component manufacturers will work hard to rebuild that trust and show that their systems are bullet proof. Eventually everyone will trust them enough to take the humans out of the loop and planes will be completely flown by automated system.  I am suprised that commercial drones have not been trialed yet.  Certainly for freight but I expect eventually for passengers.  The final step will be fully automatic (with a remote manual override for a while).  But human trust will take the humans out of the loop eventually.

Thursday, April 11, 2013

Installation of Psychtoolbox on Matlab

I had a need to set up a matlab environment to work on some legacy code.  The code relied on Psychtoolbox library. So I tried to install this.  The installation runs as a script from within matlab.  Easy enough, but it requires some pre-requisites first.
  • GStreamerSDK 64bit 
  • Subversion Command Line Client
 GStreamer went in smoothly. Installed to the default location.

Already had TortoiseSVN in and working, so ignored this item. 

Stuff that went wrong:

TortoiseSVN does not work without the command line tools. Caused the script to exit.
- Solve this by hand checkout from the repo.

Once the "DownloadPsychtoolbox.m" has failed... you are on your own. 

Script is not able to be re-started without deleting the existing checkout... doh. Start hand reading the scrip to try to figure out how to manually skip ahead.   Found some hints and ran the "SetupPsychtoolbox.m" file from the folder where I checked the files out to.  (In my case "e:\psychtoolbox") This should manually set up the matlab environment path so you can actually use it.

After that, its testing time and lots of debugging.

Ugly Error Message from Outlook.com

I remember when C++ Template Compiler Errors were ugly.  Have a look at the following that just spewed from an MS mail server.

Is this really the kind of thing you want to spit to the client side??? Seriously?


Microsoft.Exchange.Clients.Security.LiveTransientHRESULTException: LiveId authentication code has returned error 0x80049234 PP_E_RPS_REASON_POST_TICKET_TIMEWINDOW_EXPIRED, indicating that there's a temporary problem with the remote server. Please check the Application event log for detailed information and retry the operation later. ---> System.Runtime.InteropServices.COMException (0x80049234): Post ticket time window expired. Ticket could be reposted. at Microsoft.Passport.RPS.Native.IRPSHttpAuth.AuthenticateRawHttp(String siteName, String httpVerb, String path, String QS, String httpVersion, Boolean bHTTPs, String httpHeaders, String httpBody, Object pAuthResultsBag) at Microsoft.Passport.RPS.RPSHttpAuth.Authenticate(String siteName, HttpRequest request, RPSPropBag propBag) at Microsoft.Exchange.Clients.Security.LiveIdAuthentication.Authenticate(HttpContext httpContext, String siteName, String& puid, String& orgIdPuid, String& cid, String& membername, UInt32& issueTime, String& responseHeaders, RPSTicket& rpsTicket, Boolean& hasAcceptedAccrual, UInt32& rpsAuthState) --- End of inner exception stack trace --- at Microsoft.Exchange.Clients.Security.LiveIdErrorHandler.ThrowRPSException(COMException e) at Microsoft.Exchange.Clients.Security.LiveIdAuthentication.Authenticate(HttpContext httpContext, String siteName, String& puid, String& orgIdPuid, String& cid, String& membername, UInt32& issueTime, String& responseHeaders, RPSTicket& rpsTicket, Boolean& hasAcceptedAccrual, UInt32& rpsAuthState) at Microsoft.Exchange.Clients.Security.LiveIdAuthenticationModule.OnAuthenticateRequest(Object source, EventArgs e)

Wednesday, April 10, 2013

Sychronisation of nodes with cloud services

I have read a couple of articles recently about the complexity of synchronisation and reconcilliation across cloud services (apple) and the horror that ensures.

The problems are:

Multi-point synch - The so-called triangle synch or three node synch.
Inconsistent connectivity - Partial synch and partial updates.
Clashes - Multiple nodes over-writing or under-writing each other.
Rollback semantics - How does "undo" function in this kind of environment?

This problem exists in all synchronisation exercises. Be it database sharding, file based backups, database synch across cloud services, multipoint sharing and synch etc.

I have been thinking about various strategies for either getting this to work or mitigating some of the issues.

Topology Issues


Peer to Slave - This is where there is essentially one master "node" and a backup slave device.  In this case the master always wins.  This is basically a backup service.  The Master is the author of everything while the backup device has reader rights only.

Peer to Peer - This is the classsic "sychronisation" where two peer nodes are trying to stay in synch.  In this case both nodes can be authors and both nodes are readers of both nodes product.

Peer to slave to Peer - This is the dreaded three way.  Each Peer has author rights, while all three have reader rights.  So for any change, the system needs to propogate it to the slave and then to the other Peer.  Easy with assured connectivity.  Hard with asychronous and intermittant connectivity. Almost a guarantee of a reconcilliation event at some point.

In most cases higher order topology can be reduced to one of these models, however with asynchronous connectivity, it becomes exponentially complex. 

Data Issues


File based synch - There are lots of these systems and its pretty much a solved problem.  In the higher complexity topologies it simply has an increased probability of a clash.  Easy to have a deterministic resolve rule for clashes like (Add a digit to the end of the file) to prevent data loss, but merging the two versions of the same file is still logically impossible without more information or a pre-conceived rule set for reconcilliation and merging.  This can only be done by the actual application and cannot be done at the transport layer.

Fragment based synch - Such as databases, large binaries, complex data sets, real time collaborative virtual environments etc etc. These get physically ugly and logically ugly really quick, anytime the topology count goes over two.

So is there a solution? 

Possible strategies

Authoratative Model
In this model, one node is made the "Authoratative" node and logically "creates" the data which is then synched to the second (and other) nodes.  This gives a kind of master-slave model.  When synching back to the master, there needs to be some kind of idiot check that when the nodes are out of synch, the masters copy always wins. 

This works for fairly simple use cases with low complexity. However when you have multiple authors for fine grained parts of a system... trouble.

Logical Merge Model
Take the time to create a robust set of merge rules, so that any time there is a conflict, there is a prescribed solution. This may be useful for a set of shared settings, where the most conservative options overwrite less conservative options ( I am thinking about security settings) but in the case of a database of data that has no obvious natural precedence rules we need some other strategy.

Time based Transaction Log
With a database it would be possible to create a set of activity logs and merge them by merging the logs and generating the current data set.  This works for applications that do read or write-only, but falls to bits when you have read, write, modify and delete.  In an asynchronous environment the different node copies can quickly move so far out of synch, they are completely different.

Point by Point Merger
How about avoiding the problem and making the user choose what to over-write.   Show them an option for each conflict and tell them the source of each of the values and let them choose.  (Having seens users who do not want to reconcile automatic backups in word, I can imagine how this would easily fail)

Merge at the time of synch
Theoretically, if the software is in communication with another node, then now is the perfect time to reconcile any conflicts.  Give the users the choice to over-write or keep the data. (assuming its not too complex) This will determine which way the resolution goes. The problem is that its a one-shot deal that will always result in some data being irrovocably lost.

Fail loudly
Simply inform the user that there is a conflict throw an exception and make it sound like its their fault. 

Keep two copies
Keep the previous copy on the node and create a "differece" file with only the conflicts from the synch.  This prevents data loss and gives the user or software time to gracefully merge the values.  There are still logical issues with how the data is merged, and large sets of conflicting transactions may still create some sort of failure state that cannot be automatically fixed.

Thinking thinking,....