Sunday, December 18, 2016

We were reviewing the vSPC.py library. This is a virtual serial port concentrator that makes the use of VMware telnet extensions.The mechanism is based on RFC2217 - compatible telnet server.
When a remote system makes a connection request to the target on the ESX server, one virtual machine acts as a virtual serial port server and another acts as a client  The proxy listens for connection requests from the remote system and forwards it to the target This is true in the opposite direction as well. The proxy forwards both ways.
The proxy which  operates as a serial port concentrator has internal connections to several virtual machines in a datacenter and an external connection to a remote system. The concentrator provides a remote system with access to multiple virtual machines that act as serial port servers.
 This is a many to one mapping. The communication happens over a network serial port which uses a network socket on the host computer. A network socket is the endpoint of a network connection and is represented by an IP address, protocol and a port number. The network serial port must be supported by the ESX and then created or reconfigured on a virtual machine.
Virtual serial ports come in handy for backup and backing option.  They remain up even when the virtual machines go through vMotion.  To support this kind of persistent connection, the proxy makes two telnet connections for the virtual machine.  The ESX server supports a telnet extension specific to VMWare that allows the proxy to postpone the vMotion event until it finishes forwarding content. The ESX server sends a vmotion-begin  command and the proxy responds with a vmotion-goahead command. During this time, the proxy buffers any additional data it receives from the remote system. When the vMotion is complete, the proxy continues the content transmission to the new instance of the virtual machine.  When the new instance of the virtual machine boots up, the ESX server configures network backing for the virtual serial port and establishes  a second telnet connection with the proxy. Before continuing with the vMotion operation, the new virtual machine instance and the proxy renegotiate the telnet COM-PORT-OPTION without the proxy losing the com-port-option for the original instance. The proxy now supports one telnet connection for each instance. After the proxy accepts a new virtual machine instance as a peer, the ESX host on the new instance sends a vmotion-complete to the proxy so that it can release the original telnet connection.

Console access is available even from DRAC over ip as shown here : http://www.slac.stanford.edu/grp/cd/soft/unix/EnableSerialConsoleAccessViaSSH.htm

and explained here : https://1drv.ms/w/s!Ashlm-Nw-wnWlk6DmH-B9_C1dul6 

#codingexercise

Given  a binary tree with positive and negative values, find the maximum sum in a path through the parent. The path may start and end at any node in the tree.

int GetMaxPath(node root, ref int sum)
{
if (root == null) return 0;

var left  = GetMaxPath(root, ref sum);
var right = GetMaxPath(root, ref sum);
var max_one = max(root.data,
                                 max(left, right) + root.data));
sum =  Max(max_one,
                   left + right + root.data,
                   sum);
return max_one;
}
GetMaxPath(tree_top, int_min);


Determine if two trees are isomorphic
Two trees are isomorphic if the left tree and the right tree are identical.
bool isIsomorphic(Node root1, Node root2)
{
if (root1 == null && root2 == null) return true;
if (root1 == null || root2 == null) return false;
if (root1.data != root2.data) return false;
 if   (((isIsomorphic(root1.left, root2.left) && isIsomorphic(root1.right, root2.right)) ||
      ((isIsomorphic(root1.left, root2.right) && isIsomorphic(root1.right, root2.left)))
{
return true;
}
return false;
}

find the length of the longest arithmetic progression in an array

int GetLongestAP(List<int>numbers)
{
var progressions = new List<List<int>>();
var candidate = new List<int>();
numbers.ForEach( x => candidate.Add(-1));
int start = 0;
int level = 0;
Combine(numbers, ref candidate, ref progressions, start, level); // already implemented in this blog
but with the enhancement that we reject combinations that are not isAP();
return progressions.Max(x => x.Count(y => y != -1)).count;
}

bool isAP(List<int> numbers)
{
if (numbers == null || numbers.count <=2) return false;
int diff = numbers[1] - numbers[0] ;
for (int i = 2; i <numbers.count; i++)
    if (numbers[i]-numbers[i-1] != diff)
        return false;
return true;
}

Saturday, December 17, 2016

Yesterday we were talking about serial port and the pyserial library. Today we review the vSPC.py library. This is a virtual serial port concentrator that makes the use of VMware telnet extensions.
Its requirements are simple.
 A Linux VM w/Python 2/3
a vSPC.py script installed on the VM.
configure it to start on boot
enable local firewall rules to permit 13370/tcp, 13371/tcp and a range of ports for the targets.
This is enough to configure a virtual serial port concentrator host VM.
To configure the target, we add a serial port to the VM with the following settings:
Type : Network
Direction : Server
Port URI: vSPC.py
Use Virtual Serial Port Concentrator : <checked>
vSPC URI: telnet://vspc.local.lan:13370
Yield CPU on Poll : <checked>

To enumerate the connections from the target, we simply issue
locally : .vSPC.py localhost
remote : vSPC.py vspc.local.lan
The advantages of a serial port concentrator over statically mapped ones include :

It handles dynamic port assignment which can be queried. Static port assignments cannot be queried. The access to the target is never lost.
You no longer need the VMware console access and authorization.
The static ports are mapped onto the ESXi server which requires firewall to be opened for ESXi but vSPC runs on the local VM.
vSPC works on any Linux flavors.

The mechanism is based on RFC2217 - compatible telnet server.  The proxy which  operates as a serial port concentrator has internal connections to several virtual machines in a datacenter and an external connection to a remote system. The concentrator provides a remote system with access to multiple virtual machines that act as serial port servers.
 This is a many to one mapping.
When a remote system makes a connection request to the target on the ESX server, one virtual machine acts as a virtual serial port server and another acts as a client  The proxy listens for connection requests from the remote system and forwards it to the target This is true in the opposite direction as well. The proxy forwards both ways.
#codingexercise
        static int GetKthSmallest(int[,] A, int row, int col, int k)
        {
            int r = 0;
            int c = 0;
            int maxr = 0;
            int maxc = 0;
            int prev = -1;
            if (k <= 0 || k < prev) return -1;
            int count = 0;
            while (count < k)
            {
                // compare right and bottom and increment r or c
                // the idea is that the k largest elements will be a contiguous block 
                // and the next element for inclusion will be either to the right of this block or 
                // at the bottom of this block
                // we just need to propagate the front on all rows one cell at a time.
                if (count + 1 == k) {  return A[r, c]; }

                int rselected = r * col + c; // position of selected at bottom
                int cselected = r * col + c; // position of selected to right
                int rmax = Int16.MaxValue;  // max value on top or at left
                for (int y = 0; y <= c ; y++)
                {
                    if (r >= row - 1) break;
                    var candidate = A[r+1,y];
                    if (r < row - 1 && candidate < rmax &&
                        (prev == -1 || candidate > A[prev/col, prev%col]))
                    {
                        rmax = A[r + 1, y];
                        rselected = (r + 1) * col + y;
                    }
                    if (maxr >= row - 1) break;
                    candidate = A[maxr + 1, y];
                    if (maxr < row - 1 && A[maxr + 1, y] < rmax &&
                        (prev == -1 || candidate > A[prev/col, prev%col]))
                    {
                        rmax = A[maxr + 1, y];
                        rselected = (rmax + 1) * col + y;
                    }
                }
                for (int x = 0; x <= r; x++)
                {
                    if (c >= col - 1) break;
                    var candidate = A[r, c + 1];
                    if (c < col - 1 && candidate < rmax &&
                        (prev == -1 || candidate > A[prev/col, prev%col]))
                    {
                        rmax = A[r, c + 1];
                        rselected = r * col + c + 1;
                    }
                    if (maxc >= col - 1) break;
                    candidate = A[r, maxc + 1];
                    if (maxc < col - 1 && candidate < rmax &&
                        (prev == -1 || candidate > A[prev/col, prev%col]))
                    {
                        rmax = A[r, maxc + 1];
                        rselected = r * col + maxc + 1;
                    }
                }
                prev = r * col + c;
                r = rselected / col;
                c = rselected % col;
                if (r > maxr) maxr = r;
                if (c > maxc) maxc = c;
                count++;
            }
            return A[r, c];
        }
    class Program
    {
        static void Main(string[] args)
        {
            var A = new int [4, 4] {{10, 13, 15, 19 }, {21, 23, 24, 27}, {29, 31, 33, 37}, {41, 43, 45, 47}};
            for (int k = 1; k < 17; k++)
            {
                Console.WriteLine("K={0},Value={1}", k, GetKthSmallest(A, 4, 4, k));
            }
       }
    }

K=1,Value=10
K=2,Value=13
K=3,Value=15
K=4,Value=19
K=5,Value=21
K=6,Value=23
K=7,Value=24
K=8,Value=27
K=9,Value=29
K=10,Value=31
K=11,Value=33
K=12,Value=37
K=13,Value=41
K=14,Value=43
K=15,Value=45
K=16,Value=47

Friday, December 16, 2016

Recently I was looking for libraries to write to the serial port on Linux machines so that I could simulate a KVM switch. The PySerial package comes very useful here.
Some examples borrowed from online tutorials and reposted here:


import time
import serial

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
    port='/dev/ttyUSB1',
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

ser.isOpen()

print 'Enter your commands below.\r\nInsert "exit" to leave the application.'

input=1
while 1 :
    # get keyboard input
    input = raw_input(">> ")
    if input == 'exit':
        ser.close()
        exit()
    else:
        ser.write(input + '\r\n')
        out = ''
        time.sleep(1)
        while ser.inWaiting() > 0:
            out += ser.read(1)

        if out != '':
            print ">>" + out

We could also talk to a DRAC card.
#codingexercise:
  static int GetKthLargest(int[,] A, int row, int col, int k)  
            {  
            int r = row-1;  
            int c = col-1;  
            int prev = r * col + c; 
           if (k <= 0 || k > prev) return -1;
            int count = 0;  
            while ( count < k)  
            {  
            // compare left and top and increment r or c  
            // the idea is that the k largest elements will be a contiguous block   
            // and the next element for inclusion will be either to the left of this block or   
            // on the top of this block  
            // we just need to propagate the front on all rows one cell at a time.  
            int m = r;  
            int n = c;  
            int rselected = r*col + c; // position of selected on top  
            int cselected = r*col + c; // position of selected at left  
            if (count + 1 == k) return A[r,c];   
            int rmax = Int16.MinValue;  // max value on top  
            int cmax = Int16.MinValue; // max value at left  
            for (int j = n ; j < col && m > 0; j++ )  
            {  
               if ( A[m-1, j] > cmax){  
                    rselected = (m-1)*col+j 
                    cmax = A[m-1,j];  
               }else break;  
            }  
            for (int i = row-1; i >= m && n > 0; i--)  
            {  
               if ( A[i, n-1] > rmax){  
                    cselected = i*col+n-1;  
                    rmax = A[i, n-1];  
               }else break;  
            }  
            if (cmax > rmax) 
            {  
               r = rselected/col;  
               c = rselected%col; 
                
            }else{  
               r = cselected/col;  
               c = cselected%col; 
                
            }  
            if ((r+1)*col + c == prev) 
             {   
                  prev = r*col + c;   
                  row--;   
              }  
            count++;  
            }  
            return A[r,c];  
            } 
    class Program     {         static void Main(string[] args) 
         {
            var A = new int [4, 4] {{10, 13, 15, 19 }, {21, 23, 24, 27}, {29, 31, 33, 37}, {41, 43, 45, 47}}; 
            for (int k = 1; k < 17; k++) 
            { 
                Console.WriteLine("K={0},Value={1}", k, GetKthLargest(A, 4, 4, k)); 
            }
         }
      } 
K=1,Value=47 
K=2,Value=45 
K=3,Value=43 
K=4,Value=41 
K=5,Value=37 
K=6,Value=33 
K=7,Value=31 
K=8,Value=29 
K=9,Value=27 
K=10,Value=24 
K=11,Value=23 
K=12,Value=21 
K=13,Value=19 
K=14,Value=15 
K=15,Value=13 
K=16,Value=10 

also we can optimize the above by removing the inner iterations because they are already sorted and cmax or rmax can be picked and compared.