Monday, July 24, 2017

Linux Commands

Find processes by user:
ps -efl | grep <username>

Find process statistics by user:
top -U <username>

Find file location:
find / -name <filename> 2>/dev/null

find file with name:
locate -i -q <filename>

Tail a process output to console
find the process id
cd /proc/id
cd fd
tail -f 1



Wednesday, July 19, 2017

OpenShift Commands


Samples of OpenShift commands:

# List the environment variables defined on all pods
oc env pods --all --list

oc types
oc project <project_name>
oc status

oc get svc
oc get po

oc describe <object_type> <object_id>

oc logs -f <pod_name> <container_name>
oc logs -f pod/pod_name -c container_name
oc logs -f --tail=100 pod/pod_name -c container_name
oc logs -f build/build_name



oc edit bc/bc_name
oc edit dc/dc_name
oc edit pod/pod_name



Object TypeAbbreviated Version
build
buildConfig
bc
deploymentConfig
dc
imageStream
is
imageStreamTag
istag
imageStreamImage
isimage
event
ev
node
pod
po
replicationController
rc
service
svc
persistentVolume
pv
persistentVolumeClaim
pvc



OpenShift Concepts:

Components are contained by a project, they are flexibly linked together,  as many components as you desireany combination of components you can imagine, and optionally labeled to provide any groupings or structure. 

images in OpenShift v3 are mapped 1:1 with containers. Containers use pods as their collocation mechanism.

Source code:
With OpenShift v3, you can choose which images are built from source and that source can be located outside of OpenShift itself.

Build:
In v3, build results are first committed as an immutable image and published to an internal registry. That image is then available to launch on any of the nodes in the cluster or rollback to at a future date.

Routing:
With v3, you can use templates to setup 0-N routes for any image. These routes let you modify the scheme, host, and paths exposed as desired, and there is no distinction between system routes and user aliases.

OpenShift Architecture





OpenShift Container Platform Architecture Overview

OpenShift Container Platform 3.3 uses Kubernetes 1.3 and Docker 1.10.


Kubernetes

A Kubernetes cluster consists of one or more masters and a set of nodes. You can optionally configure your masters for high availability (HA) to ensure that the cluster has no single point of failure.



Master Components
ComponentDescription
API Server
The Kubernetes API server validates and configures the data for pods, services, and replication controllers. It also assigns pods to nodes and synchronizes pod information with service configuration. Can be run as a standalone process.
etcd
etcd stores the persistent master state while other components watch etcd for changes to bring themselves into the desired state. etcd can be optionally configured for high availability, typically deployed with 2n+1 peer services.
Controller Manager Server
The controller manager server watches etcd for changes to replication controller objects and then uses the API to enforce the desired state. Can be run as a standalone process. Several such processes create a cluster with one active leader at a time.
HAProxy
Optional, used when configuring highly-available masters with the native method to balance load between API master endpoints.
The advanced installation method can configure HAProxy for you with the native method. Alternatively, you can use the native method but pre-configure your own load balancer of choice.

When using the native HA method with HAProxy, master components have the following availability:


Availability Matrix with HAProxy
RoleStyleNotes
etcd
Active-active
Fully redundant deployment with load balancing
API Server
Active-active
Managed by HAProxy
Controller Manager Server
Active-passive
One instance is elected as a cluster leader at a time
HAProxy
Active-passive
Balances load between API master endpoints

Nodes

A node provides the runtime environments for containers. Each node in a Kubernetes cluster has the required services to be managed by the master. Nodes also have the required services to run pods, including the Docker service, a kubelet, and a service proxy.

Kubelet

Each node has a kubelet that updates the node as specified by a container manifest, which is a YAML file that describes a pod. The kubelet uses a set of manifests to ensure that its containers are started and that they continue to run. 
A container manifest can be provided to a kubelet by:
  • A file path on the command line that is checked every 20 seconds.
  • An HTTP endpoint passed on the command line that is checked every 20 seconds.
  • The kubelet watching an etcd server, such as /registry/hosts/$(hostname -f), and acting on any changes.
  • The kubelet listening for HTTP and responding to a simple API to submit a new manifest.

Service Proxy

Each node also runs a simple network proxy that reflects the services defined in the API on that node. This allows the node to do simple TCP and UDP stream forwarding across a set of back ends.

Wednesday, July 12, 2017

Management, Communication Topics



The 7 Deadly Sins of Manager-Employee Communication

Sin#1 Foucsing on Weknesses

"Although we label weaknesses 'areas of opportunity,' brain science reveals that we do not learn and grow the most in our areas of weakness. In fact the opposite is true: we grow the most new synapses in those areas of our brain where we have the most pre-existing synapses. Our strengths, therefore, are our true areas of opportunity for growth."
- Marcus Buckingham, Harvard Business Review

Sin#2 - Disregarding Professional Development
Sin#3 - Being Unapproachable
Sin #5 - Being Too Involved
Sin #6 - Exhibiting Pessimism
Sin #4 - Being Uninvolved
Sin #7 - Using Passive-Aggressive Communication

 Difficult Interactions

Why do difficult interactions occur?

  • Positions and interests
  • Perceptions, motivations, and work styles
  • Life experiences and cultural backgrounds
  • Positions are what the parties say they want.
  • Interests are why they want it. These may be unstated and even unacknowledged.
When someone disagrees with something we deeply believe or seems obvious to us, it can feel like a personal affront. We may feel angry or distrustful, and be tempted to dismiss everything that person says.

But the blindness is partially ours.

Researchers have identified two phenomena that cause us to cling to our own perspectives:
  • False consensus effect. When people believe that most others share their same views. (“This graphic designer is terrific. Everyone knows we’d be lucky to have her create our new logo.”)
  • Naive realism. When people believe they see the world as it actually is and those who don’t see it that way are biased, uninformed, or deluded. (“Kevin prefers the old app only because he hasn’t seen the new one yet. Once he has a chance to test it, he’ll be on board with it.”)
The next time you’re involved in a dispute over facts, think about these tendencies. You may be able to turn a stuck conversation into a chance for shared learning.

Different perceptions, motivations, and work styles

Differences in perceptions, motivations, and work styles can also cause tension and conflict.
  • Perceptions about what’s important

  • Elena views management’s directives as the most important priority, while her team member Javier believes taking care of the customer matters most.
  • Motivations and intentions

    Anne is motivated by quality, while her colleague Malik is motivated by personal achievement.
  • Work style

    Ethan likes to put all the issues on the table at once, but his supervisor Mark prefers to grapple with problems one at a time.
  • Communication style
    Fatima prefers to be informed about problems through written communication; her employee Phyllis finds it easier to drop by Fatima's office for an informal conversation.
  • Cultural difference
    Description
    Possible area of conflict
  • Task orientation versus relationship orientation
    ·    In countries like the US, conversations are used primarily to exchange information.
    ·    In countries like Mexico, conversations are a way to cultivate goodwill and build relationships.
    ·    Focusing exclusively on the task may cause the other person to feel devalued.
    ·    Focusing on the relationship may cause the other person to perceive a lack of interest in the task.
  • Direct versus indirect communication
    ·    In countries like Germany, people prefer to communicate precisely and directly.
    ·    In countries like Japan, people approach problems through general statements and subtle hints.
    ·    A person who speaks directly may come across as insensitive or impolite.
    ·    A person who speaks indirectly may seem inarticulate or untrustworthy.
  • Low versus high context
    ·    In countries like Canada, people convey meaning through words more than body language (low context).
    ·    In countries like South Korea, people use cues such as setting, relationship between the parties, and emotions to discern meaning (high context).
    ·    A low-context person may think they are communicating only through what they actually say, but the listener may infer unintended meaning based on other cues.
    ·    A high-context person may convey a message in various ways, but the listener may only pay attention to the words.
  • Informal versus formal
    ·    In countries like Australia, people tend to approach even potentially sensitive conversations with a casual attitude.
    ·    In countries like Poland, people expect a degree of decorum that matches the seriousness of the matter at hand.
    ·    A person from an informal culture might appear as though she doesn’t care about the issue.
    ·    A person from a formal culture might seem to indicate that the issue is more serious than it is.
  • Barrier
    Recommended response
  • Fear of interpersonal conflict
    Acknowledge that although conflict can be uncomfortable, it’s a fact of life. Focus on the positive outcomes of addressing a dispute.
  • Failure to recognize that you have a problem with another person in the workplace
    Notice the quality of your workplace relationships. Ask which relationships seem tense, frustrating, or unproductive. Acknowledge that these relationships are hampered by difficult interactions.
  • Belief that a difficult interaction is the fault of others
    Acknowledge your role in the difficulty. Identify what you can do to improve the situation.
  • Conviction that other people won’t change, even if you try to improve the situation
    Remind yourself that you’re not trying to change another person. Rather, you want to alter the way the two of you interact. You can do that by changing your own behavior.
  • Belief that the problem will resolve itself
    Remind yourself that most problems don’t resolve themselves. 
Some managers are uncomfortable dealing with conflict. But when supervisors fail to tackle problems on their teams, their employees’ performance suffers.

To help a conflict-averse boss see the benefit of addressing conflict:
  • Don’t place blame. When discussing the issue with your boss, focus your discussion on the details of the problem, not on the individuals involved.
  • Gather supporting evidence. Provide all the information your boss needs to address the issue.
  • Communicate the costs of not addressing the situation. Identify your boss’s priorities and show how the conflict is jeopardizing those goals.
  • Put suggestions in writing. Email or message your ideas for solving the problem to your supervisor, and copy other people only as appropriate.
  • Make your boss feel supported. Show your boss that they have your backing in dealing with the matter and that you care about your shared interests.

  • Source of conflict
    What it is
    Example
  • Relationship
    Disagreement based on personalities and work styles
    Martina is annoyed with her officemate John because he often talks loudly on the phone. She prefers to work in silence.
  • Task
    Disagreement over what has to be done
    Patty believes the team should focus on researching customer needs. Rafa advocates for looking at industry trends.
  • Process
    Disagreement over how to do something
    Leonard wants the team to follow the project plan precisely, while Griselda wants to adapt the plan according to new information.
  • Status
    Disagreement over who’s in charge
    Lindsay, the marketing director, and Nolan, the creative services director, each believe they should have the final approval of the logo for a new product line.
If you’re not sure what’s actually fueling your conflict, consider:
  • ​When the disagreement started
  • What you and the other person have said and done
  • Who else has been involved
  • How you and the other person view what’s at stake

Uncover hidden emotions

Some people tend to suppress their feelings during strained encounters. But what you say generally reflects how you feel. Learn to look for the emotions behind your words; if you don’t, you may end up worsening the situation. For example:
  • If you said…
    You may be feeling…
    You could end up…
  • “The solution is for you to get these tasks done within budget.”
    Fear that you won’t get funding for a subsequent project
    Rushing to solve the problem
  • “You’re unbelievably apathetic.”
    Disappointment that the other person seems uncommitted to the work
    Mischaracterizing the other person
  • “You should have supported my proposal at the meeting.”
    Betrayed by a colleague who you thought backed your ideas
    Making judgments about how a peer is supposed to behave
  • “Why did you ignore my memo about the new strategy?”
    Self-doubt about your leadership abilities
    Attributing an intent to the other person

Reframe negative thoughts

  • Seek information that puts the person’s actions in context. For example, you may discover that your employee did not show up at a morning staff meeting for a good reason—their elderly mother accidentally locked herself out of her house.
  • Think about intentions. Did copying your manager on an email mean your colleague was questioning your judgment, or was he following conventions of past communications?
  • Examine the role you may have played. For example, an employee may be behind on a project because you added new tasks at the last minute.
  • Question your assumptions. Does your colleague’s tendency to do things differently than you would mean they’re “taking shortcuts”? Or do they care as much as you about quality, but are simply using different methods?


take a breathe
don't agree or disagree

  • If the other person...
    Try to...
  • Is aggressive and disrespectful
    • Command respect by remaining calm.
    • Interrupt verbal attacks by repeating the person's name.
    • Communicate your bottom line: "When you're ready to speak to me with respect, I will take all the time you want to discuss this.”
  • Doesn't listen to your side
    • Go into the conversation prepared to support your own perceptions and ideas.
    • Redirect the person to your idea or information with phrases such as, “I was just wondering...” “Bear with me a minute,” or “What do you suppose… ?”
    • Acknowledge that the person possesses valuable knowledge, too.
  • Has an explosive outburst
    • Take a break and then continue the conversation.
    • Get the person’s attention by calling their name loudly enough to be heard.
    • Express genuine concern for the person: "Joe, nobody should have to feel this way! I want to help."
  • Is uncommunicative
    • Schedule plenty of time for the person to respond to your ideas and questions.
    • Ask open-ended questions: "What are you thinking?" "How do you want to proceed?" "Where should we go from here?"
    • Gaze expectantly at the person for a longer-than-usual period of time after making a comment or asking a question.
  • Assumes that the situation can't get better
    • Give the person time to consider your plan and get back to you.
    • Bring up and address the negative aspects of your idea before they do.


Thursday, July 6, 2017

HTTP access control (CORS)


In the case that there is a need to post to a different domain by using JavaScript, you may see CORS issue with error such as:


XMLHttpRequest cannot load https://xyz. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.



XMLHttpRequest cannot load https://xyz. request header field content-type is not allowed by access-control-allow-headers in preflight response.


When you search this issue and many will suggest adding a header:
"Access-Control-Allow-Origin", "*"

However this is not enough, the following is a code from Swagger example that should be able to handle normal situations:


package io.swagger.sample.util;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;

public class ApiOriginFilter implements javax.servlet.Filter {
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    HttpServletResponse res = (HttpServletResponse) response;
    res.addHeader("Access-Control-Allow-Origin", "*");
    res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    res.addHeader("Access-Control-Allow-Headers", "Content-Type");
    chain.doFilter(request, response);
  }

  @Override
  public void destroy() {
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }
}




Here is another suggestion:


response.addHeader("Access-Control-Allow-Origin", "*");response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT");response.addHeader("Access-Control-Allow-Credentials", "true");response.addHeader("Access-Control-Allow-Headers","Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, X-Atmosphere-Transport, *");response.addHeader("Access-Control-Request-Headers","Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, X-Atmosphere-Transport, *");


A web page to test RESTFUL JSON post:

<!DOCTYPE html>
<html lang="en">
<head>
<title>RESTFUL API TEST</title>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/json2/20160511/json2.min.js"></script>
</head>
<body>
<div class="container">
  <h1>RESTFUL SERVICE ENDPOINT</h1>
  <form id="form" enctype='application/json' method="post"
    action="https://hostname:port/myapp/v3/api/endpoint">
    <fieldset>
        <legend>Enter sessionid and username</legend>
        <label>session id</label>
        <input name="sessionid" id="sessionid" type="text">
        <label>username</label>
        <input name="username" id="username" type="text">
        <button class="btn" id="submit" type="submit">submit</button>
    </fieldset>
  </form>
</div>
<div class="container">
  <fieldset>
    <legend>Response</legend>
    <label>status</label><input name="status" id="status" type="text">
    <p>
    <textarea id="responseJson" name="responseJson" rows="8" cols="80"></textarea>
  </fieldset>
</div>
       <script type="text/javascript">
       $("form").submit(function(e) {
            // stop the regular form submission
            e.preventDefault();

             // collect the form data while iterating over the inputs
             var data = {};
             for (var i = 0, ii = form.length; i < ii; ++i) {
                 var input = form[i];
                 if (input.name) {
                     data[input.name] = input.value;
                 }
             }

             // construct an HTTP request
             var xhr = new XMLHttpRequest();
             xhr.open(form.method, form.action, true);
             xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
             xhr.onreadystatechange = function() {
                 $("input[name='status']").val(xhr.status);
                 if (xhr.readyState === 4
                         && (xhr.status === 201
                                 || xhr.status === 400 || xhr.status === 500)) {
                     console.log(xhr.responseText);
                     $("textarea[name='responseJson']").val(
                             xhr.responseText);
                 }
             };

             // send the collected data as JSON
             xhr.send(JSON.stringify(data));
    });
    </script>
</body>
</html>



Sometimes, more constraints may be required to limit the domains that could access the resource:


response.addHeader("Access-Control-Allow-Origin", "myhost.mydomain");


Multiple values are not allowed here. 

What you may do here is, in the servlet filter, checks the original against a list of the domains that are allowed to access the resources, then put the original domain in the  "Access-Control-Allow-Origin" header then return it to the client.