Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Wednesday, October 16, 2019

PySpark getting started

In this post I'm going to show first steps for working with next components of PySpark:  RDDs and DataFrames.

To start working with PySpark we have 2 options:
-  python spark-shell from spark distro
-  setup dev env by our own

Let's make a closer look on both of them.

Option 1: Spark-shell

Simplest way to play with pyspark is using python spark-shell. First you have to download Spark from official web page(https://spark.apache.org/downloads.html). Next, unpack it and run "pyspark" from "bin" folder. You should see something like this:

Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 2.4.4
      /_/

Using Python version 2.7.15+ (default, Oct  7 2019 17:39:04)
SparkSession available as 'spark'.


And we're ready to go! Let's try some basic operations:


>>> rdd1 = spark.parallelize([('Joe',1980), ('Huan',1978), ('Max', 1985) ])

>>> rdd1.take(1)
[('Joe', 1980)]

>>> rdd1.collect()
[('Joe', 1980), ('Huan', 1978), ('Max', 1985)]

>>> rdd1.collect()[1]
('Huan', 1978)

It's definitely enough for "playing" with PySpark, but for complex applications it's not an option: we need to setup dev env.

Option 2: setup PySpark dev env


Python setup

In my ubuntu I have both pythons 2 and 3 installed, but default is 2. To use python 3 I updated bash profile file:   ~/.bashrc : I added line
alias python=python3

Let's check:
~$ python --version
Python 3.6.8

Great! 

Pip3 

Next, let's install pip3: 
sudo apt-get -y install python3-pip

For me, after installation pip3 was not working, so I had to modify file /usr/bin/pip3 :

#from pip import main
from pip import __main__
if __name__ == '__main__':
#    sys.exit(main())
    sys.exit(__main__._main())

And let's check it: 
~$ pip3 --version
pip 19.2.3 from /home/dmitry/.local/lib/python3.6/site-packages/pip (python 3.6)

It works! 

Pipenv

Now let's install pipenv using just installed pip3:
~$ sudo pip3 install pipenv
Installing collected packages: pipenv
Successfully installed pipenv-2018.11.26

Dev env

And now we're finally ready to go! 

Next let's create a folder for our test application:

mkdir pyspark-test
cd pyspark-test

Now let's create a virtual env using pipenv: 
pyspark-test$ pipenv shell
Creating a virtualenv for this project…
✔ Successfully created virtual environment! 


Next, we can try to add some dependencies:
(pyspark-test) pyspark-test$ pipenv install pyspark
Installing pyspark…
✔ Success! 
Updated Pipfile.lock (1869ad)!
Installing dependencies from Pipfile.lock (1869ad)…

Let's check:
(pyspark-test) pyspark-test$ pip3 freeze
py4j==0.10.7
pyspark==2.4.4

- looks good: all dependencies are in place.

Finally everything is prepared for coding! I created folder "src" and file "main.py" inside with next content:

from pyspark.sql import SparkSession

if __name__ == '__main__':
        spark = SparkSession.builder.appName("MyTestApp").getOrCreate()

        rdd1 = spark.sparkContext.parallelize([('Joe',1980), ('Huan',1978), ('Max', 1985) ])
        print("Count: ", rdd1.count())
        print("First: ", rdd1.take(1))




Let's run it now:

(pyspark-test) pyspark-test$ python ./src/main.py 

Count:  3                                                                       
First:  [('Joe', 1980)]

Cool! Our environment is ready for coding! 


RDD

First it's better to read about RDD from official web page: https://spark.apache.org/docs/latest/rdd-programming-guide.html

In shorts:
The main abstraction Spark provides is a resilient distributed dataset (RDD), which is a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel. RDDs are created by starting with a file in the Hadoop file system (or any other Hadoop-supported file system), or an existing Scala collection in the driver program, and transforming it. Users may also ask Spark to persist an RDD in memory, allowing it to be reused efficiently across parallel operations. Finally, RDDs automatically recover from node failures.



In a code provided below I'm showing operations which can performed on RDDs:
- rdd creation: in memory and reading from file
- rdd actions: count, take
- rdd transformations: map, flatMap, filter


from pyspark.sql import SparkSession

def main():
    # init spark
    spark = SparkSession.builder.appName("MyTestApp").getOrCreate()
    sc = spark.sparkContext

    # create rdd "in-memory"
    rdd1 = sc.parallelize([('Joe', 1980), ('Huan', 1978), ('Max', 1985)])
    print("RDD1 Count: ", rdd1.count()) #RDD1 Count:  3 
    print("RDD1 First: ", rdd1.take(1)) #RDD1 First:  [('Joe', 1980)]

    # create rdd by reading from file
    rdd2 = sc.textFile("test/test-data/groups.csv") 
    print("RDD2 All: ", rdd2.take(10)) #RDD2 All:  ['101,Admin', '102,Dev', '103,DB']

    # RDD transformation using MAP method
    rdd2formatted = rdd2 \
        .map(lambda line: line.split(",")) \
        .map(lambda arr: (arr[0], arr[1]))
    print("RDD2Formatted All: ", rdd2formatted.take(10)) 
    #RDD2Formatted All:  [('101', 'Admin'), ('102', 'Dev'), ('103', 'DB')]

    # RDD filtering using FILTER method
    rdd2filtered = rdd2formatted.filter(lambda row: int(row[0]) > 101)
    print("RDD2Filtered All: ", rdd2filtered.take(10))
    #RDD2Filtered All:  [('102', 'Dev'), ('103', 'DB')]

    # Flattening RDD
    rdd2FilteredFlat = rdd2filtered.flatMap(lambda row: (row[0], row[1]))
    print("RDD2FilteredFlat All: ", rdd2FilteredFlat.take(10))
    #RDD2FilteredFlat All:  ['102', 'Dev', '103', 'DB']


if __name__ == '__main__':
    main()

p.s. content of "test/test-data/groups.csv" is following:
101,Admin
102,Dev
103,DB



DataFrame

First, I would again suggest to read official documentation: https://spark.apache.org/docs/latest/sql-programming-guide.html.
In shorts, if you know what is RDD -  it's very easy to understand what is DataFrame: it'a a RDD + Schema. Where schema is an information about field names and types. If we have structured data like JSON, CSV - we can just read them using spark and it will take the schema from files(in case of CSV - from header).

A DataFrame is a Dataset organized into named columns. It is conceptually equivalent to a table in a relational database or a data frame in R/Python, but with richer optimizations under the hood. 


Below I'm showing: how to create dataFrame, some basic operations, how to join them. Most interesting thing here: there are to ways for data transformtion here:
- using Spark API
- using Spark SQL

from pyspark.sql import SparkSession

def main():
    # init spark
    spark = SparkSession.builder.appName("MyTestApp").getOrCreate()
    sc = spark.sparkContext

    # create DataFrame from RDD
    rdd1 = sc.parallelize((
    """{"id": "1001", "name": "Joe",  "depId": 101}""",
    """{"id": "1002", "name": "Huan", "depId": 102}""", 
    """{"id": "1003", "name": "Max",  "depId": 103}"""
    ))
    print(rdd1.take(2)) 
    # ['{"id": "1001", "name": "Joe",  "depId": 101}', '{"id": "1002", "name": "Huan", "depId": 102}']    
    df1 = spark.read.json(rdd1)
    df1.show()
    # +-----+----+----+
    # |depId|  id|name|
    # +-----+----+----+
    # |  101|1001| Joe|
    # |  102|1002|Huan|
    # |  103|1003| Max|
    # +-----+----+----+

    # Basic operations using Spark API
    df1.select("name", "depId").where("id='1001'").show()
    #+----+-----+
    #|name|depId|
    #+----+-----+
    #| Joe|  101|
    #+----+-----+    

    # Basic operation using Spark SQL
    df1.createOrReplaceTempView("users")
    spark.sql("SELECT concat(name,' has id>1001') as user_name FROM users WHERE id>1001").show()
    #+----------------+
    #|       user_name|
    #+----------------+
    #|Huan has id>1001|
    #| Max has id>1001|
    #+----------------+

    # create DataFrame by reading from file
    df2 = spark.read.option("header",True).csv("test/test-data/depts.csv")
    df2.show()
    #+-----+-------+
    #|depId|depName|
    #+-----+-------+
    #|  101|  Admin|
    #|  102|    Dev|
    #|  103|     DB|
    #+-----+-------+

    # join 2 DataFrames using Spark API
    joined1 = df1.join(df2, df1.depId==df2.depId).drop(df2.depId)
    joined1.show()
    #+-----+----+----+-------+
    #|depId|  id|name|depName|
    #+-----+----+----+-------+
    #|  101|1001| Joe|  Admin|
    #|  102|1002|Huan|    Dev|
    #|  103|1003| Max|     DB|
    #+-----+----+----+-------+    

    # join 2 DataFrames using Spark SQL
    df2.createOrReplaceTempView("deps")
    joined2 = spark.sql("SELECT u.id, u.name, d.depName FROM users u, deps d WHERE u.depId = d.depId")
    joined2.show()
    #+----+----+-------+
    #|  id|name|depName|
    #+----+----+-------+
    #|1001| Joe|  Admin|
    #|1002|Huan|    Dev|
    #|1003| Max|     DB|
    #+----+----+-------+





if __name__ == '__main__':
    main()





The end

And that is basically it. Of course it's impossible to show all RDD and DataFrame stuff in one post: it would be a book - so I just tried to show some very basic stuff for understanding "who is who" :)

Sunday, March 18, 2018

Python: getting started


Intro

Last time Python is getting more and more popular in BigData word.
From wiki:
Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, and a syntax that allows programmers to express concepts in fewer lines of code,[26][27] notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales.[28]
Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library.[29]
Python interpreters are available for many operating systems. CPython, the reference implementation of Python, is open sourcesoftware[30] and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.

From official documentation:
Python is powerful... and fast; 
plays well with others; 
runs everywhere; 
is friendly & easy to learn; 
is Open.


Installation

Installation process may vary depending on operational system: it can be installation on windows or just execution of "apt-get" in linux, but anyway, on official site you can find any information you need. 

Python shell

Easiest way to play with python - command shell, which can be open by running "python" command:

demien$ python
Python 2.7.13 (default, Nov 24 2017, 17:33:09)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Now we can output standard "hello world" greeting message: 
>>> print("hello world")
hello world


Variables can be created by simple "=" operator: 
>>> name = "Huan Sebastyan"
>>> print("hello, {0} !!!".format(name))
hello, Huan Sebastyan !!!


PY Files

For long programs, python shell is not an option: it's better to put program content into file(or files) with extension ".py"  and run it by executing: python myprogram.py.  In code examples below I'm writing the code into file test.py  and executing it by running: python test.py. 

The main issue with Python files are the "blocks" of code : Python doesn't have {} or begin end operators to define scope(beginning and ending) of block, function or class. For this purpose Python use spaces: 

operator1
operator2 
def myFunction:
    function operator1
    function operator2
operator 3


Conditions in Python

Conditions are written without any bracers and of course for block inside condition we should use spaces to define begin and end:  

name = raw_input("What is your name? ")
greeting =""
if name == "Huan Sebastyan":
greeting = "Buenos dias"
else:
greeting = "Hello"
print("{0}, {1} !!!".format(greeting, name))

execution:

demien$ python test.py
What is your name? Joe
Hello, Joe !!!

demien$ python test.py
What is your name? Huan Sebastyan
Buenos dias, Huan Sebastyan !!!

Loops

There several types of loops in python: while and for

While loop:


value=""
while value!="end":
value = raw_input("Enter 'end' to quit or anything else to continue: ")
print("you entered:{0}".format(value))
print("you did it!")


execution: 
demien$ python test.py
Enter 'end' to quit or anything else to continue: hello
you entered:hello
Enter 'end' to quit or anything else to continue: world
you entered:world
Enter 'end' to quit or anything else to continue: end
you entered:end
you did it!

For loop:

count = int(raw_input("enter iteration count: "))
for i in range(1, count+1):
s = ""
for j in range(1, i+1):
s+="*"
print(s)

execution:
demien$ python test.py
enter iteration count: 5
*
**
***
****
*****


Functions

Definition begins with keyword "def" , bracers used for parameters: 


x = 10
y = 20

def test(param):
global x
y = 20
x=x+1
y=y+1
print("from function context: param={0}, x={1}, y={2}".format(param, x, y))
return "BYE!"

result = test("HELLO!")
print("from global context: result={0}, x={1}, y={2}".format(result, x, y))

Execution:
demien$ python test.py
from function context: param=HELLO!, x=11, y=21
from global context: result=BYE!, x=11, y=20


Modules

For big programs it's impossible to keep all code in one file. Python provides concept MODULE for this: 
Let's create a simple module in subfolder "tools":

tools/simple.py: 

def sayHi(name):
print("Hi, {0}".format(name))
__version__ = "0.0.1"

If we want to use it, beside module itself we also need an empty file __init__.py in the same folder(in subfolder "tools"):
demien$ ls -la tools/*.py
-rw-r--r-- 1 demien demien  0 mar 11 14:49 tools/__init__.py
-rw-r--r-- 1 demien demien 78 mar 11 14:46 tools/simple.py

Now we can use this module from our main program: 

import tools.simple as simple

simple.sayHi("Joe")


Execution: 
demien$ python test.py
Hi, Joe


Sometimes we may need to understand if the code is running by "direct" execution, or by importing it as module. For this we can check condition: if __name__ == "__main__":
- if it returns true, the code is being executed in "direct" mode. Our current module by direct execution produce no output. Let's update our module to produce some output, but only in case of "direct" execution: 

def sayHi(name):
print("Hi, {0}".format(name))
__version__ = "0.0.1"
if __name__ == "__main__":
sayHi("Huan Sebastyan")


So, now we can run our module in a direct way: 

demien$ python tools/simple.py
Hi, Huan Sebastyan

And now let's use it as module: 

demien$ python test.py
Hi, Joe

- output remained the same. 


Dir function

This function is showing "content" of variables and methods defined in module: 

>>> import tools.simple
>>> dir(tools.simple)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', 'sayHi']


Collection classes

there several collection classes in Python: lists, dictionary, set, tuples

Lists

It's a mutable structures for storing data in arrays.

colors = ["red", "black", "white"]
print "there are ",len(colors)," colors in my list:"
for color in colors:
print(color)

colors.append("blue")
colors.append("green")
print "few more there added, now it's ",len(colors)," of them"

colors.sort()
print("sorted:", colors)

del colors[0]
del colors[0]
print("first 2 were deleted:", colors)

Execution: 
demien$ python test.py
there are  3  colors in my list:
red
black
white
few more there added, now it's  5  of them
('sorted:', ['black', 'blue', 'green', 'red', 'white'])
('first 2 were deleted:', ['green', 'red', 'white'])

Tuples

Similar to lists  but they are immutable

answer = ("yes", "no")
print answer[0]
print answer[1]
execution:
demien$ python test.py
yes
no


Dictionary

It's structure like Map or Associated array. 

user = {
"name" : "Joe",
"surname" : "Black",
"address" : {
"country" : "USA",
"city" : "Houston"
}
}

print user["name"]
print user["address"]
print user["address"]["city"]

print "full list of pairs[key,value] in user dictionary:"
for key, value in user.items():
print "key=", key, " value=", value


Execution:
demien$ python test.py
Joe
{'country': 'USA', 'city': 'Houston'}
Houston
full list of pairs[key,value] in user dictionary:
key= surname  value= Black
key= name  value= Joe
key= address  value= {'country': 'USA', 'city': 'Houston'}


Sequence operations. 

Structures like lists, tuples and strings have list of common "sequence" operations.

colors = ["red", "black", "white", "blue", "gray", "green", "orange"]
colors.sort()
print colors

print('color 2 is', colors[2])
print('color -2 is', colors[-2])

print('colors 1 to 3 is', colors[1:3])
print('colors 2 to end is', colors[2:])
print('colors 1 to -1 is', colors[1:-1])
print('colors start to end is', colors[:])

Execution:
demien$ python test.py
['black', 'blue', 'gray', 'green', 'orange', 'red', 'white']
('color 2 is', 'gray')
('color -2 is', 'red')
('colors 1 to 3 is', ['blue', 'gray'])
('colors 2 to end is', ['gray', 'green', 'orange', 'red', 'white'])
('colors 1 to -1 is', ['blue', 'gray', 'green', 'orange', 'red'])
('colors start to end is', ['black', 'blue', 'gray', 'green', 'orange', 'red', 'white'])


Set

Another collection structure is Set. On sets we can apply some math logic, like AND, OR, XOR: 

colors1 = set(["red", "black", "white"])
colors2 = set(["white", "blue", "gray"])
print(colors1)
print(colors2)

print("& : ", colors1 & colors2)
print("| : ", colors1 | colors2)
print("^ : ", colors1 ^ colors2)
Execution: 
demien$ python test.py
set(['white', 'black', 'red'])
set(['blue', 'gray', 'white'])
('& : ', set(['white']))
('| : ', set(['blue', 'gray', 'black', 'white', 'red']))
('^ : ', set(['blue', 'gray', 'black', 'red']))



Classes

Main issues with  OOP in Python are:
- classes are being created without "new" keyword:  userJoe = User("Joe", "Black")
 - constructor has name: __init__
 - variables defined in class definition are class(not object) variables and should be accessed by className.variableName
 - "self" stands for "this" variable, and used for definition of object variables: self.name = name
-  methods which are using object variables have to explicitly define self as first input parameter: def sayHi(self)
- to define subclass, superclass name has to be passed as a "parameter" for subclass name: class AdminUser(User)
- to call superclass method (even constructor) format should be SuperClassName.SuperClassMethod: User.__init__(self, name, surname)


Example: 

class User:
userCount = 0

def __init__(self, name, surname):
self.name = name
self.surname = surname
User.userCount+=1
print("User #{0} was created!".format(User.userCount))

def sayHi(self):
print("Hi, I'm {0} {1}".format(self.name, self.surname) )

class AdminUser(User):
def __init__(self, name, surname, role):
User.__init__(self, name, surname)
self.role = role

def sayHi(self):
User.sayHi(self)
print(" and I'm the {0} !!!".format(self.role))

userJoe = User("Joe", "Black")
userJoe.sayHi()

userHuan = User("Huan", "Seastyan")
userHuan.sayHi()

userAdmin = AdminUser("Super", "Admin", "boss")
userAdmin.sayHi()
Execution: 
demien$ python test.py
User #1 was created!
Hi, I'm Joe Black
User #2 was created!
Hi, I'm Huan Seastyan
User #3 was created!
Hi, I'm Super Admin
  and I'm the boss !!!

Files

For working with files all we need is "file()" operation which takes parameters : 
1. file name
2. mode: read or write 

Let's create simple file in.txt with 2 lines of text: 
it's a test file
just as example

Now let's create a simple program which will convert this file to uppercase and write it into "out.txt" file: 

inFile = file("in.txt", "r")
outFile = file("out.txt", "w")

eof = False
while eof == False :
line = inFile.readline()
if len(line)==0:
eof = True
else:
outFile.write(line.upper())

inFile.close()
outFile.close()


Execution result: 
out.txt:
IT'S A TEST FILE
JUST AS EXAMPLE

Pickle

Module pickele (which should be imported) provides ability to save the object into file in "serialized" format. And, of course, later we can read it and deserialize back to original object. 

import pickle

class User:
userCount = 0

def __init__(self, name, surname):
self.name = name
self.surname = surname
User.userCount+=1
print("User #{0} was created!".format(User.userCount))

def sayHi(self):
print("Hi, I'm {0} {1}".format(self.name, self.surname) )

userJoe = User("Joe", "Black")

fout = open("joe.bak", "wb")
pickle.dump(userJoe, fout)
fout.close()
del(userJoe)

fin = open("joe.bak", "rb")
restored = pickle.load(fin)
print(restored)
restored.sayHi()
fin.close()

Execution: 
demien$ python test.py
User #1 was created!
<__main__.User instance at 0x7f05c0296ef0>
Hi, I'm Joe Black

Exceptions

Python has similar to other languages system of error handling with TRY, EXCEPT (which stands for CATCH) and FINALLY. On next example we are handling keyboard input  exceptions such as pressing Ctrl+C during input and raising our own exception if input length is less than expected: 

class ShortInputException(Exception):
"""A user-defined exception class."""

def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast


try:
text = raw_input("Enter something ....")
if len(text) < 3 :
raise ShortInputException(len(text), 3)

except EOFError:
print("Why did you do an EOF on me?")

except KeyboardInterrupt:
print("You cancelled the operation.")

except ShortInputException as ex:
print(("ShortInputException: The input was " +
"{0} long, expected at least {1}")
.format(ex.length, ex.atleast))

else:
print("You entered {}".format(text))

finally:
print("done")


Execution: 
demien$ python test.py
Enter something ....12345
You entered 12345
done

demien$ python test.py
Enter something ....12
ShortInputException: The input was 2 long, expected at least 3
done

demien$ python test.py
Enter something ....^CYou cancelled the operation.
done


Try with resource: WITH

If we are opening something in TRY block, very often we have to close it in a FINALLY block (try with resource). To make this "automatically" we can use WITH construction: opened resource will be closed automatically: 

with open("in.txt") as fin:
for line in fin:
print(line)



The end

As for me, python has a lot of common with javascript: dynamic typing, inheritance, but more focused on "back-end" development of scripting. It's very simple but powerful.  Now a lot of big data frameworks are providing python api, so it's better to be familiar with this language. 

Wednesday, February 14, 2018

Kubernetes getting started: Minikube

0. Intro: What is Kubernetes?

From wiki:
Kubernetes (commonly referred to as "K8s"[3]) is an open-source system for automating deployment, scaling and management of containerized applications[4] that was originally designed by Google and now maintained by the Cloud Native Computing Foundation. It aims to provide a "platform for automating deployment, scaling, and operations of application containers across clusters of hosts".[3] It works with a range of container tools, including Docker.

In shorts, kubernetes is a tool which allows you to upload in it many docker images, link them by services, scale and configure them.


1. Minikube:  simple image of kubernetes "to play". 

The simplest way to get familiar with kubernetes is Minikube. Let's install it.


1.1 Virtual box installation. 

It also can be running using HyperV, but I prefer Virtual box. It can be download from here.

1.2 Docker installation.

Theoretically, this step is optional, because minikube has it's own docker. So we can use public docker images without docker installation.  But it case of development, if we have to create new images - docker is needed. 

1.3 Minikube installation. 

It can be downloaded from here. 

1.4. Kubectl installation. 

It can be downloaded from here. Also don't miss the steps regarding putting it into system PATH variable. For example for linux it's a " sudo mv ./kubectl /usr/local/bin/kubectl"

Now let's check if everything is ok with minikube and kubectl:
$ minikube status
minikube: 
cluster: 
kubectl: 


$ kubectl version
Client Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.3", GitCommit:"d2835416544f298c919e2ead3be3d0864b52323b", GitTreeState:"clean", BuildDate:"2018-02-07T12:22:21Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}
The connection to the server localhost:8080 was refused - did you specify the right host or port?

They should produce similar output to listed above.


2. Minikube: warming up

First of all, we have to set it up: it should download needed ISO image and put it into VirtualBox.
For this, theoretically we have just to run:
$ minikube start
But if for some reason it's not working, you can try to point it to vm-driver in explicit way:
$ minikube start --vm-driver="virtualbox"

For me, this process failed with error:
The vboxdrv kernel module is not loaded. Either there is no module\n         available for the current kernel (4.9.0-5-amd64) or it failed to\n         load. Please recompile the kernel module and install it by\n\n           sudo /sbin/vboxconfig\n\n 

When I executed:
# /sbin/vboxconfig

If also failed, with complains regarding linux headers. 

So I installed headers:
# apt-get install linux-headers-amd64 linux-headers-4.9.0-5-amd64

Executed again: 
# /sbin/vboxconfig

And again:
$ minikube start
demien:minikube$ minikube start
Starting local Kubernetes v1.9.0 cluster...
Starting VM...
Getting VM IP address...
Moving files into cluster...
Downloading localkube binary
 162.41 MB / 162.41 MB [============================================] 100.00% 0s
 65 B / 65 B [======================================================] 100.00% 0s
Setting up certs...
Connecting to cluster...
Setting up kubeconfig...
Starting cluster components...
Kubectl is now configured to use the cluster.

Loading cached images from config file.

- finally! :)

To make sure it works we can run:
$ minikube status
minikube: Running
cluster: Running
kubectl: Correctly Configured: pointing to minikube-vm at 192.168.99.100


3. Minikube: Simple operations

3.1. Dashboard. 

To open dashboard:
$ minikube dashboard
Opening kubernetes dashboard in default browser...

Your browser should show something like this: 


From dashboard you can configure cluster pods, deployments, replicas, servers.


3.2 Minikube: terminal

We can open terminal on minikube by running: 
$ minikube ssh
In example below I checked if my home folder is mounted to kubernetes:




4. Kubectl: simple operations

More "high-level" operations, like listed above should be executed by "minikube" command, but "low-lovel" operations belongs to "kubectl". 

4.1. Context swithing

First of all it's better to make sure kubectl is connected to minikube by running: 
$ kubectl config use-context minikube
Switched to context "minikube".

4.2. Deployment

To deploy docker image to kubernetes, we have 2 options: deploy from command line, or by creation and upload of deployment descriptor file.  

First option is faster, but for only simple situations: 
$ kubectl run hello-nginx --image=nginx --port=80 --replicas=2
deployment "hello-nginx" created

For second option,  we have to create a deployment descriptor like this: 

apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: hello-nginx
spec:
  selector:
    matchLabels:
      run: hello-nginx
  replicas: 2 # tells deployment to run 2 pods matching the template
  template: # create pods using pod definition in this template
    metadata:
      # unlike pod-nginx.yaml, the name is not included in the meta data as a unique name is
      # generated from the deployment name
      labels:
        run: hello-nginx
    spec:
      containers:
      - name: hello-nginx
        image: nginx
        ports:
        - containerPort: 80

Most important things are at the end:
- image - name of the docker image which should be pulled from docker public registry
- containerPort - port which will be exposed outside

After creation we have to deploy this descriptor by running(deployment-demo.yml - file name):
$ kubectl apply -f ./deployment-demo.yml 
deployment "nginx-deployment" created

Now we can check in dashboard: in should be one deployment :




and it should be 2 pods, because we defined "2 replicas" in descriptor:


 

Pod in kubernetes is like a "logical host": it's a running docker image. We defined 1 image with replica=2, so kubernetes is running this image twice. 

4.3 Service

Uploaded docker image is up and running now. But  we can't use is "outside" so far. For this we need the service, which will expose running container port outside. 
For service creation we have 2 the same options: from command line and from descriptor file. 

From command line:

$ kubectl expose deployment hello-nginx --type=NodePort
service "hello-nginx" exposed
 
From descriptor file(with name service-demo.yml): 

apiVersion: v1
kind: Service
metadata:
  name: hello-nginx
  labels:
    run: hello-nginx
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30080
    protocol: TCP
  selector:
    run: hello-nginx

File upload: 
$ kubectl apply -f ./service-demo.yml 
service "hello-nginx" created


Now we can check "service" menu: beside standard "kubernetes" service it should be our "hello-nginx": 


Also we can see the "outside" port here: 30080 - actually we defined it in descriptor. 
Now we can open this port using kubernetes ip and result should be: 




5. The end. 

No dubs, kubernetes is a great tool "to rule them all": to manage and configure running containers in a cluster. More tutorial can be found on official site: https://kubernetes.io/docs/tutorials/

Monday, June 5, 2017

ReactJS getting started

ReactJS official page: https://facebook.github.io/react/
From wiki:
React (sometimes styled React.js or ReactJS) is an open-source JavaScript library[2] for building user interfaces.
It is maintained by Facebook, Instagram and a community of individual developers and corporations.[3][4][5] According to JavaScript analytics service Libscore, React is currently being used on the websites of Netflix, Imgur, Buffer, Bleacher Report, Feedly, Airbnb, SeatGeek, HelloSign, Walmart, and others.[6]
React allows developers to create large web applications that use data which can change over time, without reloading the page. Its main goal is to be fast, simple and scalable. React processes only user interfaces in applications. This corresponds to View in the Model-View-Controller (MVC) template, and can be used in combination with other JavaScript libraries or frameworks in MVC, such as AngularJS.[7]

1. Intro 

So what is ReactJS? In shorts, it's a component-based library for building rich web UI. Main concept: UI elemnts(components) has to be built from more simple elements(components).

In this tutorial we will be building application for managing users and departments. For that we will create set of ReactJS components which will help us to create entities(Users, Departments) and show existing entities as tables. This entities (Departments and Users) are dependent, because User have to be assigned to department. So, on user creation we will have to select department from list of existing.








2. Create application 

To start working with ReactJS we have to do just a few things:

2.1. First of all we need nodeJS module create-react-app. To install it: 

$ npm install -g create-react-app

2.2. After it installation we can to create our ReactJS application by running: 

$ create-react-app my-reactjs-test-app

Output should be something like:
Creating a new React app in ......
Installing packages. This might take a couple minutes.
Installing react, react-dom, and react-scripts...
.........
Success! Created my-reactjs-test-app at ......my-reactjs-test-app
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd my-reactjs-test-app
  npm start

Happy hacking!


2.3. Now we can run NodeJS server by executing 2 last suggested steps: 

$  cd my-reactjs-test-app
$ npm start

Output should be: 
Compiled successfully!
You can now view my-reactjs-test-app in the browser.
  Local:            http://localhost:3000/
  On Your Network:  http://172.26.142.32:3000/
Note that the development build is not optimized.
To create a production build, use npm run build.


2.4. Open browser 

Now we can open suggested URL in browser: http://localhost:3000/
It should show something like:

3. JSX

To make this components composition process simple, ReactJS provide new syntax: JSX - it's a combination HTML tags with Javscript:
class SimpleComponent extends React.Component {
   render() {
      return (
         <div>
            <h1>{10+1}</h1>
         </div>
      );
   }
}
As you can see, HTML tags (<div> and other child tags)  are located inside Javascript function. And also this HTML block has embedded Javascript block {10+1}.

When component was created - we can use it in another components:
class ComplexComponent extends React.Component {
render() {
return (
<div>
<h1>Several simple components:</h1>
<SimpleComponent/>
<SimpleComponent/>
</div>
);
}
}

4. Components

There are 2 ways of components definition: functional-component style and class-component style.

Functional style is more simple and short. And it's good for "stateless"components: for simple components which are just UI elements without any logic related with component state:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

or as CONST:

const renderLabelForColumn = column => (<label className="formLabel">{column.label}:</label>);


Class-style is more complex, but it has much more additional features related with component state:

class ObjectList extends Component {
    constructor(props) {
        super(props);
        this.handleObjectCreation = this.handleObjectCreation.bind(this);
    }

    handleObjectCreation(obj) {
        this.props.handleObjectCreation(obj);

    }

    render() {
        return renderObjectListForm(this.props.objectType, this.props.title, this.props.columns, this.props.objectList, this.handleObjectCreation, this.props.selectors);
    }

}

5. Properties and states

5.1 Properties

User components can have custom properties just like regular HTML components:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

- name for "Hello" will be taken from properties:

Now we can use use this component with different values of property "name":

function App() {
  return (
    <div>
      <Welcome name="Joe" />
      <Welcome name="Huan" />
      <Welcome name="Sebastyan" />
    </div>
  );
}

Important things here:
  • properties are "read-only". For dynamic things like saving current state we have  to use states.
  • as a property we can also pass handler function from  level "above": 

const renderAddObjectForm = (objectType, columns, selectors, submitHandler) => (
    <div className="addObject">
        <form onSubmit={submitHandler}>
        </form>  
    </div>
)

5.2. States

In contrary to properties, states are needed for holding some data which can be changed. Main operations with states are:

  • we can set default value for state in constructor (in example below it's an empty array for userList property). 
  • we can change the state using setState method (function which is doing that can be pulled done by component hierarchy to lower level)
  • we can pass state object as a property to components on lower levels of hierarchy(in example below we are passing userList from state to component ObjectList as property with name  objectList)


function userCreation(user) {
    this.setState(
            prevState => {
                var list = prevState.userList;
                list.push(user);
                this.setState({userList: list});
            }
    );
}

class Body extends Component {

    constructor(props) {
        super(props);
        this.handleUserCreation = userCreation.bind(this);
        this.state = {userList: []};
    }

    render() {
        return (
                <div>
                    <ObjectList objectList={this.state.userList} handleObjectCreation={this.handleUserCreation} />
                </div>
                );
    }
}


6. Coding: components for new entity creation

Now let's start with coding. First of all let's create a directory "components" inside "src" directory. And a new JavaScript file: "AddObjectForm.js"

6.1. Lets create a helper function for extracting values from form.


function getFormValue(form, valueName) {
    var result;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name === valueName)
            result = form.elements[i].value;
    }
    return result;
}

6.2. Component for rendering column labels.


const renderLabelForColumn = column => (<label className="formLabel">{column.label}:</label>);

6.3. Component for rendering editor field.

Here we are passing selectors object, which may contain array for displaying combobox (HTML SELECT component). If array with values is not present - we are displaying simple text field(HTML INPUT).

const renderEditorForColumn = (column, selectors) => {
    if (selectors && selectors[column.name]) {
        var list = selectors[column.name];
        let options = list.map((el) =>
            <option key={el} value={el}>{el}</option>
        );
        return (<select name={column.name}>{options}</select>);
    } else {
        return (<input name={column.name} type="text"/>);
    }
};


6.4. Component for rendering list of pairs: Field Label -> Editor

List of columns is passed by columns parameter. We are iterating this list and creating for every element of the list corresponding pair of elements: Fileld Label -> Editor.


const renderAddColumnsList = (objectType, columns, selectors) => {
    let rows = columns.map((column) =>
        <div key={objectType + "-" + column.name}> 
            {renderLabelForColumn(column)}
            {renderEditorForColumn(column, selectors)}
        </div>
    );
    return (<div>{rows}</div>);
};


6.5. Form component - container for field list

Here we creating the form with submit handler which was passed as property

const renderAddObjectForm = (objectType, columns, selectors, submitHandler) => (
    <div className="addObject">
        <form onSubmit={submitHandler}>
            <fieldset>
                <legend>Create new</legend>
                {renderAddColumnsList(objectType, columns, selectors)}
                <br/>
                <label>Press the button:</label>
                <input type="submit" values="Submit"/>
            </fieldset>
        </form>  
    </div>
)



6.6. Main class component for AddObjectForm

We are using class component, for being able to use constructor. In conctructor we can set binding for hanleSubmit function, to make it work properly in callbacks.


class AddObjectForm extends Component {

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(event) {
        event.preventDefault();
        var form = event.target;
        var formObject = {};
        this.props.columns.forEach((column) => formObject[column.name] = getFormValue(form, column.name));
        this.props.onSubmit(formObject);
    }

    render() {
        return renderAddObjectForm(this.props.objectType, this.props.columns, this.props.selectors, this.handleSubmit);
    }
}


7. Coding: components for showing the list of existing objects

Let's create another file in src/components: ObjectList.js

7.1. Component for rendering one row of data in the table


const renderTableRow = (columns, data) => {
    let rowContent = columns.map((column) =>
        <td key={column.name + "-" + data.id}>{data[column.name]}</td>
    );
    return (<tr key={data.id}>{rowContent}</tr>);
};


7.2. Component for rendering all rows


const renderTableRows = (columns, objectList) => (
    objectList.map((data) => renderTableRow(columns, data))
);


7.3. Component for rendering table header


const renderTableHeader = (columns) => (
    columns.map((column) =>
        <th key={column.name}>{column.label}</th>
    )
);


7.4. Component for rendering table itself

If we have no data for table (in objectList) we are just return null.

const renderTable = (columns, objectList) => {
    if (!objectList || objectList.length === 0)
        return null;
    return(
            <div>
                <h3>List of existing:</h3>
                <table className="objectListTable">
                    <tbody>
                        <tr>
                            {renderTableHeader(columns)}
                        </tr>               
                        {renderTableRows(columns, objectList)}
                    </tbody>        
                </table>
            </div>
    );
};



7.5 Component for rendering AddObjectForm together with table of existing objects

AddObjectForm is rendered as ussual HTML component.

const renderObjectListForm = (objectType, title, columns, objectList, creationHadler, selectors) => (
    <div className="objectList">
        <h2>{title}</h2>
        <AddObjectForm onSubmit={creationHadler} columns={columns} selectors={selectors} objectType={objectType}/>
        <br/>
        {renderTable(columns, objectList)}
    </div>
);


7.6. Class component with proper hadlerBinding


class ObjectList extends Component {
    constructor(props) {
        super(props);
        this.handleObjectCreation = this.handleObjectCreation.bind(this);
    }

    handleObjectCreation(obj) {
        this.props.handleObjectCreation(obj);

    }

    render() {
        return renderObjectListForm(this.props.objectType, this.props.title, this.props.columns, this.props.objectList, this.handleObjectCreation, this.props.selectors);
    }

}

8. Main App component

Now all our components are ready and we can combine them together.
We have to create function which will be handlers for department and user creation. This functions will be updating state object. We will pull then "down" to low level components. For department creation, we need to update additional selector object, which will be used for user creation.  Also we have not to forget to set up in constructor the  initial state with empty objects.


function departmentCreation(department) {
    this.setState(
            prevState => {
                var list = prevState.depList;
                var depSelectors = prevState.selectors;
                var selector = depSelectors.department ? depSelectors.department : [];
                list.push(department);
                selector.push(department.name);
                depSelectors.department = selector;
                this.setState({depList: list});
                this.setState({selectors: depSelectors});

            }
    );
}

function userCreation(user) {
    this.setState(
            prevState => {
                var list = prevState.userList;
                list.push(user);
                this.setState({userList: list});
            }
    );
}

class Body extends Component {

    constructor(props) {
        super(props);
        this.handleDepartmentCreation = departmentCreation.bind(this);
        this.handleUserCreation = userCreation.bind(this);
        this.state = {depList: [], userList: [], selectors: {}};
    }

    render() {
        var depColumns = [{name: "id", label: "Id"}, {name: "name", label: "Name"}];
        var userColumns = [{name: "id", label: "Id"}, {name: "name", label: "Name"}, {name: "emal", label: "Email"}, {name: "department", label: "Department"}];
        return (
                <div>
                    <ObjectList objectList={this.state.depList} handleObjectCreation={this.handleDepartmentCreation} columns={depColumns} objectType="departments" title="Departments" />
                    <ObjectList objectList={this.state.userList} selectors={this.state.selectors} handleObjectCreation={this.handleUserCreation} columns={userColumns} objectType="users" title="Users" />
                </div>
                );
    }
}

class App extends Component {
    render() {
        return (
                <div className="App">
                    <div className="App-header">
                        <img src={logo} className="App-logo" alt="logo" />
                        <h2>Welcome to React</h2>
                    </div>
                    <p className="App-intro">
                        To get started, edit <code>src/App.js</code> and save to reload.
                    </p>
                    <Body/>
                </div>
                );
    }
}


9. The end

ReactJS can make application creation very simple, because it's based on creation of simple blocks which can be developer and tested separately. Full source code can be downloaded from here.