<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tal Maoz on Medium]]></title>
        <description><![CDATA[Stories by Tal Maoz on Medium]]></description>
        <link>https://medium.com/@tal.maoz?source=rss-e300705c6cf2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BhXNhs8oEFJCOVEdtGzHNQ.png</url>
            <title>Stories by Tal Maoz on Medium</title>
            <link>https://medium.com/@tal.maoz?source=rss-e300705c6cf2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:51:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tal.maoz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Taming of the Queue]]></title>
            <link>https://medium.com/cisco-fpie/taming-of-the-queue-f320f855a09?source=rss-e300705c6cf2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f320f855a09</guid>
            <category><![CDATA[aws-msk]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[aws-documentdb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Tal Maoz]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 17:45:13 GMT</pubDate>
            <atom:updated>2022-08-11T07:19:56.806Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Dynamic Data Pipes Using AWS DocumentDB, MSK and Lambda</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*peJzFvRL2NOVFD8t8keEMA.jpeg" /></figure><p>There are many data driven applications that require online processing of data as well as storing the raw data. Some examples include recommendation engines, IoT processors, event-driven services and more. If you’ve ever needed to build some kind of data processing pipeline or workflow, you’re probably familiar with the challenges of handling multiple data types while accounting for the possibility of new data types coming in during the lifetime of your system.</p><p>In this article I will discuss a solution I came up with for a recent project using AWS DocumentDB, MSK and Lambda functions, and will provide instructions for deploying a simple pipeline along with useful Go code snippets.</p><h3>The Design</h3><p>When building a data processing pipeline, one typically needs two components: data transmission and processing blocks. Processing blocks are manipulations applied to the incoming data in a given sequence that may change depending on the type of data, while the data transmission is the means by which data is moved between the various processing blocks. You can think of this as a production line where the conveyor belt moves the products in their various stages between the various stations until the final product comes out the end of the line. The conveyor belt is our data transmission, and the stations are the processing blocks.</p><p>More often than not, you also want a means of storage for the raw data because you never know what you may want to do with it later on, or if some error would force you to run your data through the pipeline again.</p><p>My design requirements were simple:</p><ol><li>Build a fully managed system</li><li>Keep a copy of all the raw data</li><li>Process data in near real-time and in low-latency</li><li>Account for the possibility of new data types coming in over time without requiring system downtime</li></ol><p>After looking into several options, I settled on the following design for my pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iW1HV-591RfTn0ZxSP3ug.png" /><figcaption>Architecture Diagram</figcaption></figure><p>Let us start by going over the building blocks we will use to understand what they are and how we can use them:</p><p><a href="https://aws.amazon.com/documentdb/">AWS DocumentDB</a> is Amazon’s managed <a href="https://www.mongodb.com/">MongoDB</a> service based on MongoDB 3.6 or 4.0. As such, it can store, query and index JSON and BSON data. MongoDB is a source-available NoSQL JSON database that uses <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a> as the basis for its query language thus allowing you to also run JavaScript functions server-side. Within a MongoDB deployment, one can define multiple DBs with multiple collections in each one. One useful feature introduced in Mongo 3.6 are <a href="https://www.mongodb.com/docs/manual/changeStreams/">Change Streams</a>. Change Streams allow applications to access real-time data changes by registering for events on specific collections. The event notifications can be configured to include the deltas or full documents and capture “insert”, “change” and “delete” events.</p><p><a href="https://aws.amazon.com/msk/">AWS MSK (Managed Streaming for Apache Kafka)</a> is Amazon’s managed Kafka service. <a href="https://kafka.apache.org/">Apache Kafka</a> is a widely used open-source distributed event store and stream-processing platform. Kafka is designed for high-throughput low-latency real-time data processing. With Kafka you can define “topics” to which you can publish key/value messages. Multiple publishers can publish to a topic and multiple consumers can consume it. Kafka topics are managed using a <a href="https://zookeeper.apache.org/">ZooKeeper</a> cluster while publishing and consuming is done via Kafka brokers.</p><p><a href="https://aws.amazon.com/lambda/">AWS Lambda</a> is a serverless, event-driven compute service that lets you run code in response to various events and triggers while automatically managing the underlying compute resources required by your code. Lambda supports many programming languages including Node.js, Python, Java, Ruby, C# and Go. A very useful feature of Lambda is the ability to trigger functions on Kafka topics, which makes it ideal for usage as part of a data processing pipeline.</p><p><a href="https://aws.amazon.com/vpc/">AWS VPC</a> is a way to create Virtual Private Networks within AWS. This allows you to contain services in a more secure environment and gives you total control over who and what has access to the network and the resources within.</p><p><a href="https://aws.amazon.com/ec2/">AWS EC2</a> is Amazon’s Elastic Compute Cloud where you can deploy virtual or physical instances (computers) and manage their security and networking properties.</p><p><a href="https://aws.amazon.com/s3/">AWS S3</a> is a Simple Storage Service. With the S3 object storage you can create buckets and then store files and folders within them. S3 gives you full access control and security.</p><p><a href="https://aws.amazon.com/iam/">AWS IAM</a> is Amazon’s Identity and Access Management system. IAM lets you manage users, roles, and policies so you can achieve fine grained access control over your resources and grant access to other users and AWS accounts in a secure way.</p><p><a href="https://aws.amazon.com/cloudwatch/">AWS CloudWatch</a> is Amazon’s observability platform where you can aggregate logs from AWS services and easily filter and search through them.</p><h3>Putting Things Together</h3><p>The idea is that DocumentDB is used as the entry point into the pipeline while MSK acts as the data transmission. Each path between processing blocks is implemented using a Kafka topic. One processing block publishes its output to the topic while the next block in line consumes the topic to get its input. The first processing block will act as a “router” that analyses the new data and decides what type it is. It the published the data to a dedicated topic for that data type so the proper processing blocks can be used on that data.</p><p>I start by inserting a new piece of raw data into DocumentDB. Next, I use an MSK connector to register to a change stream for my DocumentDB collection and push the newly inserted documents into an initial MSK topic, which is the input to the “router”. Then, I configure a Lambda-based “router” function to consume the initial MSK topic, analyze the messages and publish each one to a dedicated MSK topic. Finally, for each data-type dedicated topic, I would have a specific Lambda function that knows how to process that data. I can then continue building more processing elements on the pipeline as required.</p><p>Once all the pieces are in place, all I have to do to run new data through the pipeline is simply insert it into my DocumentDB collection. From that point on, everything happens automatically. Moreover, by using the combination of Kafka topics and Lambda functions, I can dynamically create topics for new types of data messages and then define handlers to process them. The messages would wait in the topic until I build a processor that can handle them, and as soon as I deploy the new processor, it can start processing the messages, which means messages are never lost. This design also allows me to dynamically change the layout of my processing pipeline over time.</p><p>In order to configure DocumentDB and MSK, I make use of a bastion instance that I deploy on EC2. This instance allows me to connect to my VPC using a secure SSH connection as well as use port forwarding to give my local environment access to the VPC.</p><p>I use an S3 bucket to store the Kafka connector package as well as my Lambda functions’ code package. In addition, I use IAM to create the required execution roles for the Kafka connector and the Lambda functions.</p><p>Finally, I use CloudWatch to gain visibility to what the Lambda functions are doing by funneling the Lambda logs into CloudWatch log groups.</p><p>Let us now go over each of the components and see how to provision and/or deploy them.</p><h3>VPC Gateway</h3><p>DocumentDB as well as MSK are both deployed only in a VPC. Thus, in order to connect to them from your local machine for development, testing and debugging, you need to create a gateway into your VPC. We will use the default VPC, but any VPC can be used instead. Please refer to the <a href="https://docs.aws.amazon.com/vpc/latest/userguide/vpc-getting-started.html">AWS documentation</a> for information on how to create a new VPC in case the default one is not appropriate.</p><p>We start by creating an EC2 instance that we will use as our gateway. Simply launch a new EC2 instance in the default VPC and choose Ubuntu 20.04 as the OS image (there is no support for the mongo CLI in Ubuntu 22.04 at the time of writing this article):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*UNQQyz06Q51fFYSveLqYPQ.png" /><figcaption>Launch New EC2 Instance</figcaption></figure><p>Next, create an SSH key-pair you will use to access the new instance from your local machine. Click on “Create new key pair” to create a new key pair and download the public key, or choose an existing one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ZNNhRZq4aIEYgQ-cHnOX7A.png" /><figcaption>New EC2 Instance SSH Key Pair</figcaption></figure><p>Next, we look at the “Network Settings” section. Make sure you select the VPC you wish to use and the security group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*RqQnnMeqqVtTJbtE8t02dg.png" /><figcaption>New EC2 Instance Network Settings</figcaption></figure><p>Finally, launch your new instance. Once your instance is up, you can SSH into the new instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Xkpt8gRVRu35S7095p9how.png" /><figcaption>SSH Into the New Instance</figcaption></figure><h3>DocumentDB</h3><p>Now that we have a VPC, we can start looking into deploying DocumentDB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*zGQHMkz_A9iNMHQrBAFH8w.png" /><figcaption>Architecture — DocumentDB</figcaption></figure><p>Start by going into the Amazon DocumentDB dashboard and click on “Create Cluster”. Give your cluster a name, make sure the selected engine version (MongoDB version) is “4.0.0” and select the desired instance class.</p><p>The connectors we will use to let MSK register to the DocumentDB change stream require that the MongoDB deployment be part of a replica-set so make sure the number of instances is greater than 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*W-FPfjbuZi9SECGesref-g.png" /><figcaption>DocumentDB — Launch New Instance</figcaption></figure><p>Next, under the authentication section, fill in the admin username and password you would like to use in your cluster.</p><p>Now, click on the “Show advanced settings” toggle at the bottom to open the network settings and make sure that the selected VPC is the same as the one in which you deployed your EC2 instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*_Ur2zrU0UC47bDDN30ZG6A.png" /><figcaption>DocumentDB — New Instance Network Settings</figcaption></figure><p>Tweak any other settings and then click on the “Create cluster” button at the bottom to launch the new cluster. The process takes a few minutes and then you will see the following or similar according to your choices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0V7SBCLuByJIpjxNuxt1xA.png" /><figcaption>AWS Document DB Cluster</figcaption></figure><p>To test our new cluster, we need to install the mongo client in our EC2 gateway instance. Follow these instructions to do so: <a href="https://www.mongodb.com/docs/mongodb-shell/install/">https://www.mongodb.com/docs/mongodb-shell/install/</a></p><p>Next, go into the cluster details in the AWS console and follow the instruction to download the CA certificate to your EC2 instance and then run the newly installed mongo client to connect to your new cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*pVOLc0YNRbpRuD653xRtog.png" /><figcaption>Connecting to DocumentDB using mongo shell</figcaption></figure><p>If the connection fails, you may need to manage the DocumentDB cluster’s security group to allow access to your EC2 instance’s security group. To do so, go into the cluster’s details and scroll down to the “Security Groups” section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9wL6L0jbu86ygJuswTSjA.png" /><figcaption>AWS Security Groups</figcaption></figure><p>Select the security group and then go into the “Inbound rules” tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_EgHJ9OzXcILZF3pTpY4w.png" /><figcaption>AWS Security Group Inbound Rules</figcaption></figure><p>Click on the “Edit inbound rules” button to edit the inbound rules and then add a rule that allows the traffic type you need (if you need to specify a port, use 27017) from a “Custom” source. In the search box, search for and select the security group you used for the EC2 instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMUR8HOS-Pmx0oB5oZAOVg.png" /><figcaption>Adding Inbound Rule to AWS Security Group</figcaption></figure><p>Finally, save the rules. You should now have access from your instance to DocumentDB.</p><p>To make development and debugging easier, you may want to use a tool such as <a href="https://snapcraft.io/install/robo3t-snap/ubuntu">Robo 3T</a>,that lets you access MongoDB using a nice GUI that is intuitive and easy to use and that lets you view and manage data conveniently. You will need to forward port 27017 from your local machine to DocumentDB via the EC2 instance using SSH:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQhEzt-slgAPsFQVV0AVww.png" /><figcaption>SSH to the Gateway with Port Forwarding to DocumentDB</figcaption></figure><p>Now you can configure your local Robo 3T or mongo client to access port 27017 on your local machine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RxEGm9P-Xp9FGrTH_UQoA.png" /><figcaption>Robo 3T — New Connection</figcaption></figure><p>For Robo 3T, make sure to allow invalid hostnames because your local hostname is different than the one in the CA certificate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iku-6IXiaWj-_hHjoh3kAw.png" /><figcaption>Robo 3T — setting CA Certificate</figcaption></figure><p>Now, we can create a new Database called “pipeline” and in it a collection called “intake”. We also create a new user called “puser” that has read permissions for the “pipeline” database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*-M1Jxm4Kh3nv7hvooStMTw.png" /><figcaption>Robo 3T — After Creating A Collection and A User</figcaption></figure><p>The last thing we need to do is enable change streams on our new collection. To do that we need to connect to DocumentDB as we did above and then run the following command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2768c4d5b8765bf0fdc05eb42a521b8/href">https://medium.com/media/c2768c4d5b8765bf0fdc05eb42a521b8/href</a></iframe><p>If you are using Robo 3T as I do, right click on the “pipeline” database in the tree on the left and then select “Open Shell”. Now you can enter the above command and use <em>CTRL+ENTER</em> to execute it.</p><h3>MSK</h3><p>Now that we have DocumentDB set up, we can move on to MSK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eee4MKULcxOZsBj_WurFmg.png" /><figcaption>Architecture — MSK</figcaption></figure><p>We will be deploying our MSK cluster using the “Quick create” option. For this little demo we will use the “kafka.t3.small” flavor and allocate only 1GB of space. If you need to change the network settings to choose a different VPC, zones and subnets, you will have to switch from “Quick create” to “Custom create”.</p><p>In any case, make sure that your MSK cluster is in the same VPC and subnets as the gateway EC2 instance. Otherwise, you would have to start configuring routing between the VPC or subnets, which we will NOT cover in this article.</p><p>When done, click on the “Create cluster” button and wait until your cluster is up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugwhrORKn7F8jy3PkyWLTQ.png" /><figcaption>MSK Cluster</figcaption></figure><p>To test our cluster, we need to get the brokers’ addresses. Click on the cluster, select the “properties” tab and scroll down to the “Brokers” section. There, you will find a list of the brokers that have been deployed as part of the cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uCmciFMw0H_Btk4BBReFw.png" /><figcaption>MSK Cluster Brokers</figcaption></figure><p>Managing a Kafka cluster is done using the Kafka CLI tools. The CLI tools require the Java runtime as Kafka is written in Scala which runs on a JVM (Java Virtual Machine). We are using openjdk-8-jre. Now, download the Kafka package from <a href="https://kafka.apache.org/downloads">https://kafka.apache.org/downloads</a> to the EC2 instance and extract it. For this document, we are using Kafka 2.13–3.1.0 .</p><p>Next, use the “kafka-topics” command to get the list of existing topics. You need to provide a bootstrap server, which can be any of the brokers in the cluster (we use the first one):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFPiIe6NpJkm4WsrTdascA.png" /><figcaption>List Kafka Topics</figcaption></figure><p>Please note that port 9092 does NOT use TLS. If you wish to use a secure TLS connection, you should follow these steps:</p><ol><li>Create a client profile:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1evcO6hvaiadv-WJ6b54A.png" /></figure><p>2. Create the initial trust store:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QdZQUg_PHDJMdrGl0eKMg.png" /></figure><p><em>Note that the location of the “cacerts” file will change according to the JRE you installed on your machine.</em></p><p>3. Finally run the command as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edYURmF2t41vJiKui6rKZA.png" /></figure><p>Now that we have our MSK cluster deployed and accessible, we can create our initial topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRiK8c1b5o0RGr4F9okojA.png" /></figure><p>Let us publish a test message to our new topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBaGRNJVzKezt34nu9rvNQ.png" /></figure><p>We can see that our new message was, indeed, published and can be consumed as well.</p><p>But how do we clear out a topic? There is no way to directly delete messages from a topic. Instead, we have to change the retention policy and wait for Kafka to delete all the expired messages for us before we can restore our original retention policy.</p><p>First, we get the current settings and see that there is no policy set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C383mHaEiVdLCVAGTgKV7Q.png" /></figure><p>Thus, the default policy applies which is 7 days (<a href="https://docs.confluent.io/platform/current/installation/configuration/topic-configs.html">https://docs.confluent.io/platform/current/installation/configuration/topic-configs.html</a>). We now change that policy to one second:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuDtkxcZVQ4e_vKaQiBh-w.png" /></figure><p>It takes a little while for the new policy to take effect, but once it does, we can run our consumer and see that there is nothing in the topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUvbG6vknSSyfPzmwOkMSA.png" /></figure><p>Finally, we can restore the default policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_qutKDbsJ5mx8cMgBwlxA.png" /></figure><h3>S3</h3><p>If order to create a Kafka MongoDB connector and to make reusing Lambda code easier, we need to create an S3 bucket where the code packages would be kept.</p><p>To do that, start by going to the S3 dashboard and create a new bucket by clicking the “Create bucket” button. Fill in the name for your new bucket, select the requested region and then scroll down and click on the “Create bucket” button. We keep all the default options for now, but you can play with them later if you wish to change anything.</p><h3>IAM Execution Role</h3><p>Our next challenge is tying DocumentDB to Kafka so that inserting new documents into DocumentDB would automatically put notifications with the full document data into a given Kafka topic. For this we are going to use a Kafka connector that will register for a Mongo change stream for our collection and then publish the new documents to the chosen Kafka topic.</p><p>We will start by creating an IAM execution role for our new connector. Note, that when creating a connector, AWS will give you the option to create an execution role. However, it turns out that due to some changes made by AWS to how <a href="https://docs.aws.amazon.com/msk/latest/developerguide/msk-connect-service-execution-role.html">execution roles work</a>, using this option results in a Service Linked role that is not usable by MSK Connect. AWS is aware of <a href="https://stackoverflow.com/questions/70885951/aws-msk-connectors-for-debezium-iam-role-problem">this issue</a> but has not fixed it as of the date of writing this article. So, we need to create our own role manually…</p><p>Go to the IAM console, select the “Roles” section on the left and then click on “Create role” on the top right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtHynSy3LORO5-eOHxMtog.png" /><figcaption>IAM — Create New Role</figcaption></figure><p>Next, select the “AWS account” option and then click on “Next”. At this point you can select a policy to use. None of these policies are good for us so just click on “Next” again. Now give your role a name and description and then scroll to the bottom and click on “Create role”.</p><p>Now that we have a role, we need to configure the proper permissions so find your role in the list of roles and click on it. Under the “Permissions” tab click on the “Add permissions” button to open the drop-down menu and select “Create inline policy”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nL0c7MVHX5l-VyQKAbxiWw.png" /><figcaption>IAM — Creating a New Policy For MSK Connect</figcaption></figure><p>We would now like to manually enter a policy so select the “JSON” tab and then replace the existing empty policy with the following one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c7af97f151d66e9f5b8b950a71b55a1/href">https://medium.com/media/4c7af97f151d66e9f5b8b950a71b55a1/href</a></iframe><p>Now click on “Review policy” and then give your new policy a name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyWwvXroxbPSYxzXTvLqXg.png" /><figcaption>IAM — Review Policy</figcaption></figure><p><em>Note that this policy grants many permissions. We do this for simplicity, but you may want to experiment and limit the permissions you grant for better security.</em></p><p>Finally, click on the “Create policy” button at the bottom. You will now be able to see your new policy listed in your role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWMzgDQNtv1kW2C-VUbx1w.png" /><figcaption>IAM — New Inline Policy</figcaption></figure><p>Next, we need to add the proper trust policy so click on the “Trust relationships” tab and then on “Edit trust policy”. In the editor that opened, replace all the text with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/279429c99c4bddbaccc9bd751b89b497/href">https://medium.com/media/279429c99c4bddbaccc9bd751b89b497/href</a></iframe><p>Finally, click on “Update policy” to finalize the new role.</p><h3>CloudWatch</h3><p>In order to keep track of what is going on with our connector and Lambda functions, we need a place to keep our logs. We will use CloudWatch and so we need to create a log group.</p><p>Go to the CloudWatch dashboard, select “Logs” on the left and then “Log groups”. Click on “Create log group” on the right, give your log group a name and a retention setting, and then click on “Create” on the bottom and you are done.</p><p>That was simple!</p><h3>MSK Security Group</h3><p>Another thing to tackle before we can create a Kafka connector is configuring our security group to allow internal communications.</p><p>Go to your MSK cluster’s configurations, click on the “Properties” tab, and then click on the security group that is applied. If you followed this article, you should only have a single security group applied.</p><p>Once you get to the EC2 dashboard and to the security group settings, you need to click on the “Edit inbound rules” button to add the required rule.</p><p>Now, click on the “Add rule” button on the bottom left, select “All traffic” for the rule type and then find your security group in the custom “Source” search box. Make sure to select the same security group as the one you are currently editing. Note that the name of the security group appears in the navigation bar on the top left of the page.</p><p>Finally, click on “Save rules” and you should be set.</p><h3>MSK and DocumentDB Security</h3><p>Now I must point out a slight problem with the DocumentDB connection. We used the default DocumentDB configurations that enables TLS. This means that in order to connect to DocumentDB, we needed to supply the client with the CA file we downloaded from the DocumentDB dashboard. However, since MSK is a managed service, we have no way of installing these certificates in the new plugin. Furthermore, while there is a way to specify the CA file within the MongoDB URI, the current MongoDB driver used within both the Confluent and Debezium connectors simply ignores this option and/or the CA file if we try to include it in the JAR file or in a ZIP file that holds both. If any readers are aware of a way to do this, please let me know so I can update this document. The only other option would be to implement our own connector that would contain the certificates and use them without relying on external files or certificate registries, but this is out of scope for this article.</p><p>Thus, we first need to turn off TLS in our DocumentDB. For this, go back to the DocumentDB dashboard, select “Parameter groups” from the left side menu and then click on the “Create” button on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVeOabHgxYwAlwn9ZUh9PQ.png" /><figcaption>DocumentDB — Creating a New Parameter Group</figcaption></figure><p>Fill in a name for the new parameter group, add a description and click on “Create”.</p><p>Next, click on the new group from the list, then select “tls” from the new list that opens, click on the “Edit” button on the top right of the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiZ98OJIXeYP0ZhgdEu4Jw.png" /><figcaption>DocumentDB — Modify the “tls” Parameter</figcaption></figure><p>Set the selection to “disabled” and click on “Modify cluster parameter”.</p><p>Now, click on “Clusters” from the left side menu and then click on your cluster. Go to the “Configuration” tab and click on the “Modify” button within that tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQKei-UjzmW5F4o8ntcAjw.png" /><figcaption>DocumentDB — Modify Cluster Options</figcaption></figure><p>Under the “Cluster options” section, select the new parameter group that we just created and then scroll down, click on the “Continue” button and finally click on the “Modify cluster” button. This will modify the settings and take you back to the cluster list.</p><p>However, the new settings will not take effect until you reboot the cluster. If you click on the cluster again, you will see that the summary section indicates “pending-reboot”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMGqFvQscxSe_Vxu_dPVQA.png" /><figcaption>DocumentDB — Cluster Pending Reboot</figcaption></figure><p>Go back to the cluster list, select the cluster by clicking on the checkbox next to it, then click on the “Actions” button to open the menu and select “Reboot”. The cluster will now reboot and in a few minutes will be ready for work.</p><h3>Kafka MongoDB Connector</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkqfgvBFzMVApDd8K1pg3A.png" /><figcaption>Architecture — Kafka MongoDB Source Connector</figcaption></figure><p>There are two options we can use, the Confluence connector and the Debezium connector. Both are Java based but the Confluence connector is easier to use so we will focus on that one and mention the differences in the Debezium connector briefly.</p><p>Do NOT go to <a href="https://www.confluent.io/hub/mongodb/kafka-connect-mongodb/">https://www.confluent.io/hub/mongodb/kafka-connect-mongodb/</a> to download the connector from there. Although we ARE going to use this connector, the version you will find there is designed specifically for the confluence cloud and so missing some dependencies required by MSK that are provided by the Confluence cloud.</p><p>Instead, go to the Maven repo at <a href="https://search.maven.org/search?q=a:mongo-kafka-connect">https://search.maven.org/search?q=a:mongo-kafka-connect</a>, click on the “Download” icon on the right and select “all”. This will download a JAR file that includes all the required dependencies. Upload this JAR file to your S3 bucket.</p><p>In MSK, you first need to create a plugin, and then a connector which is an instance of the plugin. In our case, MSK does not have a built-in MongoDB plugin and so we need to create a custom plugin. Fortunately for us, MSK can wrap the process of creating both plugin and connector into a single sequence.</p><p>Go to the MSK dashboard, select “Connectors” from the left side menu and then click on the “Create connector” button. You can see that MSK takes you to the “Custom plugin” screen to first create the new custom plugin. Select the “Create custom plugin” option, and then click on the “Browse S3” button to find your S3 bucket and select the JAR you just uploaded. Next, give your plugin a name and add a description, and then click on “Next” to start creating the connector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txLZYQSNLekpLhCW8OXxZg.png" /><figcaption>MSK — Create a Custom Plugin</figcaption></figure><p>To create a connector, start by choosing a name and add a description. Then choose you MSK cluster from the “Apache Kafka Cluster” list and the “None” authentication method as our plugin does not support the IAM authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*SCGx5Zkg2xJpkFEZgKnVvA.png" /><figcaption>MSK — Create a New Connector</figcaption></figure><p>Now we need to configure our connector. You can find detailed configuration information in the <a href="https://www.mongodb.com/docs/kafka-connector/current/source-connector/configuration-properties/#std-label-source-configuration-index">MongoDB connectors documentation site</a> and more information about MongoDB and change stream settings in the <a href="https://www.mongodb.com/docs/v4.2/introduction/">MongoDB documentation</a>.</p><p>We want to monitor the “intake” collection in the “pipeline” database and publish new documents to the pipeline.intake.inserts topic. We also want to poll the change stream every second (this might be high so consider reducing the polling frequency according to your application) and get the results in JSON format. The following configurations specify these choices:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6893c0ca518285b9dd6655670c0f674f/href">https://medium.com/media/6893c0ca518285b9dd6655670c0f674f/href</a></iframe><p><em>Note that for </em><em>&lt;YOUR_CONNECTOR_NAME&gt; you have to use the exact same name you chose for your connector. Also make sure to use your actual password instead of </em><em>&lt;YOUR_PASSWORD&gt; in the URI.</em></p><p>We leave the rest of the settings in the page on the defaults, but you can try and change them according to your needs. We need to give our connector access permissions using an AWS IAM role, so we choose the IAM execution role we created before and then click on the “Next” button.</p><p>The next section deals with security and the defaults here are good for us, so we touch nothing and simply click on the “Next” button again.</p><p>Now we need to choose where to send logging information. We previously created a CloudWatch log group and now is the time to use it. So, choose “Deliver to Amazon CloudWatch Logs” and then select the log group using the “Browse” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmw2xp34A9gaYTMXM7Eodg.png" /><figcaption>MSK — Sending Connector Logs to AWS CloudWatch</figcaption></figure><p>Click “Next” one more time to get to the “Review and create” screen. This screen shows you a summary of your choices and configurations and gives you the ability to edit things you missed. After making sure everything is as it should be, click the “Create connector” button to finish the process. Your new connector will now be created. This process can take a few minutes.</p><p>You can go to the CloudWatch console and select your log group to watch for progress. First you will see a new log stream titled “log_stream_created_by_aws_to_validate_log_delivery_subscriptions” appearing to indicate that the connector has permissions to log to CloudWatch. If you never see this, you need to go back and check the execution role settings to make sure you got them right.</p><p>After a couple of more minutes, you should see a log stream titled something like “medium-connector-33190fb9-ae60–471b-8a8f-412186b023ce-3”. If you click on this log stream you will be able to see all the output from your new connector as it initializes. If you see any errors during initialization, which may be in the form of Java exceptions and stack traces, you probably missed some of the steps above so go back and make sure you configured everything correctly. Note that you can NOT modify an existing connector so you would need to delete it once it reaches a “failed” state and create a new one instead.</p><p>If everything works and the connector was able to connect to DocumentDB and initialize the change stream, you will see messages like these appearing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGvjFr7V2VAQAkOg2lzJKw.png" /><figcaption>MSK COnnector Logs in CloudWatch</figcaption></figure><p>Your plugin is now ready for work!</p><p>We can run the CLI Kafka consumer as before and then use our MongoDB client to insert some documents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRhw9qKXV7OcYLW1nnL3WQ.png" /><figcaption>Inserting New Documents to DocumentDB using Robo 3T</figcaption></figure><p>The consumer will then show us that the connector picked up the documents and published them to our chosen topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPyQvQMctXw-XehjvrQ2tg.png" /><figcaption>Kafka CLI Consumer Showing the New Documents in the Topic</figcaption></figure><p>The connector is working as expected!</p><p>As for the Debezium connector, the documentation and download link can be found <a href="https://debezium.io/documentation/reference/2.0/connectors/mongodb.html">here</a>. Once downloaded, extract the archive, and upload the JAR to S3 so it can be used in MSK as with the Confluence connector.</p><p>The configurations are a bit different for the Debezium connector:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc2273737cb98711c5a4efc7dc7df096/href">https://medium.com/media/bc2273737cb98711c5a4efc7dc7df096/href</a></iframe><p>Unlike the Confluence connector, the Debezium one does not let you set a suffix for the topic name but rather uses the “mongodb.name” logical name as a prefix. Thus, we cannot use a topic like pipeline.intake.inserts. These configs will actually cause the connector to try and publish to a topic named inserts.pipeline.intake so make sure to name your topic correctly if you wish to use this connector. Otherwise testing should be done in the same way as before.</p><h3>Lambda</h3><p>This is where we start building our actual processing pipeline/graph. We need to create a new Lambda function and set an MSK based trigger for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUopohXUU_u6E4RktgwjzQ.png" /></figure><p>Start by going to the Lambda dashboard and click on the “Create function” button on the top right. Make sure to choose “Author from scratch” and fill in a name for your function. We are going to use Go code so select “Go 1.x” from the “Runtime” list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEigOQg6EXq4r3cm2cxcDw.png" /><figcaption>Lambda — Create a New Function</figcaption></figure><p>Next, expand the “Change default execution role” section, select “Create a new role from AWS policy templates” and give the role a name. This will create a new “service-role” to be used as the execution role for the Lambda function. Once created, we will need to tweak the permissions.</p><p>Expand the “Advanced settings” section and tick the “Enable VPC” box. We need our Lambda function to have access to the MSK cluster so the trigger can read from a topic and so we can publish to the next topic in line. Choose your VPC from the list, ALL the subnets where the MSK brokers are deployed and finally the security group as we defined previously:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*QxwXWYI2qni6tYjv14yVmw.png" /><figcaption>Lambda — Function VPC Settings</figcaption></figure><p>Create the function by clicking on “Create function”.</p><p>Once the function is created, click on it and then go to the “Configuration” tab and select “Permissions” from the left menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*_OShuk4yV8KVXtLVT385oQ.png" /><figcaption>Lambda — Execution Role</figcaption></figure><p>This shows you the execution role created for you, and you can browse the list of permissions it gives your Lambda function. Click on the role to open it in the IAM dashboard, remove the current policy and then create a new one that has the following permissions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f077f71cde5f64727a6746b3b901813/href">https://medium.com/media/4f077f71cde5f64727a6746b3b901813/href</a></iframe><p><em>Note to replace the </em><em>&lt;REGION&gt; with your selected region and </em><em>&lt;ACCOUNT_ID&gt; with your AWS account ID.</em></p><p>Go back to the Lambda function’s configurations, click on the “Monitor” tab and then click on “View logs in CloudWatch”. This should take you to the log group that was created for you Lambda functions. If, for some reason, this group was not automatically created, you will get an error message like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2p0jlb97CWIHIIAtSB9mg.png" /><figcaption>CloudWatch — Log Group Missing Error</figcaption></figure><p>You will need to manually create the log group. To do this, note the group’s required name in the error message, which in this case is /aws/lambda/medium-pipline-router. Now click on “Log groups” from the navigation bar under the error message or by expanding the left sidebar and clicking on “Log groups” there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnorFGlvn7Zc9o_s92kB5Q.png" /><figcaption>CloudWatch — Showing Log Groups</figcaption></figure><p>Now click on “Create log group”, fill in the required name and then click on the “Create” button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLuqOgCAWu87Szkcd6igzg.png" /><figcaption>CloudEWatch — Creating a New Log Group</figcaption></figure><h3>VPC Revisited</h3><p>Another thing we need to take care of at this point is making sure we have network connectivity to some required AWS services for our trigger. Depending on your VPC of choice, you may not have connectivity to the STS, Lambda and/or Secrets Manager services. We can fix this by adding VPC endpoints for each of these to our VPC. If you get an error message about this when setting up the MSK trigger for the Lambda function, follow these instructions:</p><p>Go to the VPC dashboard and select “Endpoints” from the left side menu. Then click on “Create Endpoint” on the top right. Fill in a descriptive name for your endpoint and then search and select the com.amazonaws.&lt;REGION&gt;.sts service from the “Services” list. Remember to replace &lt;REGION&gt;with your region.</p><p>Now select your VPC from the VPC list, select ALL the subnets where MSK brokers are deployed, and for each, Select the subnet ID from the combobox. Select the “IPv4” IP address type and then select the security group we set up for our VPC:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*PJKfui4OZVIq2bTZmmfLpg.png" /><figcaption>Creating VPC Endpoints</figcaption></figure><p>Leave the rest as is and click on “Create Endpoint” at the bottom. Repeat the process for the lambda and secretsmanager services as well.</p><h3>Lambda Router</h3><p>Now that you have a Lambda function, we can write code for it and configure a trigger. Here is an example Go code that will take care of everything our Lambda’s will do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a3cde9f232ba9bec9f353c521ba365/href">https://medium.com/media/55a3cde9f232ba9bec9f353c521ba365/href</a></iframe><p>As can be seen, this code encapsulates the Lambda Go SDK functionality required to run the proper handler function when the Lambda function is activated. The handlers specifically expect a Kafka data structure (this is being deserialized by the AWS Lambda SDK for us) and we then take the JSON items contained within and convert to our own Go data structure. Finally, if specified using the KAFKATOPICand KAFKABROKERS environment variables, we also publish to a Kafka topic.</p><p>This code contains handlers for both a router and a worker, and chooses the correct one based on the NODE_ROLEenvironment variable.</p><p>Please note that while the Confluence MSK connector we used publishes the data to Kafka in JSON format, the Debezium connector uses the Rust <a href="https://serde.rs/">Serde</a> serialization instead. The resulting structure looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b505e6e7fac959315fa7edacbac8433a/href">https://medium.com/media/b505e6e7fac959315fa7edacbac8433a/href</a></iframe><p>This means we will need to replace the JSON deserialization code with something like <a href="https://github.com/Xuanwo/serde-go">serde-go</a>, which we will not cover in this article.</p><p>In order to build you code for Lambda, you need to specify some Go build parameters like this:</p><pre>GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o medium-lambda-node</pre><p>and then zip the resulting binary. If you which to easily reuse your code, it is recommended to upload the zip file to S3 at this point.</p><p>Now go to your Lambda function’s settings and select the “Code” tab. Click on “Upload from”, select “.zip file”, click “Upload” in the dialog that popped up and select your zip file. If you uploaded to S3, select “Amazon S3 location” instead then paste the S3 link URL to your zip file.</p><p>Next, under the “Runtime settings” section, click the “Edit” button and enter your compiled binary’s filename in the “Handler” box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LEgjM71MO3CKKf2Jk8AGQ.png" /><figcaption>Lambda — Uploading Code to the function</figcaption></figure><p>Click on “Save” and give your lambda a few minutes to load the new code.</p><h3>Lambda MSK Trigger</h3><p>Next, we will set up the MSK trigger. This trigger will connect to the MSK cluster, listen on our initial topic, and then trigger the Lambda on new incoming messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mw4ZSfLF3R_ErD9nVoaaxg.png" /></figure><p>You can either click on “+ Add Trigger” from the “Function overview” section, or go to the “Configuration” tab, select the “Triggers” section on the left and then click on “Add trigger” on the right.</p><p>In the new dialog, select the “MSK” trigger type. This will open the trigger’s settings. Select the MSK cluster, set the desired batch size, your “Batch Window” (the max polling time in seconds for the topic) and then fill in the topic name.</p><p>By default, the trigger will handle new incoming messages. If you want it to process ALL the messages in the topic, select “Trim horizon” from the “Starting position” box. This is the desired action for us as one of our requirements was that we do not want to lose messages so we can dynamically plug in components into our pipeline to start handling previously unknown message types.</p><p>In this article we are not taking care of Authentication. However, there is a fine point to note here. We created the MSK cluster with the default Authentication settings, which means that both “Unauthenticated” and “IAM role-based authentication” are enabled. The trigger will default to using “IAM role-based authentication” for which we previous added the “kafka-cluster” actions to our Lambda execution role’s policy. If these permissions are missing, you will get a “SASL authentication failed” error message from the trigger. We did NOT enable SASL authentication in our MSK cluster, so why are we getting this error? Well, this is because behind the scenes, AWS implements the “IAM role-based authentication” mechanism using SASL.</p><p>As we are not tackling authentication here, just go ahead and click the “Add” button to create the new trigger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*c3lq0oIx_KRPbVvRbLLsFw.png" /><figcaption>Lambda — Creating an MSK Trigger</figcaption></figure><p>Deploying the trigger can take a few minutes, and once deployed we can configure and test our router.</p><p>Under the “Configuration” section, select “Environment variables” on the left and then click the “Edit” button and add the NODE_ROLE variable with ROUTER as the value.</p><p>If we now add this new document to our DocumentDB, it will be published to the pipeline.intake.inserts topic by the MSK connector as we saw before. The trigger will then pick it up and trigger the Lambda. Our sample code will output the information read in the message to CloudWatch so if you go to the log group we created above, you will see a new log entry appearing and within something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TieO-8e_B5UU9pjgXnlf9w.png" /><figcaption>Lambda — Successful RunCloudWatch Output</figcaption></figure><p>In order to finalize the router’s work, we want to demonstrate that it can actually route messages to different topics based on their type. The Lambda code will use the color field as a type for the message and will route the message to a Kafka topic named pipeline.type.&lt;COLOR&gt;. So, create two new topics: pipeline.type.blue and pipeline.type.green.</p><p>Next, we should tell our Lambda where MSK is so it can actually publish the messages to the various topics so go back to the environment variables and add a variable called KAFKABROKERS and set its value to be a comma-separated list of the brokers in you MSK cluster. For example:</p><pre>b-1.medium-msk.i78wus.c3.kafka.eu-west-2.amazonaws.com:9094,b-2.medium-msk.i78wus.c3.kafka.eu-west-2.amazonaws.com:9094,b-3.medium-msk.i78wus.c3.kafka.eu-west-2.amazonaws.com:9094</pre><p>You may note that we are using port 9094 here as our nodes are connecting to MSK securely using TLS. This will tell our example code to publish the data to the proper queue in MSK in addition to printing to the log.</p><p>Now, if we add a new document with the same message as before, we will be able to use the console consumer as we did before to listen on the pipeline.type.blue topic and we will see the message appear under that topic with a few seconds from creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8PJ3OGbkASpzTkAyTlhl_Q.png" /><figcaption>Kafka CLI Consumer</figcaption></figure><p>Our router picked up the new document, determined that the message type is blue and published the data to the pipeline.type.blue queue as desired.</p><h3>Lambda Processor</h3><p>The final piece of the puzzle is the processor node, which is just another Lambda function that uses the same code as before. Go ahead and replicate the process we used for the router Lambda to create a new Lambda with an MSK trigger listening on the pipeline.type.blue topic. This time, set the NODE_ROLE environment variable to WORKER so the worker handler function is used.</p><p>Finally, we can test the full E2E mechanism by adding a new document as before, and we will see a new log entry in CloudWatch for the new Lambda function with the content of the document.</p><p>If we create another document with green as the color, we will see the new message appearing under the pipeline.type.green topic, but no Lambda function will be activated as we do not have a trigger listening on this topic. The messages will accumulate in this topic until we create a new Lambda function capable of processing “green” messages and add a trigger for it that listens on the pipeline.type.green topic.</p><p>Our sample pipeline is now complete!</p><h3>Conclusion</h3><p>In this article we demonstrated how to configure various AWS components (VPC, EC2, DocumentDB, S3, IAM, CloudWatch, MSK and Lambda) and tie them together to create an E2E processing pipeline that triggers automatically when new documents are inserted into the DB. For this article, we chose the smallest available instance sizes for the various service so our EC2 instance and our DocumentDB are running for free while our Lambda functions are only billed when running (i.e., when triggered by a new document published into the proper topic until they finish processing it).</p><p>Our pipeline can be dynamically configured to accommodate any processing structure by creating Kafka topics as edges in our graph and Lambda functions as nodes with triggers for the specific Kafka topics. Restructuring can be done while the system is running without losing any data.</p><p>We also covered various CLI, shell and GUI tools for working with MongoDB and Kafka as well as remotely connecting to our resources via SSH port forwarding.</p><p>Hopefully, this document provides a good starting point for anyone interested in building fully managed cloud-based processing pipelines using AWS services.</p><h3>Thanks</h3><p>I wish to thank <a href="https://medium.com/@juliarvalenti">Julia Valenti</a> for her amazing assistance in reviewing and editing this article ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f320f855a09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cisco-fpie/taming-of-the-queue-f320f855a09">Taming of the Queue</a> was originally published in <a href="https://medium.com/cisco-fpie">cisco-fpie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons Learned from Using AWS Cloud Directory]]></title>
            <link>https://medium.com/cisco-fpie/lessons-learned-from-using-aws-cloud-directory-783041239478?source=rss-e300705c6cf2------2</link>
            <guid isPermaLink="false">https://medium.com/p/783041239478</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[directory]]></category>
            <dc:creator><![CDATA[Tal Maoz]]></dc:creator>
            <pubDate>Mon, 13 Dec 2021 15:17:39 GMT</pubDate>
            <atom:updated>2021-12-13T15:17:39.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avV1UQJjq5kgz9hIaNjyKA.jpeg" /></figure><p>There are various ways of representing and managing organizational hierarchies and users, and several common tools used to do so. Some of the popular solutions include Microsoft’s <a href="https://en.wikipedia.org/wiki/Active_Directory">Active Directory</a> (AD) and <a href="https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol">LDAP</a> (Lightweight Directory Access Protocol) based services such as <a href="https://www.openldap.org/">Open-LDAP</a>. However, setting up and managing any of these can be complicated, and requires advanced DevOps skills to make deployments secure, highly available and backed up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*nga5M0w9XZGfp5Mv" /><figcaption>AWS Directory Service</figcaption></figure><p>Cloud platforms such as AWS offer <a href="https://docs.aws.amazon.com/directory-service/index.html">managed solutions</a> that take most of the headache off the process by managing all the DevOps aspects mentioned above. AWS offers several types of directories including a managed <a href="https://en.wikipedia.org/wiki/Active_Directory">Microsoft AD</a> service, A Linux <a href="https://en.wikipedia.org/wiki/Samba_(software)">SAMBA</a>-based (an open-source implementation of the SMB — Server Message Block — protocol) simple directory service and the <a href="https://docs.aws.amazon.com/cognito/index.html">Cognito </a>user pool — a service used to define user pools that can be used to authenticate users into web or other applications. Alongside these, Amazon offers <a href="https://docs.aws.amazon.com/clouddirectory/index.html">Cloud Directory</a>, which is a simplified multi-tenant directory-based store.</p><p>This post talks about what Amazon Cloud Directory is and what its main concepts are with GUI, <a href="https://aws.amazon.com/cli/">CLI</a> and <a href="https://golang.org/">Go</a> code usage examples. <strong><em>It is important to note, that despite the fact the Cloud Directory is easier to understand and use than AD or LDAP, it hasn’t gained popularity and there seems to be no support community around it</em></strong>. The only helpful resource outside AWS’s documentation is the <a href="https://forums.aws.amazon.com/forum.jspa?forumID=180">AWS Directory Services forum</a> that mainly deals with the other solutions and hardly responds to questions regarding Cloud Directory.</p><p>While researching Cloud Directory, it became apparent that the provided documentation is lacking, and more often than not, the only way to understand an object/request format was to dive into the <a href="https://github.com/aws/aws-sdk-go/tree/main/service/clouddirectory">AWS SDK source code</a>.</p><h3>What is AWS Cloud Directory?</h3><p>To quote AWS’s <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/what_is_cloud_directory.html">documentation</a>: “<em>Amazon Cloud Directory is a highly available multi-tenant directory-based store in AWS. These directories scale automatically to hundreds of millions of objects as needed for applications.</em>”</p><p>Cloud Directory is a directory store built on a simple graph structure with a customizable schema. One can create objects to which attributes can be assigned, and can define connections/links between the objects. The graph structure can be traversed by following the links (e.g. listing children or parents) to find requested objects. In addition, indices can be used to quickly locate objects by attributes.</p><p>Cloud Directories are subject to various limitations as described <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/limits.html">here</a>.</p><p><em>Note, that although the classic usage of a directory would be holding organizational information, which is the example we use throughout this post, it can be used to hold any type of hierarchic or graph-based information by defining the proper schemas.</em></p><h3>What is a Schema?</h3><p>A schema is a JSON file that includes <em>Facets</em> and <em>Typed Link Facets</em>. A <em>Facet</em> defines the set of attributes that make up a specific type of object (a node in the directory graph), and includes data types and rules such as min/max (length for string fields or value for number fields, etc.), whether or not the attribute is required or mutable, etc. <em>Typed Link Facets</em> are essentially the same for the links between objects. The full format specifications can be found <a href="https://docs.aws.amazon.com/clouddirectory/latest/developerguide/schemas_jsonformat.html">here</a>. A new object must conform to at least one of the facets defined in the applied schemas.</p><p>Multiple schemas can be applied to the same Cloud Directory instance. Schemas are versioned and can be upgraded to newer versions. Schemas start in <em>development</em> mode and that is the only mode in which they can be modified. In order to apply a schema to a directory, it first has to be <em>published</em> with a version, at which point it becomes immutable. When applied to a directory, the schema is copied into the directory. This copy has its own ARN (AWS Resource Name) and is considered an <em>Applied</em> schema. Even though an applied schema is said to be immutable, you can still add new facets and non-required attributes by upgrading to a new version of the schema. Once a schema is applied, it <strong>cannot</strong> be removed from the directory.</p><h4>Creating a New Schema</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAZ58kbG7hsElVwH-27uSA.png" /><figcaption>AWS Cloud Directory Schemas List</figcaption></figure><p>The easiest way to create a new schema is from the AWS console. Just go into the “Schemas” section of the Cloud Directory console and click on “Upload new schema” on the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*Vi_OMe3gChiJ36RlgvpxIg.png" /><figcaption>Upload New Cloud Directory Schema</figcaption></figure><p>Fill in the name of the new schema and select the JSON file containing your schema data.</p><p>Finally, click on the “Upload” button.</p><p>Here is an example of a full schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/648cb444eb26c491db64fe26c4ab45db/href">https://medium.com/media/648cb444eb26c491db64fe26c4ab45db/href</a></iframe><p>To Publish a schema, choose it from the schema list and select “Publish” from the “Actions” menu on the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*0hvWrs1yYjGf1xM3qHIPlg.png" /><figcaption>Publish Schema</figcaption></figure><p>Fill in the version of your schema and click on “Publish”.</p><p>The AWS CLI can also be used to create and publish a new schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c44b1c2242a721b275be0fc4aef94ac/href">https://medium.com/media/3c44b1c2242a721b275be0fc4aef94ac/href</a></iframe><p>You get back the ARN of the new schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9acfd002e2b173ca8c5a26d2699d0a20/href">https://medium.com/media/9acfd002e2b173ca8c5a26d2699d0a20/href</a></iframe><p>Now you can put the schema JSON data into the new schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1354bd2367a2a368fbdfc2986bb0d05/href">https://medium.com/media/b1354bd2367a2a368fbdfc2986bb0d05/href</a></iframe><p>Again, you get back the ARN of the schema.</p><p>Finally, you can publish your schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d87034c23170b7f5c82fe9fdd3c87c6c/href">https://medium.com/media/d87034c23170b7f5c82fe9fdd3c87c6c/href</a></iframe><p>And you get back the ARN for the published schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f75152378c76edf2a753ddb78ae2053/href">https://medium.com/media/0f75152378c76edf2a753ddb78ae2053/href</a></iframe><p>As can be seen, the only way to specify the schema data using the CLI is directly on the command-line, which can be very limiting.</p><p>Now you have two schemas in your schema list, the <em>development</em> schema, and the <em>published</em> schema.</p><h3>Objects</h3><p>Objects are nodes in the directory graph. They have a type, which is defined by the facets applied to them, and an Id. Objects can be linked to other objects by using <em>Link Facets</em>, which are the edges within the graph.</p><p><strong>It is very important to note, that creating objects in the directory doesn’t automatically attach them to the directory graph!</strong> There’s an optional field in the create request to specify the parent object, but it is very easy to miss. This means that the only initial way to find a newly created object is by using its Id. If you lose this Id, your object will become a space-wasting zombie. Remember that your directory has limited space, so space management is critical! The only way to find a zombie object is to go through the AWS trace logs in <a href="https://aws.amazon.com/cloudtrail/">CloudTrail</a> and find the log entry for the create operation with the new object’s Id.</p><p>I recommend planning your directory structure in advance so that when you create a new object, you already know where in the graph you want to attach it to and attach it there while or immediately after creating it. Once an object is attached, you can also find it using a path selector from the graph’s root to the object.</p><p><em>Another note to remember is that the root of the directory graph is, in itself, an object in the graph</em>.</p><h3>Indices</h3><p>Indices allow you to search for objects within your directory. Unlike database indices, Cloud Directory indices require explicit association of objects. When you create a new index, it is empty. You need to manually attach objects, one by one, to the index to be able to search for them. Moreover, an index is just another object in your directory so, like every other object, you must either remember its Id or attach it to your graph.</p><p>I recommend creating an “indices” object (branch) under the graph’s root and hanging all the indices under this branch. This way you can easily get to your index by following the path to it from the root:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26bbb449500f63f563a3db2259bf52f7/href">https://medium.com/media/26bbb449500f63f563a3db2259bf52f7/href</a></iframe><p>For which you get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da3ce76ca8adc0b1b2ade5415abb1e23/href">https://medium.com/media/da3ce76ca8adc0b1b2ade5415abb1e23/href</a></iframe><p>While an index is an object in the directory, it is a special one so listing items under an index is done using the “list-index” command instead of the “list-object-children” command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd384111adf7c632f513c715952b2d46/href">https://medium.com/media/bd384111adf7c632f513c715952b2d46/href</a></iframe><p>And you get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e3d43842c797c014b6c93a61797029/href">https://medium.com/media/e6e3d43842c797c014b6c93a61797029/href</a></iframe><p>In this output we see just a single object that has been attached to the index. For each object we get the list of set attributes. Each attribute has a “Key” that contains the ARN of the schema in which the attribute is defined, the facet within that schema and the attribute’s name. We also get a “Value” for the attribute with the attribute’s type and value.</p><h3>Creating a Cloud Directory</h3><p>The simplest way to deploy a Cloud Directory instance is to log into the AWS console and navigate to the Directory Service console. Then, select the “Directories” link under the “Cloud Directory” section from the left sidebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*U0knqfzDEut3EZJNl15BeA.png" /><figcaption>AWS Cloud Directory Console</figcaption></figure><p>Now, click the “Set up Cloud Directory” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*-3onQXw11SNnmIpsZ6asyw.png" /><figcaption>Create Cloud Directory</figcaption></figure><p>First, choose a name for the new directory, and then the type of schema to start with.</p><p>The <em>Managed</em> schema is a simple schema with a <em>dynamic</em> facet and a<em> dynamicTypedLinkFacet</em>, which means you can put whatever you want into your new objects. While this allows you to quickly start building, it is limited in the sense that the directory will not be able to type check your objects or index them.</p><p>Choosing the <em>Sample</em> schema option will allow you to apply one of three preexisting schemas that are often used to build organizational hierarchies: “device”, “organization” and “user”.<br> Finally, <em>Custom</em>, let’s you apply your own custom schema that has already been uploaded and published.</p><p>When you click the ‘Next” button, you will get a review screen showing a summary of the configuration for the new Cloud Directory instance, as well as a notification regarding pricing. With Cloud Directory you pay as you go, starting with a free tier service and moving into paying schemes over time and as you grow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*0SoKHuZByRc_w3Iaw_0SDw.png" /><figcaption>New Cloud Directory Review</figcaption></figure><p>Finally, you can click the “Create” button to create your new Cloud Directory instance.</p><p>The AWS console allows you to also create a directory with an existing schema directly from the Schemas section. You simply select your schema and select “Create directory from schema” form the “Actions” menu on the top right. You get the same screen as before, but this time “Custom schema” is selected, and your new schema is selected from the schema list. Fill any other required details and click on “Next”. If your schema was not yet published, you will now be asked to fill in the Major and Minor versions for your schema before giving you the review screen upon clicking “Next”, where you can now also preview the schema. Finally, click on “Create” to create your directory.</p><p>You can create a new Cloud Directory from the AWS CLI using the <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/clouddirectory/create-directory.html">create-directory</a> command.</p><p>Please note, that once you apply a schema to a directory, either by specifying the published schema to use while creating the directory or by applying a published schema to an existing directory, Cloud Directory will copy your schema into the directory and will give you back an ARN pointing to that copy, which is now an <em>Applied </em>Schema.</p><h3>Code Example</h3><p>Here is a Go code example that shows how to create and publish a schema, and how to create a directory using the published schema, thereby also creating an applied schema. Next, we create an “indices” branch under the root of the directory and then create a new index over the “name” attribute of the “organization” facet and hang it under that branch. Finally, we create a new organization object, hang it under the root and attach it to the index.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0644780ca4958b346e7274d268dc7c/href">https://medium.com/media/5b0644780ca4958b346e7274d268dc7c/href</a></iframe><h3>Transactions</h3><p>Cloud Directory doesn’t support sessions or transactions in the traditional sense. Since each call to Cloud Directory is atomic, you have the option to batch multiple operations into a single call, thereby achieving the effect of a session or a transaction.</p><p>To do this you can use the <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/clouddirectory/batch-read.html">batch-read</a> and <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/clouddirectory/batch-write.html">batch-write</a> commands using the CLI, or the <a href="https://github.com/aws/aws-sdk-go/blob/main/service/clouddirectory/api.go#L846">BatchRead</a> and <a href="https://github.com/aws/aws-sdk-go/blob/main/service/clouddirectory/api.go#L959">BatchWrite</a> Go functions accordingly.</p><h3>Summary</h3><p>AWS Cloud Directory is a simple graph-based directory that allows you to store typed objects, traverse the graph by listing the children and parents of objects, create indices to index objects and then search for the objects using those indices.</p><p>It is conceptually simple to use but as there is little to no community support, it can be hard to understand how everything comes together.</p><p>I hope this post helps you, future Cloud Directory users, understand the basic concepts and build your applications on top of Cloud Directory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=783041239478" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cisco-fpie/lessons-learned-from-using-aws-cloud-directory-783041239478">Lessons Learned from Using AWS Cloud Directory</a> was originally published in <a href="https://medium.com/cisco-fpie">cisco-fpie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Reality — Virtual Re-Creation and Monitoring of Real-World Environments]]></title>
            <link>https://medium.com/cisco-fpie/exploring-reality-virtual-re-creation-and-monitoring-of-real-world-environments-756383a7987a?source=rss-e300705c6cf2------2</link>
            <guid isPermaLink="false">https://medium.com/p/756383a7987a</guid>
            <category><![CDATA[vr]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[point-cloud]]></category>
            <category><![CDATA[motion-capture]]></category>
            <category><![CDATA[project-tango]]></category>
            <dc:creator><![CDATA[Tal Maoz]]></dc:creator>
            <pubDate>Thu, 15 Apr 2021 15:11:58 GMT</pubDate>
            <atom:updated>2021-04-15T15:11:58.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Reality — Virtual Re-Creation and Monitoring of Real-World Environments</h3><p>In 2016, I worked on a research project called “Exploring Reality” or ExR for short. The idea was to provide the ability to do 360-degree security monitoring of public areas without compromising people’s privacy. For example, imagine a playground where children are playing and people are walking around. By placing cameras that continuously monitor the area, we basically violate those people’s privacy. Anyone with access to the security camera recordings can see everything each one of those children and people are doing.</p><p>The question is, can we find a way to let security personnel identify suspicious activity while maintaining people’s privacy?</p><p>The idea I investigated was built of the following three steps:</p><ol><li>Create a virtual replica of the area that can be viewed with a VR headset</li><li>Identify and record the movement of people within the area from the security cameras</li><li>Map the movement of the various people onto virtual avatars that would reenact those movements within the virtual area, either in real-time or using pre-recorded historic data</li></ol><p>Scroll to the bottom for the TL;DR!</p><p><strong>Virtually Mapping an Area</strong></p><p>The first step was to map out a physical area and creating a virtual replica of it. For simplicity, I chose my office as my physical area and set out to map it.</p><p>At the time, AR technology was taking its first steps towards commercialization. Google had just launched the “<a href="https://en.wikipedia.org/wiki/Tango_(platform)">Project Tango</a>” research tablet that was aimed at giving developers and researchers a single platform on which they could explore AR technologies and experiment. Later, the lessons learned from Project Tango turned into Google’s <a href="https://developers.google.com/ar">ARCore</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4W-VO8Z6W8TW3rwj7hQ0BA.jpeg" /><figcaption>Google’s Project Tango Tablet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*6wNDU7y44mEryfwjPTXABA.png" /></figure><p>I used a pre-existing tool called “<a href="https://androidappsapk.co/detail-phi-3d-for-tango-beta/">Phi.3D for Tango</a>” created by <a href="https://www.dotproduct3d.com/">DotProduct LLC</a>, later replaced by “<a href="https://play.google.com/store/apps/details?id=de.dotproduct.dot3dtango&amp;hl=en&amp;gl=US">Dot3D for Tango</a>”. The Tango version was a free Beta. It started out nicely, but I quickly found that there was a size limit for the mapping so I couldn’t map the entire office in one go but rather had to map various sections separately and then figure out how to stitch them together. The result of the scanning was a bunch of partially overlapping point clouds.</p><p>In order to stitch the separate point clouds together, I turned to <a href="https://pointclouds.org/">PCL (Point Cloud Library)</a>. I first used the <a href="https://www.danielgm.net/cc/">CloudCompare</a> open-source software to import the scan results created by Phi.3D and convert them into an ASCII cloud format that I taught PCL to read. Using PCL, I was able to write some code that unified all the individual point clouds into a single one and then construct a mesh from the individual vertices. This process took a very long time (several hours) and produced a single mesh that had around 11 million vertices and 20 million faces. The mesh was too heavy to view even on my laptop so certainly not suitable for use on a mobile phone.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fk57sxhUIh9w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dk57sxhUIh9w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fk57sxhUIh9w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/59a578b5f585946467b4cad03c676a38/href">https://medium.com/media/59a578b5f585946467b4cad03c676a38/href</a></iframe><p>I then proceeded to write my own C++ code that employed voxel subsampling on each of the individual point clouds, then used a <a href="https://en.wikipedia.org/wiki/Greedy_triangulation">Greedy Triangulation</a> algorithm within PCL to build a mesh from each point cloud, and finally combine them into a single model. This process took around 10 minutes to run and I ended up with a mesh that had around 5 million faces, looked virtually the same and worked nicely within the Unity 3D engine.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqP90ppTlBJw&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqP90ppTlBJw&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4401c6d77f5aa40e31f8e8558a370a48/href">https://medium.com/media/4401c6d77f5aa40e31f8e8558a370a48/href</a></iframe><p>So, I now had a usable virtual representation of a real-world location, my office!</p><p><strong>Pose Estimation and Skeletal Movement Capture</strong></p><p>The second step was to be able to capture the movements of a real person. For this I chose to use a <a href="https://en.wikipedia.org/wiki/PrimeSense">PrimeSense</a> depth camera. PrimeSense was an Israeli company later acquired by Apple. They created the first generation of the Xbox Kinect camera. I used the PrimeSense PSDK 5.0 (PSMP05000) Camera in conjunction with the <a href="https://structure.io/openni">PrimeSense OpenNI 2 SDK</a> and the <a href="http://www.openni.org/files/nite/">PrimeSense NITE 2 Middleware</a>, which give you very convenient utility functions such as pose estimation and skeletal structure detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*LLl2ZvN90YuMgn8gcXwpbQ.jpeg" /><figcaption>PrimeSense Depth Camera</figcaption></figure><p>Putting these together I was able to quickly write some C++ code that uses the camera to identify the skeletal structure of the user standing in front of the camera. I then developed a simple Node.JS service backed by a MariaDB database to store the positions and orientations of all the detected joints in each time point. The service allows getting real-time data from the camera reader or do queries on the database to replay data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoK6FDR31RHE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoK6FDR31RHE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoK6FDR31RHE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d18f103b317a7f10425cda20b4b5be/href">https://medium.com/media/89d18f103b317a7f10425cda20b4b5be/href</a></iframe><p><strong>Mapping Captures Movements onto an Avatar</strong></p><p>The final step was to map the captured movements to a virtual avatar within the virtual environment. For this I used the Unity 3D engine.</p><p>I started by importing the mapping I captured of my office into Unity and added a human avatar into the scene. Next, I wrote some C# code that allowed my Unity application to connect to the collector Node.JS service and either can live data or make queries for past data replay.</p><p>As I wanted to be able to place the viewer within the scene and be able to walk around while watching the event unfold, I integrated with Google’s cardboard SDK so I can build the app to run on a mobile phone and create a real VR experience. This also gave me the ability to map phone movements to the Unity camera, thereby giving the users the feeling they are moving within the scene.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRCuNqkC6RVg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRCuNqkC6RVg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRCuNqkC6RVg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6f28f47dbe1dbf75178d3e7d9f19d3d/href">https://medium.com/media/b6f28f47dbe1dbf75178d3e7d9f19d3d/href</a></iframe><p>You may notice from the images that the capture was actually a mirror image of the real movement, but I opted to not try and fix this as my goal was to prove the viability of the technology and had a limited timeframe in which to do it.</p><p>The entire process took me almost 3 months to complete.</p><p><strong>What it All Amounts To</strong></p><p>This project demonstrated that we could monitor an area and capture all the movements within. We could then provide security personnel the ability to walk around the area in VR and view avatars re-enacting the movement of people that were present in the real area. When suspicious activity is detected, we would allow the security person to view the original footage of the specific individual whose movements were represented by the selected avatar. Thus, they are able to identify the suspect while maintaining the privacy of unrelated people in the surrounding environment.</p><p><strong>TL;DR</strong></p><ul><li>I used a tablet with point-cloud mapping capabilities to map my office</li><li>Applying simplification and cleanup algorithms to the point-cloud segments allowed me to easily patch them into a single mesh</li><li>By using a depth-camera I was able to map the skeletal structure of a person in real-time and store the data into a DB-backed backend service</li><li>Importing the office model into Unity proved easy and effortless and allowed me to easily build an experience on top of the model</li><li>Mapping the captured skeletal movements onto a virtual avatar allowed me to replicate a users presence in the office while maintaining privacy</li><li>Finally, integrating with the Unity Goolge-Cardboard plugin, I was able to put the user into the virtual replication and let them move around and view the avatar replicating the human presence captured from every angle</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=756383a7987a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cisco-fpie/exploring-reality-virtual-re-creation-and-monitoring-of-real-world-environments-756383a7987a">Exploring Reality — Virtual Re-Creation and Monitoring of Real-World Environments</a> was originally published in <a href="https://medium.com/cisco-fpie">cisco-fpie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Built a Domain-Specific Natural Language Semantic Parser]]></title>
            <link>https://medium.com/cisco-fpie/how-we-built-a-domain-specific-natural-language-semantic-parser-f16548a91b05?source=rss-e300705c6cf2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f16548a91b05</guid>
            <category><![CDATA[semantic-parsing]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Tal Maoz]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 00:25:55 GMT</pubDate>
            <atom:updated>2021-03-19T00:25:55.999Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How We Built a Networking-Specific Natural Language Semantic Parser</strong></h3><p>As a member of Cisco’s Future Product Innovation team, I recently led a technical investigation focused on using natural language to configure a network management system (NMS). We wanted to help non-technical personnel carry out various types of network configurations in an intuitive and human-friendly way, using natural language (NL) in combination with speech-to-text. Our team consisted of a Cisco Fellow engineer, a senior software engineer and me, serving as the technical lead of the project. Although we had no prior knowledge or experience with natural language processing (NLP), we were highly motivated.</p><p>We focused on three main sub-domains within networking, and defined the following usage examples:</p><p><strong>Filter sub-domain:</strong></p><ul><li>“Please allow all voip to bldg. 10”</li><li>“All voip to bldg 10 should be blocked”</li><li>“Permit udp traffic from 10.0.8.1 to 171.21.58.16/12”</li><li>“Do not allow traffic from Battle.net”</li><li>“All FTP traffic to wireless should be denied”</li></ul><p><strong>QoS sub-domain:</strong></p><ul><li>“Please apply highest priority to Diana’s ip-camera packets going to campuses”</li><li>“Diana’s ip-camera packets outbound to campuses should be sent at highest priority”</li><li>“Make all packets of type iso-tp4, marked with de and going towards campuses, oam”</li><li>“John’s blue ios devices wap secure connectionless session service packets that are flagged with ef and from cellular phone should be sent at lowest latency”</li></ul><p><strong>Setpath sub-domain:</strong></p><ul><li>“All of Dave’s mail going to salesforce.com should go via security broker Lima”</li><li>“Route all traffic to company.com through the DMZ interface”</li><li>“All TCP packets on port 8888 should go through building A26”</li></ul><p>Since no existing systems understand or carry out such requests, we knew we had to devise a new approach to make this happen. After inspecting the chosen sub-domain and assessing how real network technicians would configure a system to carry out each one of the example requests, we realized that for each sub-domain we could define a data structure breaking down the required data items for that sub-domain as fields, that we would call a “structured network request” or “SNR”. We would then need to find a way to parse the request and fill in the fields so that we could build an actual NMS command to configure the system. We started thinking about how a person would go about parsing and understanding such requests. After a bit of thinking, it became clear that language knowledge alone was not enough, and that we would need to add network semantics into the parsing process.</p><p><strong>Thus was born the “semantic parser,” comprised of the following six parts:</strong></p><ol><li>A deep neural network (DNN) based sub-domain classifier</li><li>A natural language processing (NLP) engine for part of speech (POS) tagging</li><li>Lexical lists (LLs)</li><li>A custom trained, DNN-based named entity recognizer (NER)</li><li>An adaptive learning knowledge base (ALKB)</li><li>A scoring metric</li></ol><p>Figure 1 shows what our semantic parsing flow looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2JmFoo5OOQB5JeDXfFcBg.png" /><figcaption>Figure 1: Semantic Parser Architecture</figcaption></figure><p>We started by passing the request through an NLP engine, which uses a pre-trained, language-specific model to analyze a given sentence, tag the words within according to their part of speech (POS), and then build a graph that shows the dependencies between the words according to their POS. The NLP engine can also identify and tag words as people, places, numbers, etc. For example, the parsing results for “All of Dave’s mail going to salesforce.com should go via security broker Lima,” can be seen in figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QdHcxz4-3HxEOUPlu7QaA.png" /><figcaption>Figure 2: NLP Engine Analysis</figcaption></figure><p>In order to add network semantics, we built what we call “lexical lists”. An LL is a collection of key words, regular expressions, code snippets and application rules that combined, can identify and map words into SNR fields. Each LL targets a specific field. We built our LLs to be hierarchic so there would be inheritance of common sections between LLs. We soon found, however, that standard POSIX regular expressions were not enough to capture the complexity of a language. So we enhanced the regular expressions with the ability to run validation rules on capture groups, replace the content of capture groups according to predefined rules and checks, and even run snippets of code on capture groups to take advantage of all the data provided by the NLP engine and run more complicated checks and substitutions.</p><p>Validation rules are used to tell the LL engine how to evaluate the LL and allow the application of Boolean conditions on the results. By default, all the regular expressions and keyword lists are used, but are overridden by validation rules.</p><p>The LLs worked, but were not very robust since they required us to think of every possible way someone might phrase a request — which wasn’t feasible. However, they were an advantage for special and edge cases, where we found we needed to be able to define precedence rules for parsing and mappings. So we turned to DL to make our engine more robust. We set out to train our own named entity recognizer (NER), based on a deep neural network (DNN), to map a request into SNR fields.</p><p>The first problem we faced was getting training data. As any data scientist will tell you, getting good, tagged data is the most important and difficult part of building a deep learning (DL) model. Since no one has ever tried using NL for networking requests, we had no pre-existing data to use. As our entire team consisted of only three people, it would have taken us a very long time to create and tag enough data to be able to do decent training. We’re talking about millions of input samples! We could have tried to recruit other people to help, but again, we were looking for a solution to prove the feasibility of our system within a short timeframe.</p><p>Eventually, we decided to build our own data generator. We studied the typical structure of network requests in the chosen sub-domains and extracted several thousands of templates that define all possible request types. Then we created lists of words for each field in the templates, while also using data from our LLs’ key word lists. We were able to synthetically produce more than <em>15 quadrillion</em> — that’s <em>15*10¹⁵</em> or <em>15,000,000,000,000,000</em> — different tagged requests. We used the generator to randomly produce 3 million sentences for each sub-domain to train our NER on.</p><p>As it turned out, this method worked very nicely for a single sub-domain and our trained NER correctly tagged many words that it had never seen during training. However, when training for multiple sub-domains, the NER got confused and couldn’t cope. We needed first to identify the specific sub-domain <em>then</em> run the NER using a domain-specific model.</p><p>Thus, we built a sub-domain classifier, again using a DNN. We augmented the generator to also include the sub-domain classification and generated 9 million new sentences. We used those to train the classifier and the domain-specific NER models. Our classifier was able to achieve 99% accuracy across various sets of 9 million sentences. We realized that using the classifier could also be useful before running the LLs to eliminate false positives, get better SNR mappings and reduce the runtime of our semantic parser. Finally, we put everything together by first running the classifier and then the domain-specific LLs and NER model, applying our scoring metric on the results of both.</p><p>Next, we added a phase where we weeded out invalid mappings (where some fields were missing or doubly mapped, etc.) and filled in default values for empty fields such as “all” when no source/destination were specified and so on. Lastly, an evaluation step was carried out where we used our scoring metric to choose the “best” SNR mapping for the given query.</p><p>It should be noted, that the semantic parser itself was built to be generic. We used sub-domain specific LLs as well as generator templates for the classifier and NER training (all in the form of JSON files) to teach it the chosen networking sub-domains.</p><p><strong>Where Does This Fit in the Grand Scheme of Things?</strong></p><p>At this point, it was time to start thinking about configuring an NMS according to the chosen SNR mapping. To incorporate that, we widened our perspective and came up with a high-level design as shown in figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXtdPWQcIh4h62YZqJwGXw.png" /><figcaption>Figure 3: High Level Design</figcaption></figure><p>We would start by parsing the NL request while applying network semantics, extracting the various bits of information, and mapping them into an SNR. To make sure we got everything right, we would show the user what we understood and get their approval.</p><p>Next, we pass the SNR through a verification mechanism to confirm we had filled in all the required fields and to translate the human understandable terms to machine terms (such as addresses, ports, etc.) Once everything is ready, we pass the SNR through an NMS specific module that builds the actual network request according to the supplied fields. In our case, we used an NMS that was configured via a REST API. In a bit more detail, figure 4 shows the actual flow we built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ei3R7D5NHhfzYs6knFi87w.png" /><figcaption>Figure 4: SNR Processing Flow</figcaption></figure><p>The user speaks their request, and the speech-to-text mechanism converts it to text. The request passes through the semantic parser to give us the set of SNR candidates. Just as humans might understand the same sentence in several different ways so might our parser, and we need to examine each option to find the best one. We pass the candidates through a resolver that eliminates bad candidates according to predefined rules on required fields or sets of fields for the specific sub-domain, and fills in default values for empty fields. The candidates are ranked using our custom scoring metric and passed through an evaluator that chooses the best match according to the given scores. Once we have our “best” SNR in hand, we pass it through a standardizer to translate all the data into machine/network terms.</p><p>At this point, we might have several SNRs since some requests may translate into several network operations such as setting both directions of a network flow, handling both TCP and UDP requests, handling multiple port/address ranges etc. We then pass those SNRs through a dedicated NMS translator to convert everything to what the specific NMS expects to get, and then use an NMS specific API runner to build the corresponding REST API calls and carry them out.</p><p>This all looked good, but when trying some new real-world examples, we found that we were still missing some knowledge. The system didn’t know anything outside of the language and semantics we incorporated into it, but humans know more and have a context in which they make their requests. For example, a human technician would know what “the company site in San Jose” is, but the machine didn’t. How could we add such capabilities to our system?</p><p>Our solution was two-fold. Firstly, we decided to harvest the chosen NMS for data it already had regarding networks, VPNs, VLANS, hosts etc. Secondly, we added an adaptive learning knowledge base (ALKB). The first time the system encounters something it can’t translate into network/NMS terms, we ask the user to do this for us. We add the knowledge into our ALKB so that we can retrieve it the next time we encounter the same term. We use an iterative process in which we review all the unknowns and let the user fill them in. After a couple of iterations, we have the full mapping and translation and can build the REST calls used to configure the system.</p><p><strong>Making Things Pretty</strong></p><p>To make things nice and presentable, we added a simple Web UI where the user can simply speak to the machine and make their request (figures 5–6). The system presents the initial mapping and then gives the user the ability to fill in missing data, either by choosing from a list of options taken from the ALKB or NM, or by typing/speaking their own answers (figures 7–10). Finally, we configure the NMS and give the user a link to the NMS screen where the results of the configuration can be inspected (figures 11–13). The UI also keeps track of all the requests and configurations for debugging and accountability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bNLi9CHPtbs1xwi58DPAeg.png" /><figcaption>Figure 5: Front page where the user can either type in or speak their request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUxYuw8jrM9KbvKqwjfs1w.png" /><figcaption>Figure 6: The system is running the request through the semantic parser…</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLaBXS8me94UzU8Qkgt0Vg.png" /><figcaption>Figure 7: The request has been parsed and the SNR mapping is shown after translation to NMS terms. Still some information is missing so the user is asked to make a choice.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEQFhwX_7PwcS_vcpoiPuQ.png" /><figcaption>Figure 8: The user makes a choice</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qj8cZnq9Bbts89BMXZSDCQ.png" /><figcaption>Figure 9: Now the SNR is fully resolved</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_avjT74QSij4WYCfNKd-Pw.png" /><figcaption>Figure 10: We can also see the list of API calls that will be carried out to fulfill the request — In this case we need a single call</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTLG7O8NS_CmtzuKAypCKQ.png" /><figcaption>Figure 11: The NMS is being configured…</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoZBskG3HLrpTVT32hOq7g.png" /><figcaption>Figure 12: The request was successfully carried out!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVRZ4Hij8UeJ2a2ulCOIvg.png" /><figcaption>Figure 13: This is the NMS dashboard showing the new configuration that was added to fulfill the request</figcaption></figure><p><strong>So How Good Were Our Results?</strong></p><p>We needed a way to measure our success. We already had our generator that gave us gold-standard data, so all we needed to do was compare that to what our semantic parser did. We created more than 50,000 sample sentences, passed them through the system, and counted and averaged the good, bad, and missing mappings. As it turned out, our mapping accuracy was roughly 94% — a very high figure in the NLP world.</p><p>All in all, we spent two to three months in tech investigations to learn the field of NLP and the existing tech as well as to meet with various groups within and outside our company to gather their input and wisdom. We then spent another month dissecting the problem space and planning our moves. We chose to use Python 3.6 as our language and spent another six months on actual coding and debugging to get the final result.</p><p>We published our efforts as a defensive publication: <a href="https://www.tdcommons.org/dpubs_series/3402/">https://www.tdcommons.org/dpubs_series/3402/</a></p><p>We had some thoughts on future development such as adding an initial configuration step where user/company/entity specific knowledge could be fed into the system to avoid having to ask the users many questions during the initial running period of the system. We also wanted to integrate with some user/employee management systems that would be able to give us information about the registered devices a user owns and is currently using and add background trackers that would continuously update the NMS configurations as things change to make sure the network requests are always carried out in a dynamic environment. However, since this was a technical investigation that was picked up as a project for further development by a different R&amp;D group, we didn’t have the opportunity to pursue those ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f16548a91b05" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cisco-fpie/how-we-built-a-domain-specific-natural-language-semantic-parser-f16548a91b05">How We Built a Domain-Specific Natural Language Semantic Parser</a> was originally published in <a href="https://medium.com/cisco-fpie">cisco-fpie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>