Friday, January 23, 2015

Different between single and multiple row indexing

With the following 3 indexes, the "AND" query will use the index with multiple rows, whilst the "OR" query will use the combination of single indexes.

CREATE INDEX user_email_id_index
  ON action_audits
  USING btree
  (user_email COLLATE pg_catalog."default", user_id);

CREATE INDEX user_email_index
  ON action_audits
  USING btree
  (user_email COLLATE pg_catalog."default");

CREATE INDEX user_index
  ON action_audits
  USING btree
  (user_id);







Wednesday, January 21, 2015

Some interview tests for software developers


I. SQL Database

Table: transaction_flows
id (int, PK)
date (date)
amount (bigint)
cash_flow_file_id (int, allow null, FK)
created_at (datetime, allow null)
1
2013-01-01
1000
1
Null
2
2013-01-02
12000
2
Null
3
2013-01-03
8000
Null
2013-01-05 10:00:08

Table: cash_flow_files

Id (int, PK)
created_at (datetime)
body (text)
1
2013-01-06 23:59:59
'Some text A'
2
2013-01-11 00:00:01
'Some text B'

Question 1.1:
Write a SQL statement to list out all records in transaction_flows table and it's corresponding cash_flow_files body.  For records that do not associated with cash_flow_files, the body is expected to be null.


Question 1.2:
Write a SQL statement to update transaction_flows.created_at if it is null, from the value of corresponding cash_flow_files.created_at value.
II. Programming

Question 2.1

Let fn(int x) be a function that
            returns 'buzz' if x is dividable by 3 only,
            returns 'fuzz' if x is dividable by 5 only,
            returns 'wizz' if x is dividable by 7 only. 
            returns a combination of 'buzz', 'fuzz', 'wizz' if x is dividable by 3 and/or 5 and/or 7.  
            Otherwise return 'x' string.

Write unit test(s) for fn(int x) so that if all test(s) passed, the function should be implemented correctly.
(May use any programming language and syntax on any unit test framework)


Question 2.2
Implement fn(int x) described in Question 2.1 in any programming language.
Question 2.3
Implement a function bool IsSymmetric(string s) such that if reverse of s is equal to s, return true, otherwise, return false.
III. System Design

Background Story
            Peter is a movie enthusiast such that he got lots of VCDs, DVDs and BlueRay discs at home.  From time to time he buys new discs and loves to share with his friends.  Now he want to build a system to manage he discs and trace the discs borrowed to his friends.  From his non-technical perspective, he list out his requirements:

  • Keep a movie database.  Including the following attributes.
◦       Name of movie
◦       Cast
◦       Movie category
◦       Movie release year
◦       Disc bought date
◦       Disc price
  • The movie database is searchable from UI.
  • Keep track of the discs borrowed to his friends
◦       When was a disc borrowed.
◦       When a disc is returned.
◦       An email alert will be send to Peter if a disc was borrowed for over 1 month.
  • Only Peter can create new login account for his friends.
◦       Peter's friend will receive an invitation email once account created.
◦       His friend can login the system by their Facebook or Gmail login.
  • What Peter's friend can do on the system:
◦       Browse the movie collections.
◦       Movie reservation
▪       Select a movie.  And select when they want to get it from Peter's home.
▪       When reserved, Peter will receive an email.

Question 3.1
Create a system design includes hardware spec, software spec, system architecture, ER-diagram, and Page UI draft.

Interview Questions

Details on Education and Working Experiences

  •     Education?
  •     Describe the team size of previous positions.
  •     Role on team?
  •     Describe the project management flow of previous positions.
  •     Could you describe the representative project that you had worked on?
  •         What's the achievement?
  •         What's the difficulties?
  •     Experience on communicate with end user?
  •     Interaction with end users?
  •         Product demo?
  •     Approach on problem solving?
  •     How to handle disaster, major bug deployed to production?
  •     Documentations?
  •     Scrum/Agile development experience?  Sprints, PBI, stories, ...
  •     Feature Spec -> Design spec -> Implementation Spec -> Programming...
  •     Overtime?  (I don't encourage, but must focus with good efficiency.)

Key Requirements Review

  •     Team work
  •     Communication
  •     Agile/Scrum
  •     Continues integration
  •     Analysis
  •     Problem solving
  •     Source control
  •     Debugging
  •     Unit tests
  •     QA
  •     User support
  •     Documentation
  •     System administration

Learning Abilities

  •     Ability on learning new programming language.
  •         When and how did you learn programming languages?

Development Knowledge

  •     SDLC experience?
  •         Report issues, bugs.
  •         Experiences on management system such as JIRA.
  •     Experience on unit test.
  •         Has any experience on test driven development?
  •         Test Driven development
  •         Test cases code coverage?
  •         Test automation?
  •     Code refactoring?
  •     Continue integration.
  •     QA testing knowledge?

Technical Know-hows

  •     Hardware knowledge?
  •     RAID 0, 1, 0+1, 5
  •     UDP vs TCP, which protocol is suitable for video streaming?  Why?
  •     IPv4 vs IPv6
  •     Window services or Daemon development experience?
  •     How to debug on Visual Studio Web application?  In case of developer server by VS.  In case of a web application hosted on local IIS.
  •     How to debug on client side, javascript?  (Browser tools like Firebug, Chrome developer tools.)
  •     How do you access database?  Stored Procedure vs Parameterized Query.  Your option?
  •     Tell the different between sql join and left join.
  •     How to debug SQL stored procedure?
  •     System security?
  •     Deployment process details.
  •         By GUI?
  •         By Script?
  •     Experience on version control system, e.g. Svn, Git, Csv?
  •     How to ensure a series of database operations be atomic?
  •     Experience on Linux administration, network configuration.
  •         Cron job
  •         rsync
  •     Experience on AJAX, front-end HTML?
  •     Experience on Cloud?
  •     Experience on NoSQL
  •         e.g. Memcached?
  •     Experience on public web APIs (e.g. Facebook) ?
  •     Web services, restful.  Concept on Restful web service (GET, PUT, POST, DELETE)
  •     What's the difference between static and dynamic programming language.
  •     Regular expression?
  •     Can Apache server serve multiple domain websites with single IP?  With SSL cert?

Others

    Any technical news group do you follows?

Developer's Mindset, Practices

  •     Define top 3 coding practice rules.
  •     Define top 3 team collaboration rules.
  •     What's the most important thing to get things done well? ... It's Passion.
  •     Daily logbook?
  •     Keep knowledge base?
  •     Personal technical blog?
  •     Open source development experience?
  •     How to choose from "Do it well" and "Do it fast" on time pressure?
  •         Technical debt
  •     Code review?

Personal

  •     Career plan?
  •     *** Comfortable with coding convention, guideline and collaboration practice? (e.g. code commit every day, daily scrum meeting, code review)
  •         Play different role on different story.
  •     What's the major achievement on years of development life?
  •     What's the area to be strengthen?
  •     What's the role you want to try in software development industry?
  •     How do you improve yourself?

Programming Tests

    Design a approach to solve a problem in a generic and extendable way ...
        Car service depot - The company has a system with database that takes a car's made, model, year as input.  Customer can check the wanted service.  Then the system can generate a work list for staff.  And cashier charge base on details.
            Car database
                Made
                    Details
                Model
                    Spec
                Year
            Create service list base on made and model.
                refuel_car(car)
                    fuel_diesel(car)
                    fuel_petrol(car)
                    What if we want to support gas in future?
                Cleaning
                    < 1500cc : $200
                    1500cc - 2500cc : $300
                    > 2500cc : $500
                    What if we change the charging plan in future?
                    Configuration file? or store in database?
                Save record with worksheet include worker name and charges.
            Question: What's the problem on the following implementation?  Or what improvement could be made.
                Car -> PetrolCar
                Car -> DieselCar
                Refuel_car(?) { if car is PetrolCar, fuel_petrol; if car is DieselCar, fuel_diesel;}
            Alt Question.
                Create the Refuel_car function.

System design test (Open design, no model answer)

    Online application
        create an online application with private information and file uploads, what's the approach? (on server hardware setup, web security concerns, etc.)
            Upload file handling.
            Prevent web robots - Captcha.
        Security, the basic security for an online application, e.g. loan application?
        CMS, any knowledge?
    Create a simple system including hardware, software to support a DVD lending system at home.
        Hardware
        Software
            ER diagram
        System

        Enhancements:
            Enhance data redundancy, availability
            System security


Introduction to our company and development team.

    Small SME loan.
    Office in Singapore, Philippine, and will be more.
    12 month salary.
    Development team:
        Agile/Scrum development.
        Internal loan management system
        4 developers
        Daily operation support
        System maintenance
        Feature enhancement
        New projects
        Team member will play different role for:
            Analysis
            Coding
            Testing
        Due with change requests.
        Open source learning opportunity
        Comprehensive system development and deployment.

Questions?

Tuesday, January 20, 2015

Extend Ubuntu server disk volume after resizing VM

Check current partitions:
>sudo fdisk -l

Create new partition:
>sudo fdisk /dev/sda
- primary partition
- partition number: 3
- first and last cylinder block
- partition system ID: 8e
- write to disk.

Setup the partition:
>pvcreate /dev/sda3
>vgdisplay
>vgextend [VG Name] /dev/sda3
>pvscan
>lvdisplay
>lvextend [LV Path] /dev/sda3
>resize2fs [LV Path]

DONE

http://www.rootusers.com/how-to-increase-the-size-of-a-linux-lvm-by-expanding-the-virtual-machine-disk/

ssh-copy-id with port

ssh-copy-id "user@host -p 1234"

Monday, January 19, 2015

Fixed Jenkins with upgraded postgresql server and clients

Problem:
pg_dump: server version: 9.3.5; pg_dump version: 9.1.14  pg_dump: aborting because of server version mismatch  rake aborted!  Error dumping database    Solution:  > sudo apt-get remove postgresql-client-8.3  > sudo apt-get remove postgresql-client-9.1  

Jenkins config file

config file: /etc/default/jenkins

Monday, January 12, 2015

Toolbox - Control multiple linux server by ssh - ClusterSSH

mac: brew install csshx
linux: apt-get install cssh/clusterssh

Ubuntu server manual update

sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get autoremove

Upgrade linux problem solved - could not find image

Linux upgrade problem: could not find image vmlinuz...-generic

>sudo apt-get purge linux-image-xxxxxx-generic

Ubuntu server upgrade to latest LTS

Check current version:
>uname -mrs
>lsb_release -a

*Update /etc/apt/source.list if it is necessary.

Do upgrade:
>sudo apt-get update
>sudo apt-get install update-manager-core
>sudo do-release-upgrade

Thursday, January 8, 2015

The Ultimate Guide: 5 Methods For Debugging Production Servers At Scale

Source: http://highscalability.com/blog/2015/1/7/the-ultimate-guide-5-methods-for-debugging-production-server.html




The Ultimate Guide: 5 Methods For Debugging Production Servers At Scale


This a guest post by Alex Zhitnitsky, an engineer working at Takipi, who is on a mission to help Java and Scala developers solve bugs in production and rid the world of buggy software.

How To Approach The Production Debugging Conundrum?

All sorts of wild things happen when your code leaves the safe and warm development environment. Unlike the comfort of the debugger in your favorite IDE, when errors happen on a live server - you better come prepared. No more breakpoints, step over, or step into, and you can forget about adding that quick line of code to help you understand what just happened. In production, bad things happen first and then you have to figure out what exactly went wrong. To be able to debug in this kind of environment we first need to switch our debugging mindset to plan ahead. If you’re not prepared with good practices in advance, roaming around aimlessly through the logs wouldn’t be too effective.

And that’s not all. With high scalability architectures, enter high scalability errors. In many cases we find transactions that originate on one machine or microservice and break something on another. Together with Continuous Delivery practices and constant code changes, errors find their way to production with an increasing rate. The biggest problem we’re facing here is capturing the exact state which led to the error, what were the variable values, which thread are we in, and what was this piece of code even trying to do?

Let’s take a look at 5 methods that can help us answer just that. Distributed logging, advanced jstack techniques, BTrace and other custom JVM agents:

1. Distributed Logging

For every log line we print out, we need to be able to extract the full context to understand what exactly happened there. Some data might come from the logger itself and the location the log is created in, other data needs to be extracted at the moment of the event. One caveat to avoid here is hurting your throughput. The more context you draw out, the bigger performance hit you experience. To test this in practice we ran a benchmark and discovered 7 Logback tweaks to help mitigate this risk (naming the logger by the class name is my favorite one).

What Context Should You Draw Out?

Everything! Where in the code are we, if relevant this can go down to the class we’re in, or even the specific method, which thread is this, and a self assigned transaction ID that’s unique to this request. A transaction ID is key to understanding the full context of an error, since it often travels between your nodes, processes and threads. A good practice to keep here is making sure you generate a UUID at every thread’s entry point to your app. Append the ID into each log entry, keep it for the tasks in your queue, and try to maintain this practice across your machines. We found this to be critical for making sense out of distributed or async logging. It becomes even more powerful when binded together withlog management tools, like Logstash or Loggly, where you can search and tie the knots around the transaction from end to end.

 

When Everything Else Fails - Catch ‘Em All

Uncaught exceptions are where threads go to die. And so does most of the evidence as to what actually happened there. Most of the time the framework you’re using will be able to contain this and show some error message (like YouTube’s custom message dispatching a team of highly trained monkeys to the rescue). For your own way to handle this, the last line of defense would be setting up a Global Exception Handler, like this one in Java:

public static void Thread.setDefaultUncaughtExceptionHandler(

   UncaughtExceptionHandler eh);

void uncaughtException( Thread t, Throwable e) {

   logger.error(“Uncaught error in thread “ + t.getName(), e);

}

This is similar to the things Tomcat or a framework like Akka will give you. Here are 3 ways to extract even more data when an uncaught exception inevitably happens:

  1. Thread names: A nifty little trick is to change your thread name according to the request you’re handling. For example, whenever you’re processing a certain transaction, append its ID to the thread’s name and remove it when you’re done.

  2. Thread-local storage (TLS): A way to keep thread specific data - off the Thread object. You can put there anything that would help identify what went wrong once an error happens. Things like a transaction id, time, or username. Other than this data and the thread name, there’s nothing much you can save when reaching the Uncaught Exception Handler.

  3. Mapped Diagnostic Context (MDC): Similar to the thread-local concept and coming at it from the logging angle, the MDC is part of logging frameworks like Log4j or Logback. It creates a static map at the logger level, and enables a few more advanced features other than TLS.

2. Preemptive Jstack

Most of you Java developers are probably familiar with jstack, a powerful tool that comes with the JDK. In two sentences, it basically allows you to hook into a running process and output all the threads that are currently running in it with their stack trace, frames, either Java or native, locks they’re holding and all sorts of other meta data. It can also analyze heap dumps or core dumps of processes that already don’t exist, a longstanding and super useful toolkit.

BUT… One of the issues it has is that it’s mostly used in retrospect, the bad awful thing has already happened and we’re firing up jstack to recover any clues of what might have caused it. The server isn’t responding, the throughput is dropping, database queries taking forever: A typical output would be a few threads stuck on some nasty database query. No clue of how we got there.

A nice hack that would allow getting the jstack output where it matters most would be activating it automatically when things go south. For example, say we want to set a certain throughput threshold and get jstack to run at the moment it drops:

public void startScheduleTask() {

   scheduler.scheduleAtFixedRate(new Runnable() {

       public void run() {

           checkThroughput();

       }

   }, APP_WARMUP, POLLING_CYCLE, TimeUnit.SECONDS);

}

private void checkThroughput()

{

   int throughput = adder.intValue(); //the adder is inc’d when a message is processed

   if (throughput < MIN_THROUGHPUT) {

       Thread.currentThread().setName("Throughput jstack thread: " + throughput);

       System.err.println("Minimal throughput failed: executing jstack");

       executeJstack();  // See the code on GitHub to learn how this is done

   }

   adder.reset();

}

3. Stateful Jstack

Another issue with jstack is that while it provides very rich meta data about the thread, we’re lacking the actual state that led to the error. This is where manually setting the thread name comes to our rescue again. To be able to understand the source of the error, we need more than just a stack trace. Let’s go back to the nasty database query example, by adding a line like:

Thread.currentThread().setName(Context + TID + Params + current Time, ...);

What once looked like this in jstack’s output and didn’t provide much actionable data:

“pool-1-thread-1″ #17 prio=5 os_prio=31 tid=0x00007f9d620c9800 nid=0x6d03 in Object.wait() [0x000000013ebcc000]

Now looks like this:

”Queue Processing Thread, MessageID: AB5CAD, type: AnalyzeGraph, queue: ACTIVE_PROD, Transaction_ID: 5678956, Start Time: 10/8/2014 18:34″ #17 prio=5 os_prio=31 tid=0x00007f9d620c9800 nid=0x6d03 in Object.wait() [0x000000013ebcc000]

Now we have a better sense of what’s going on. You see what the thread was doing and the parameters it received, including the Transaction ID and Message ID. With these parameters the state that led us here becomes clearer. Now we know which message got us stuck, and can retrace our steps back, reproduce the error, isolate and solve it.

4. BTrace - An Open Source Tracing Tool

The next piece of the puzzle is better visibility into the state of a JVM at runtime. How can we get this kind of data about the state of our JVM without logging and code changes?

One interesting way to tackle this is by using the BTrace Java agent (You can find out more about what Java agents are and what’s the difference between them to native agents righthere. BTrace lets us extract data from a running JVM without adding logging or restarting anything. After attaching the agent, you can hook up to it using the BTrace scripting language. Through scripting, you can instrument the code and grab data that runs through it.

Let’s take a look at some code to get a feel of what the scripting language looks like:

@BTrace public class Classload {

   @OnMethod(

       Clazz=”+java.lang.ClassLoader”,

       method=”defineClass”,

       location=@Location(Kind.RETURN)

    )

    public static void defineClass(@Return class cl) {

       println(Strings.strcat(“loaded ”, Reflective.name(cl)));

       Threads.jstack();

      println(“==============================”);

   }

}

Pretty similar to Java, right? Here we’re grabbing all the ClassLoaders and their subclasses. Whenever “defineClass” returns, the script will print out that the class was loaded and run jstack for us.

BTrace is a useful tool for investigating specific issues but it’s not recommended to use it continuously in production. Since it’s a Java agent with a high level of instrumentation, the overhead could often be significant. It also requires writing specific scripts for anything you’d like to measure and has many restrictions to avoid high overhead and not mess up anything important. For example, it cannot create new objects, catch exceptions, or include loops. With all that, it’s pretty cool to be able to edit scripts during runtime without having to restart your JVM.

5. Custom JVM Agents

While pinpointing the pieces of data we need for debugging is a good practice for logging, JVM agents have much more power and less to almost no extra plumbing requirements. To extract variable values for debugging without any code changes to your server, you need an agent in place. Smart use of agents can practically go around the other methods and serve you most of the data you need for debugging in high scalability.

Like BTrace, you can write your own custom Java agent. One way this helped us was when a certain class was instantiating millions of new objects for some reason, what we did to debug this was write a simple Java agent. The agent would hook to the constructor of that object and anytime the object was allocated an instance, it would get its stack trace. Later we analyzed the results and understood where the load was coming from. This is something BTrace couldn’t help us with since it has many restrictions and can only read data, and here we needed to write to file, log and do other operations that it doesn’t support.

If you’d like to get a feel for how an agent works, here are the few lines that get the whole thing rolling:

private static void internalPremain(String agentArgs, Instrumentation inst) throws IOException {

….

   Transformer transformer = new Transformer(targetClassName);

   inst.addTransformer(transformer, true); // the true flag let’s the agent hotswap running classes

}

A transformer object is created and we register it to the instrumentation object that has the power to change classes. The transformer implementation and the agent’s full source code, are available on GitHub.

The Native Agent And Variable Data

Unlike Java agents, native agents go a step deeper: They’re written in platform dependant native C/C++ code. Java agents have access to the code Instrumentation API, while Native Agents can also access the JVM’s low-level set of APIs and capabilities (JVMTI). This includes access to JIT compilation, GC, monitoring, exceptions, breakpoints and more.

At Takipi, we’re building a next generation production debugger that’s based on a native agent. It requires no code or configuration changes and it’s optimized to run on large scale production systems. Takipi analyzes your caught exceptions, uncaught exceptions, and log errors, showing you the exact state that led there down to the variable level. After attaching the agent to your JVM, you’ll be able to see your errors as if you were there when it happened:

Conclusion

It all boils down to this, the more valuable data you have, the quicker it is to solve the problem. Today when a few extra minutes of downtime are more valuable than ever, the drive to build rather than fix bugs is stronger, and the ability to quickly deploy new code without concerns is essential to succeed: A sound production debugging strategy must be in place.