Building a document understanding pipeline with Google Cloud

Document understanding is the practice of using AI and machine learning to extract data and insights from text and paper sources such as emails, PDFs, scanned documents, and more.In the past, capturing this unstructured or “dark data” has been an expensive, time-consuming, and error-prone process requiring manual data entry. Today, AI and machine learning have made great advances towards automating this process, enabling businesses to derive insights from and take advantage of this data that had been previously untapped. In a nutshell, document understanding allows you to:Organize documents Extract knowledge from documents Increase processing speedAt Google Cloud we provide a solution, Document AI, which enterprises can leverage in collaboration with partners to implement document understanding. However, many developers have both the desire and the technical expertise to build their own document understanding pipelines on Google Cloud Platform (GCP)—without working with a partner—using the individual Document AI products.If that sounds like you, this post will take you step-by-step through a complete document understanding pipeline. The Overview section explains how the pipeline works, and the step-by-step directions below walk you through running the code.OverviewIn order to automate an entire document understanding process, multiple machine learning models need to be trained and then daisy-chained together alongside processing steps into an end-to-end pipeline. This can be a daunting process, so we have provided sample code for a complete document understanding system mirroring a data entry workflow capturing structured data from documents.Our example end-to-end document understanding pipeline consists of two components:A training pipeline which formats the training data and uses AutoML to buildImage Classification,Entity Extraction,Text Classification, andObject Detection models.A prediction pipeline which takes PDF documents from a specified Cloud Storage Bucket, uses the AutoML models to extract the relevant data from the documents, and stores the extracted data in BigQuery for further analysis.Training DataThe training data for this example pipeline is from a public dataset containing PDFs of U.S. and European patent title pages with a corresponding BigQuery table of manually entered data from the title pages. The dataset is hosted by the Google Public Datasets Project.Part 1: The Training Pipeline The training pipeline consists of the following steps:Training data is pulled from the BigQuery public dataset. The training BigQuery table includes links to PDF files in Google Cloud Storage of patents from the United States and European Union.The PDF files are converted to PNG files and uploaded to a new Cloud Storage bucket in your own project. The PNG files will be used to train the AutoML Vision models.The PNG files are run through the Cloud Vision API to create TXT files containing the raw text from the converted PDFs. These TXT files are used to train the AutoML Natural Language models.The links to the PNG or TXT files are combined with the labels and features from the BigQuery table into a CSV file in the training data format required by AutoML. This CSV is then uploaded to a Cloud Storage bucket. Note: This format is different for each type of AutoML model.This CSV is used to create an AutoML dataset and model. Both are named in the format patent_demo_data_%m%d%Y_%H%M%S. Note that some AutoML models can sometimes take hours to train.Part 2: The Prediction PipelineThis pipeline uses the AutoML models previously trained by the pipeline above. For predictions, the following steps occur:The patent PDFs are collected from the prescribed bucket and converted to PNG and TXT files with the Cloud Vision API (just as in the training pipeline).The AutoML Image Classification model is called on the PNG files to classify each patent as either a US or EU patent. The results are uploaded to a BigQuery table.The AutoML Object Detection model is called on the PNG files to determine the location of any figures on the patent document. The resulting relative x, y coordinates of the bounding box are then uploaded to a BigQuery table.The AutoML Text Classification model is called on the TXT files to classify the topic of the patent content as medical technology, computer vision, cryptocurrency or other. The results are then uploaded to a BigQuery table.The AutoML Entity Extraction model is called to extract predetermined entities from the patent. The extracted entities are applicant, application number, international classification, filing date, inventor, number, publication date and title. These entities are then uploaded to a BigQuery table.Finally, the BigQuery tables above are joined to produce a final results table with all the properties above.Step-by-Step DirectionsFor the developers out there, here’s how you can build the document understanding pipeline of your dreams. You can find all the code in our GitHub Repository.Before you begin:You’ll need a Google Cloud project to run this demo. We recommend creating a new project.We recommend running these instructions in Google Cloud Shell(Quickstart). Other environments will work but you may have to debug issues specific to your environment. A Compute Engine VM would also be a suitable environment.1. Git clone the repo and navigate to the patents example.2. Install the necessary system dependencies. Note that in Cloud Shell system-wide changes do not persist between sessions, so if you step away while working through these step-by-step instructions you will need to rerun these commands after restarting Cloud Shell.3. Create a virtual environment and activate it.When your virtual environment is active you’ll see patents-demo-env in your command prompt. Note: If your Cloud Shell session ends, you’ll need to reactivate the virtual environment by running the second command again.For the remaining steps, make sure you’re in the correct directory in the professional-services repo: /examples/cloudml-document-ai-patents/.4. Install the necessary libraries into the virtual environment.5. Activate the necessary APIs.Note: We use the gcloud SDK to interact with various GCP services. If you are not working in Cloud Shell you’ll have to set your GCP project and authenticate by running gcloud init.6. Edit the config.yaml file. Look for the configuration parameter project_id (under pipeline_project) and set the value to the project id where you want to build and run the pipeline. Make sure to enclose the value in single quotes, e.g. project_id: ‘my-cool-project’.Note: if you’re not used to working in a shell, run nano to open a simple text editor.7. Also in config.yaml, look for the configuration parameter creator_user_id (under service_acct) and set the value to the email account you use to log in to Google Cloud. Make sure to enclose the value in single quotes, e.g. creator_user_id: ‘cloud.user@fake.email.address.com’.8. Create and download a service account key with the necessary permissions to be used by the training and prediction pipelines.9. Run the training pipeline. This may take 3–4 hours, though some models will finish more quickly.Note: If Cloud Shell Closes while the script is still downloading, converting, or uploading the PDFs, you will need to reactivate the virtual environment, navigate to the directory, and rerun the pipeline script. The image processing should take about 15-20 minutes, so make sure Cloud Shell doesn’t close during that time.10. After training the models (wait about 4 hours), your Cloud Shell session has probably disconnected. Reconnect to Cloud Shell and run the following commands to reinstall dependencies, reactivate the environment, and navigate to the document understanding example code.11. Next, you need to use the AutoML UIs to deploy the object detection and entity extraction models, and to find the ids of your models (which you will enter into config.yaml). In the UIs, you can also view relevant evaluation metrics about the model and see explicit examples where your model got it right (and wrong).Note: Some AutoML products are currently in beta; the look and function of the UIs may change in the future.Go to the AutoML Image Classification models UI, and make sure you are in same project you ran the training pipeline in (top right dropdown). Note the ID of your trained image classification model. Also note the green check mark to the right of the model—if this is not a check mark, or if there is nothing listed, it means model training is still in progress and you need to wait.In Cloud Shell, edit config.yaml. Look for the line model_imgclassifier: and on the line below you’ll see model_id:. Put the image classification model id after model_id: in single quotes, so the line looks something like model_id: ‘ABC1234567890’Go to the AutoML Natural Language models UI, and similarly, make sure you are in the correct project, make sure your model is trained (green check mark) and note the model id of the trained text classification model.In Cloud Shell, edit config.yaml. Look for the line model_textclassifier: and on the line below you’ll see model_id:. Put the text classification model id after model_id: in single quotes, so the line looks something like ” model_id: ‘ABC1234567890′”Go to the AutoML Object Detection models UI, again making sure your project is correct and your model is trained. In this UI, the model id is below the model name. You also need to deploy the model, by opening the menu under the three dots at the far right of the model entry and selecting “Deploy model”. A UI popup will ask how many nodes to deploy to, 1 Node is fine for this demo. You need to wait for the model to deploy before running prediction (about 10-15 minutes), the deployment status is in the UI under “Deployed” and it will be “Yes” when the model is deployed.In Cloud Shell, edit config.yaml. Look for the line model_objdetect: and on the line below you’ll see model_id:. Put the object detection model id after model_id: in single quotes, so the line looks something like model_id: ‘ABC1234567890’Go to the AutoML Entity Extraction models UI, and make sure the project and region are correct. Verify the model training is complete by checking to make sure the Precision and Recall metrics are listed. Note the id as well.To deploy the model, click the model name and a new UI view will open. Click “DEPLOY MODEL” near the top right and confirm. You need to wait for the model to deploy before running prediction (about 10-15 minutes), the UI will update when deployment is complete.In Cloud Shell, edit config.yaml. Look for the line model_ner: and on the line below you’ll see model_id:. Put the entity extraction model id after model_id: in single quotes, so the line looks something like model_id: ‘ABC1234567890′.Before going further, make sure the model deployments are complete.12. To run the prediction pipeline, you’ll need some PDFs of patent first pages in a folder in Cloud Storage. You can provide your own PDFs in your own Cloud Storage location, or for demonstration purposes, you can run the following commands, which create a bucket with the same name as your project id (if it doesn’t already exist) and copy a small set of five patent first pages into a folder in the bucket called patent_sample.13. In the config.yaml file, fill in the configuration parameter labeled demo_sample_data (under pipeline_project) with the Cloud Storage location of the patents you want to process (in single quotes). If you’re following the example above, the parameter value is ‘gs://<YOUR-PROJECT-ID>/patent_sample’, substituting your project id.Also, fill in the parameter labeled demo_dataset_id, just under demo_sample_data. With the BigQuery dataset (in single quotes) in your project where the predicted entities will be collected. For example, you can use ‘patent_demo’. Note that this dataset must not exist already; the code will attempt to create the dataset and will stop running if the dataset already exists.Now, you are ready to make predictions!14. Run the prediction pipeline. This will process all the patent PDF first pages in the Cloud Storage folder specified in the demo_sample_data parameter, and upload predictions to (and create) BigQuery tables in the dataset specified by the  demo_dataset_id parameter.python3 run_predict.py15. Finally, go check out the dataset in the BigQuery UI and examine all the tables that have been created. There is a table called “final_view” which collects all the results in a single table. You should see something like this:Note, for this, or any of the other intermediate tables that were created during the prediction pipeline, you may need to query the table to see the results since it is so new. For example:If you are new to BigQuery, you can open a querying interface in the UI prepopulated with the table name by clicking the “QUERY TABLE” button visible when you select a table to view.ConclusionCongratulations! You now have a fully functional document understanding pipeline that can be modified for use with any PDF documents. To modify this example to work with your own documents, the data collection and training stages will need to be modified to pull documents from a local machine or another Cloud Storage bucket rather than a public BigQuery dataset. The training data will also need to be created manually for the specific type of documents you will be using. Now, if only we could create a robot that could scan paper documents to PDFs…For more information about the general process of document understanding, see this blog post from Nitin Aggarwal at Google Cloud. And for more information about the business use cases of Document Understanding on Google Cloud, check out this session from Google Cloud Next ’19.
Quelle: Google Cloud Platform

Cloud Build named a Leader for Continuous Integration in the Forrester Wave

Today, we are honored to share that Cloud Build, Google Cloud’s continuous integration (CI) and continuous delivery (CD) platform, was named a Leader in The Forrester Wave™: Cloud-Native Continuous Integration Tools, Q3 2019. The report identifies the 10 CI providers that matter most for continuous integration (CI) and how they stack up on 27 criterias. Cloud Build received the highest score in both the current offering and strategy categories. “Google Cloud Build comes out swinging, matching up well with other cloud giants. Google Cloud Build is relatively new when compared to the other public cloud CI offerings; this vendor had a lot to prove, and it did…. Customer references are happy to trade the cost of paying for the operation and management of build servers for moving their operations to Google’s pay-per-compute system. One reference explained that it’s in the middle of a cloud shift and is currently executing up to 650 builds per day. With that proved out, this customer plans to move an additional 250 repositories to the cloud” – Forrester Wave™ reportTop score in the Current Offering category: Among all 10 CI providers evaluated in the Wave, Cloud Build got the highest score in the Current Offering category. The Current Offering score is based on Cloud Build’s strength in the developer experience, build speed and scale, enterprise security and compliance, and enterprise support, amongst other criteria.Top score in the Strategy category: Along with top score in the current offering category, Cloud Build also received the highest score in the Strategy category. In particular, Cloud Build’s scores in the partner ecosystem, commercial model, enterprise strategy and vision, and product roadmap criteria contributed to the score. CI plays an increasingly important role in DevOps, allowing enterprises to drive quality from the start of their development cycle. The report mentions “that cloud-native CI is the secret development sauce that enterprises need to be fast, responsive, and ready to take on incumbents and would-be digital disruptors.”At Google, we’ve seen first-hand how cloud-based serverless CI tool can help drive quality and security at scale, and the lessons we’ve learned in that process manifest directly in Cloud Build. Today, organizations of all sizes use Cloud Build to drive productivity improvements via automated, repeatable CI processes. Some customers include Zendesk, Shopify, Snap, Lyft, and Vendasta, who chose Cloud Build for its:Fully serverless platform: Cloud Build scales up and scale down in response to load with no need to pre-provision servers or pay in advance for additional capacity. Flexibility: With custom build steps and pre-created extensions to third party apps, enterprises can easily tie their legacy or home-grown tools as a part of their build process.Security and compliance features: Developers have an ability to perform deep security scans within the CI/CD pipeline and ensure only trusted container images are deployed to production. We’re thrilled by Forrester’s recognition for Cloud Build. You can download a copy of the report here.
Quelle: Google Cloud Platform

Deployed AI: How Lumiata is using AI to make healthcare smarter

Editor’s note: Today we hear from Miguel Alvarado, CTO at Lumiata, which is using Google Cloud AI to provide intelligent health analytics for improved risk awareness and cost management in healthcare. Lumiata was founded on a vision of smarter, more cost-effective healthcare, and AI plays a central role in making it a reality. We provide sophisticated machine learning applications that elevate a healthcare organization’s ability to manage spend forecasting, stop loss, disease prediction and more, out of the box. We recently unveiled the Lumiata AI Platform for healthcare organizations who are seeking to apply machine learning to improve affordability and quality of care. Our platform helps healthcare organizations in two ways. Firstly, they can streamline their data to get a comprehensive longitudinal person record (LPR) for personalized analytics that uses different signals including claims, eligibility, labs, pharmacy, EHR/EMR, unstructured data, and more. Secondly, they get tools and access to pre-trained models through Lumiata AI Studio that healthcare data scientists can use to build and deploy machine learning models for use-cases like predicting medical costs and events.It takes powerful infrastructure to deliver ease of use and simplicity to our customers. After careful evaluation, we chose Google Cloud to help us deliver meaningful AI capabilities to transform healthcare organizations. Google Cloud’s security infrastructure, wide selection of intuitive AI tools, and technologies like Anthos that make multi-cloud environments utterly straightforward were some of the key factors behind our decision.As we moved to Google Cloud and built our platform, there are a few lessons we learned along the way that can help others who are in the middle of deploying AI in business. Lesson #1: AI doesn’t “just work”The first misconception about AI—and probably the most common—is that it’s a kind of silver bullet that “just works”. The truth is, AI must be purpose-built to extract the most value and insights from data. It requires a deep understanding of the problem at hand and the unique challenges it presents. With a goal to improve the affordability and quality of care, we focus on helping healthcare organizations use AI to understand the individual and provide personalized experiences. Google addresses this learning head-on with Deployed AI, a uniquely pragmatic approach that echoes our belief that although AI is incredibly powerful—and often transformative—it’s not magic.It also takes patience to iterate, experiment, and learn from mistakes, from stakeholders at every level of an organization. Operating ML infrastructure and live production models is hard.The CI/CD philosophy you apply to traditional software can be applied to models as well. These practices—also called “MLOps”—may not be the most attractive parts of AI, but they’re an essential part of successful deployments. We’re doing the ML Ops heavy lifting on behalf of our customers. Through Lumiata’s MLOps framework, models can be automatically monitored, validated, and tested so model performance is continuously optimized.Lesson #2: AI is about much more than modelsNext, I believe a disproportionate amount of attention is paid to machine learning models themselves, making it easy to underestimate the universe of supporting components that surrounds them and makes them work. There’s the data that trains the model, for instance, as well as the infrastructure that connects everything—two areas in which Google has deeper roots than just about anyone. Healthcare organizations are sitting on large volumes of data, but its visibility and access to the data science and analytics teams are limited. This impedes their ability to apply AI to meaningfully solve relevant problems. BigQuery, Google’s serverless data warehouse, enables us to solve this challenge for our users by providing access to large volumes of data with no operational hurdle at all.In addition to data, building, deploying, and maintaining machine learning models requires significant computational horsepower. Our customers often struggle to get buy-in from their technology counterparts to scale their infrastructure requirements for machine learning. With the help of Google Kubernetes Engine, our platform helps them meet their compute requirements for machine learning with ease and flexibility. Lesson #3: AI is a team sportThe bottom line is that even the most sophisticated machine learning model is but a single part of a larger system. Building that system—an AI deployment that makes a real-world difference—takes software engineering muscle, a culture of DevOps, and the tooling developers need to rapidly automate, test, deploy, and measure the results.Smaller companies often benefit from generalists that wear a number of hats, while bigger companies can afford to hire a range of specialists. Either way, engagement between disciplines is key: for instance, it’s vital to encourage machine learning experts to participate in development activities like testing and automation. There’s also the question of proportion; both engineering talent and AI vision are vital, but the former is generally needed in larger numbers than the latter. There’s no substitute for at least one qualified voice to push the envelope with advanced models that optimize for multiple variables or deliver transparency reasoning—sometimes known as “explainability”—along with their predictions; but it takes a far larger group of engineers to bring such a vision into production in a robust, efficient way.Adoption of AI in healthcare is limited partially due to the talent gap. Recruiting and retaining top talent to build an AI-architecture can be challenging. We strive to alleviate this challenge for our customers through our platform by automating many aspects of the machine learning pipeline, and thereby enabling them to deploy AI faster.  Finally, be ready to continually test your deployment once it goes into production. Real-time monitoring helps ensuring models perform as expected and remain consistent. ConclusionAI may be complex, but we remain big believers in its remarkable potential to transform business. That’s why we founded Lumiata—to address these challenges ourselves so healthcare organizations can focus on innovations that improve affordability and quality of care.We’re helping to make healthcare smarter. And with Google Cloud, we’re getting there faster than ever.Learn more about AI on Google Cloud.
Quelle: Google Cloud Platform

PaaS vs KaaS: What’s the difference, and when does it matter?

The post PaaS vs KaaS: What’s the difference, and when does it matter? appeared first on Mirantis | Pure Play Open Cloud.
Earlier this month I had the pleasure of addressing the issue of Platform as a Service vs Kubernetes as a Service. We talked about the differences between the two modes, and their relative strengths and weaknesses. If you’d like to see the full webinar, you can click this link, but there were several questions we didn’t get to, and I promised to recap all of them in a blog.
Is it possible to have a PaaS that’s also a KaaS?
Yes.  While a PaaS is designed to provide applications for developers to use without having to worry about deploying them, a KaaS is designed to deploy Kubernetes clusters for developers.  There’s no reason that a PaaS can’t offer a Kubernetes cluster as an “application” to be deployed, though not all do.
Can you deploy a PaaS on Kubernetes?
Yes. At the end of the day, a PaaS is just an application, and it needs to be deployed somewhere.  If it’s already containerized, of course it can be deployed on Kubernetes. If not, it might take some additional work, but yes, it’s possible.
If the applications are written for AKS or EKS or PKS will they be locked into that respective provider APIs?
Any time you’re writing to a specific API, you’re locked into that API.  If it’s the Kubernetes API, or the OpenStack API, or any other open source API, your application can then be used anywhere that API is available.  If, however, you write to an API that’s only available from a particular provider (such as AKS or EKS or PKS) then you’re locked into that provider.
Are there open source KaaS solutions out there? Or do most people resort to Ansible/kubeadm automation to standup the clusters? This may only be relevant to organizations that run K8s on prem.
In general, most people do resort to a single-cluster tool such as Kubeadm, but once you get past a couple of clusters, a full-blown KaaS solution is generally more convenient.  There are some open source solutions, such as Kubespray, KQueen and Gardener, but so far, none that have really captured the market.
Can you talk more about why you consider OpenShift to be more PaaS than KaaS?
Most of my experience with OpenShift has been with OpenShift 3, which is definitely a PaaS; it’s essentially a single Kubernetes cluster with an application catalog and a wrapper, oc, for OpenShift-specific commands.  A single tenant can deploy a “project” which is architecturally just a namespace. (Which leads to the interesting side-effect that every project has to have a globally-unique name, but that’s just a side issue.) In to that project, OpenShift uses Operators to deploy applications of the user’s choice.
The important thing to note here is that the user has NOT been provisioned a Kubernetes cluster; they’re just squatting on the main cluster that is OpenShift.  So OpenShift 3 is definitely not a KaaS.
As another attendee of the webinar pointed out, OpenShift’s original motivations were to provide easy access to CI/CD and Software Defined Networking; Kubernetes was an afterthought.  (In fact early versions of OpenShift didn’t use it at all.)
I’ve been told that OpenShift 4 is more KaaS-like, which I assume means that it can deploy an independant Kubernetes cluster for you to use, but I’ve been unable to verify that through the documentation, and OpenShift Online still uses version 3.  (If someone has more information on this issue, I’d love to hear it.)
In terms of adoption, do we see more KaaS compared to PaaS?
That all depends on how you’re defining each. KaaS is definitely going to take off in the next few years, particularly as Edge Computing becomes more important and the need for deploying multiple clusters becomes impossible to ignore.  That said, however, many KaaSes also include application catalogs, so while the function of PaaS will continue to be important, it’s possible that stand-alone PaaSes themselves might begin to fall by the wayside.
Does KaaS provision nodes across a cluster or even multiple pods in a node?
Let’s get straight where KaaS fits in in the “provisioning” world. KaaS provisions the actual Kubernetes cluster, and not individual pods.  For example, if I were using Mirantis KaaS, I might define 5 servers to be used, and then specify that I want 3 control nodes and 2 worker nodes, which would then be spread across those 5 machines.
Once the cluster itself had been provisioned, I could then deploy my pods on those Kubernetes nodes, but that’s independent of the KaaS.
In the PDF you list Pivotal’s PKS but not PCF. I thought PKS was still beta. Can you speak where PCF fits in? It is clearly (non-k8s) PaaS, but is there anything more to add?
By PCF I assume that you’re referring to Pivotal Platform, which is not so much PaaS as an umbrella project for multiple things, including Pivotal Container Service (the KaaS), Pivotal Application Service, and Pivotal Function Service. Like OpenShift, it appears to be focused more on the CI/CD process.
If you know, what do you think about the EIRINI CloudFoundry project? Integrating Application Runtime & K8s. Is it a real convergence between PaaS and KaaS?
Yes, it does give CF KaaS capabilities. It only allows for CF Orchestration to be applied to Kubernetes Containers as well as VMs. They created a “plugin” to their CF Engine to call the same things, for example, that might be called in a KaaS.
Does OpenShift support Kubespray?
It doesn’t appear to, and there’s no mention of it in the documentation.
In your opinion, what is more cost-effective, KaaS or PaaS?
Like most questions that involve cost and technology, the answer is “it depends”.  There are a number of different factors that matter, such as what you’re trying to accomplish, your infrastructure, and your use case.  (Contact us and we’ll be happy to help you take a look at your situation.)
 
The post PaaS vs KaaS: What’s the difference, and when does it matter? appeared first on Mirantis | Pure Play Open Cloud.
Quelle: Mirantis

How to Handle OpenShift Worker Nodes Resources in Overcommitted State

One of the benefits in adopting a system like OpenShift is facilitating burstable and scalable workload. Horizontal application scaling involves adding or removing instances of an application to match demand. When OpenShift schedules a Pod, it’s important that the nodes have enough resources to actually run it. If a user schedules a large application (in the form of Pod) on a node with limited resources , it is possible for the node to run out of memory or CPU resources and for things to stop working!
It’s also possible for applications to take up more resources than they should. This could be caused by a team spinning up more replicas than they need to artificially decrease latency or simply because of a configuration change that causes a program to go out of control and try to use 100% of the available CPU resources. Regardless of whether the issue is caused by a bad developer, bad code, or bad luck, what’s important is how a cluster administrator can manage and maintain control of the resources.
In this blog, let’s take a look at how you can solve these problems using best practices.
What does “overcommitment” mean in OpenShift ? 
In an overcommitted state, the sum of the container compute resource requests and limits exceeds the resources available on the system. 
Overcommitment might be desirable in development environments where a tradeoff of guaranteed performance for capacity is acceptable.Therefore, in an overcommitted environment, it is important to properly configure your worker node to provide the best system behavior. With this note let’s find out what needs to be enabled on the worker nodes in an overcommitted environment.
Prerequisites for the overcommitted worker nodes: 
The following prerequisites flow chart describes all the checks that should be performed on the worker nodes. Let’s go into the details one by one.

 1. Is the worker node ready for overcommitment? 
In OpenShift Container Platform overcommitment is enabled by default. If not, it is always advisable to cross check. When the node starts, it ensures that the kernel tunable flags for memory management are set properly. The kernel should never fail memory allocations unless it runs out of physical memory.
To ensure this behavior, OpenShift Container Platform configures the kernel to always overcommit memory by setting the vm.overcommit_memory parameter to 1, overriding the default operating system setting.
OpenShift Container Platform also configures the kernel not to panic when it runs out of memory by setting vm.panic_on_oom parameter to 0. A setting of 0 instructs the kernel to call oom_killer in an Out of Memory (OOM) condition, which kills processes based on priority.
You can view the current setting by running the following commands on your nodes:
$ oc debug node/<worker node>
Starting pod/<worker node>-debug …
If you don’t see a command prompt, try pressing enter.
sh-4.2# sysctl -a |grep commit
vm.overcommit_memory = 1
sh-4.2# sysctl -a |grep panic
vm.panic_on_oom = 0

In case your worker node settings are different than the expected you can easily set it via machine-config operator for RHCOS and for RHEL via below command .
$ sysctl -w vm.overcommit_memory=1
 2. Is the worker node enforcing CPU limits using CPU CFS quotas ?
The Completely Fair Scheduler (CFS) is a process scheduler which was merged into the Linux Kernel 2.6.23 release (October 2007) and is the default scheduler. It handles CPU resource allocation for executing processes, and aims to maximize overall CPU utilization while also maximizing interactive performance.
By default, the Kubelet uses CFS quota to enforce pod CPU limits. For example, when a user sets a limit on CPU to 100 millicores for the pod, kubernetes (via the kubelet on the node) specifies a CFS quota for CPU on the pod’s processes. The pod/’s processes get throttled if they try to use more than the CPU limit.
When the node runs many CPU-bound pods, the workload can move to different CPU cores depending on whether the pod is throttled and which CPU cores are available at scheduling time.  Many workloads are not sensitive to this migration and thus work fine without any intervention.
kubeletArguments:
 cpu-cfs-quota:
   – “True”
 3. Are enough resources reserved for system and kube processes per node?
To provide more reliable scheduling and minimize node resource overcommitment, each node can reserve a portion of its resources for use by all underlying node components (such as kubelet, kube-proxy) and the remaining system components (such as sshd, NetworkManager) on the host.
CPU and memory resources reserved for node components in OpenShift Container Platform are based on two node settings:

kube-reserved
Resources reserved for node components. Default is none.

system-reserved
Resources reserved for the remaining system components. Default is none.

 
If a flag is not set, it defaults to 0. If none of the flags are set, the allocated resource is set to the node’s capacity as it was before the introduction of allocatable resources.
The below table summarizes the recommended resources to be reserved per worker node . This is based upon OpenShift version 4.1. Also note that this does not include the resources required to run any 3rd party CNI plugin , its operator etc.

You can set the reserved resources with the help of machineconfigpool and KubeletConfig (CR) as shown in the example below .
Find out the correct machineconfigpool for your worker node and label it if not done already.
$ oc describe machineconfigpool worker

apiVersion: machineconfiguration.openshift.io/v1
kind: MachineConfigPool
metadata:
 creationTimestamp: 2019-02-08T14:52:39Z
 generation: 1
 labels:
   custom-kubelet: small-pods

$ oc label machineconfigpool worker custom-kubelet=small-pods
Create a KubeletConfig as shown below and set the desired resources for system and kube processes .
apiVersion: machineconfiguration.openshift.io/v1
kind: KubeletConfig
metadata:
 name: set-allocatable 
spec:
 machineConfigPoolSelector:
   matchLabels:
     custom-kubelet: small-pods 
 kubeletConfig:
   systemReserved:
     cpu: 500m
     memory: 512Mi
   kubeReserved:
     cpu: 500m
     memory: 512Mi

 4. Is swap memory disabled on the worker node?
By default, OpenShift disables swap partitions in the Node. A good practice in Kubernetes clusters is to disable swap on the cluster nodes in order to preserve quality of service (QOS) guarantees. Otherwise, physical resources on a node can oversubscribe, affecting the resource guarantees the Kubernetes scheduler makes during pod placement.
For example, if two guaranteed pods have reached their memory limit, each container could start using swap memory. Eventually, if there is not enough swap space, processes in the pods can be terminated due to the system being oversubscribed.
Failing to disable swap results in nodes not recognizing that they are experiencing MemoryPressure, resulting in pods not receiving the memory they made in their scheduling request. As a result, additional pods are placed on the node to further increase memory pressure, ultimately increasing your risk of experiencing a system out of memory (OOM) event.
 5. Is QoS defined ?
In an overcommitted environment, it is possible that the pods on the node will attempt to use more compute resources than is available at any given point in time. When this occurs, the node must give priority to one pod over another. The facility used to make this decision is referred to as a Quality of Service (QoS) Class.
For each compute resource, a container is divided into one of three QoS classes with decreasing order of priority.

Priority
Class
Name
Description

1 
Guaranteed
If limits and optionally requests are set (not equal to 0) for all resources and they are equal, then the container is classified as Guaranteed.

2
Burstable
If requests and optionally limits are set (not equal to 0) for all resources, and they are not equal, then the container is classified as Burstable.

3 
BestEffort
If requests and limits are not set for any of the resources, then the container is classified as BestEffort.

 
A priority class object can take any 32-bit integer value smaller than or equal to 1000000000 (one billion). Reserve numbers larger than one billion for critical pods that should not be preempted or evicted. For the critical Pods we define two classes .For example :

System-node-critical – This priority class has a value of 2000001000 and is used for all pods that should never be evicted from a node.
System-cluster-critical – This priority class has a value of 2000000000 (two billion) and is used with pods that are important for the cluster. Pods with this priority class can be evicted from a node in certain circumstances.

You can also use the qos-reserved parameter to specify a percentage of memory to be reserved by a pod in a particular QoS level. This feature attempts to reserve requested resources to exclude pods from lower QoS classes from using resources requested by pods in higher QoS classes. For example a value of qos-reserved=memory=100% will prevent the Burstable and BestEffort QoS classes from consuming memory that was requested by a higher QoS class i.e. Guaranteed QoS. Similarly, a value of qos-reserved=memory=0% will allow a Burstable and BestEffort QoS classes to consume up to the full node allocatable amount if available, but increases the risk that a Guaranteed workload will not have access to the requested memory.
 
Mechanisms to control the resources on the overcommitted worker nodes :
After executing the prerequisites on the worker nodes / cluster  it’s time now to see what all mechanisms are available from the kubernetes side to control the resources like CPU, Memory , Ephemeral storage, Ingress and Egress traffic etc.

Limit Ranges: 

A limit range, defined by a LimitRange object, enumerates compute resource constraints in a project at the pod, container, image, image stream, and persistent volume claim level, and specifies the amount of resources that a pod, container, image, image stream, or persistent volume claim can consume.All resources create and modification requests are evaluated against each LimitRange object in the project. If the resource violates any of the enumerated constraints, then the resource is rejected. If the resource does not set an explicit value, and if the constraint supports a default value, then the default value is applied to the resource.
Below is the example of limit range definition.
apiVersion: “v1″
kind: “LimitRange”
metadata:
 name: “core-resource-limits” 
spec:
 limits:
   – type: “Pod”
     max:
       cpu: “2” 
       memory: “1Gi” 
     min:
       cpu: “200m” 
       memory: “6Mi” 
   – type: “Container”
     max:
       cpu: “2” 
       memory: “1Gi” 
     min:
       cpu: “100m” 
       memory: “4Mi” 
     default:
       cpu: “300m” 
       memory: “200Mi” 
     defaultRequest:
       cpu: “200m” 
       memory: “100Mi” 
     maxLimitRequestRatio:
       cpu: “10” 

 2. CPU Requests:
Each container in a pod can specify the amount of CPU it requests on a node. The scheduler uses CPU requests to find a node with an appropriate fit for a container.The CPU request represents a minimum amount of CPU that your container may consume, but if there is no contention for CPU, it can use all available CPU on the node. If there is CPU contention on the node, CPU requests provide a relative weight across all containers on the system for how much CPU time the container may use.On the node, CPU requests map to Kernel CFS shares to enforce this behavior.
 3. CPU Limits:
Each container in a pod can specify the amount of CPU it is limited to use on a node. CPU limits control the maximum amount of CPU that your container may use independent of contention on the node. If a container attempts to exceed the specified limit, the system will throttle the container. This allows the container to have a consistent level of service independent of the number of pods scheduled to the node.
 4. Memory Requests:
By default, a container is able to consume as much memory on the node as possible. In order to improve placement of pods in the cluster, specify the amount of memory required for a container to run. The scheduler will then take available node memory capacity into account prior to binding your pod to a node. A container is still able to consume as much memory on the node as possible even when specifying a request.
 5. Memory Limits:
If you specify a memory limit, you can constrain the amount of memory the container can use. For example, if you specify a limit of 200Mi, a container will be limited to using that amount of memory on the node. If the container exceeds the specified memory limit, it will be terminated and potentially restarted dependent upon the container restart policy.
 6. Ephemeral Storage Requests:
By default, a container is able to consume as much local ephemeral storage on the node as is available. In order to improve placement of pods in the cluster, specify the amount of required local ephemeral storage for a container to run. The scheduler will then take available node local storage capacity into account prior to binding your pod to a node. A container is still able to consume as much local ephemeral storage on the node as possible even when specifying a request.
 7. Ephemeral Storage Limits:
If you specify an ephemeral storage limit, you can constrain the amount of ephemeral storage the container can use. For example, if you specify a limit of 2Gi, a container will be limited to using that amount of ephemeral storage on the node. If the container exceeds the specified memory limit, it will be terminated and potentially restarted dependent upon the container restart policy.
 8. Pods per Core:
The podsPerCore parameter limits the number of pods the node can run based on the number of processor cores on the node. For example, if podsPerCore is set to 10 on a node with 4 processor cores, the maximum number of pods allowed on the node is 40.
 9. Max Pods per node:
The maxPods parameter limits the number of pods the node can run to a fixed value, regardless of the properties of the node.Two parameters control the maximum number of pods that can be scheduled to a node: podsPerCore and maxPods. If you use both options, the lower of the two limits the number of pods on a nodeIn order to configure these parameters , label the machineconfigpool.
$ oc label machineconfigpool worker custom-kubelet=small-pods

$ oc describe machineconfigpool worker

apiVersion: machineconfiguration.openshift.io/v1
kind: MachineConfigPool
metadata:
 creationTimestamp: 2019-02-08T14:52:39Z
 generation: 1
 labels:
   custom-kubelet: small-pods
Create the KubeletConfig (CR) as shown below.
apiVersion: machineconfiguration.openshift.io/v1
kind: KubeletConfig
metadata:
 name: set-max-pods 
spec:
 machineConfigPoolSelector:
   matchLabels:
     custom-kubelet: small-pods 
 kubeletConfig:
   podsPerCore: 10 
   maxPods: 250

 10. Limiting the bandwidth available to the Pods:
You can apply quality-of-service traffic shaping to a pod and effectively limit its available bandwidth. Egress traffic (from the pod) is handled by policing, which simply drops packets in excess of the configured rate. Ingress traffic (to the pod) is handled by shaping queued packets to effectively handle data. The limits you place on a pod do not affect the bandwidth of other pods.To limit the bandwidth on a pod you can specify the data traffic speed using kubernetes.io/ingress-bandwidth and kubernetes.io/egress-bandwidth annotations as shown below.
{
   “kind”: “Pod”,
   “spec”: {
       “containers”: [
           {
               “image”: “openshift/hello-openshift”,
               “name”: “hello-openshift”
           }
       ]
   },
   “apiVersion”: “v1″,
   “metadata”: {
       “name”: “iperf-slow”,
       “annotations”: {
           “kubernetes.io/ingress-bandwidth”: “10M”,
           “kubernetes.io/egress-bandwidth”: “10M”
       }
   }
}
Conclusion:
As you can see from the post, there are about 10 mechanisms available from the kubernetes perspective which can be used very effectively to control the resources on the worker nodes in the overcommitment state provided pre-requisites are applied at first place. Now which mechanism to be used preciously is entirely depends upon the end user and the use case he or she is trying to solve.
The post How to Handle OpenShift Worker Nodes Resources in Overcommitted State appeared first on Red Hat OpenShift Blog.
Quelle: OpenShift