<?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 Marcos Vinicius Moreira Santos on Medium]]></title>
        <description><![CDATA[Stories by Marcos Vinicius Moreira Santos on Medium]]></description>
        <link>https://medium.com/@marcos30004347?source=rss-4a2fb51caee4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*m5jZnpL6NgRjoXFQ.jpg</url>
            <title>Stories by Marcos Vinicius Moreira Santos on Medium</title>
            <link>https://medium.com/@marcos30004347?source=rss-4a2fb51caee4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:17:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcos30004347/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[Programming a Kubernetes Extension API Server — Part 3]]></title>
            <link>https://medium.com/@marcos30004347/programming-a-kubernetes-extension-api-server-part-3-f7edddc974f4?source=rss-4a2fb51caee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7edddc974f4</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Marcos Vinicius Moreira Santos]]></dc:creator>
            <pubDate>Thu, 23 Sep 2021 17:43:26 GMT</pubDate>
            <atom:updated>2021-09-23T17:43:26.108Z</atom:updated>
            <content:encoded><![CDATA[<h3>Programming a Kubernetes Extension API Server — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJNbirMY6d0nZkoDmwYWAA.jpeg" /></figure><p>This is the last post of the “Programming a Kubernetes Extension API Server” series. In this post all the manifest files that will be used to deploy the Extension API Server inside a cluster will be given. As an example, we’re going to deploy it inside a minikube cluster and a simple example of how to apply our defined custom resources using kubectl. I will not explain every deployment file since this is assumed as a basic kubernetes knowledge. The manifest files presented here should be seen as examples and it should be easy to everyone to copy and change the parts needed for your use case.</p><h4>Enviroment</h4><p>Authough you can start and use the server written in the last two parts as a standalone application, they are generally deployed inside a kubernetes cluster. We’re going to use minikube for the deployment of our custom API server.</p><p>Before anything, lets start the cluster with:</p><p>$ minikube start</p><p>And let’s share the docker environment with:</p><p>$ eval $(minikube docker-env)</p><p>To build our docker image we’re going to use the following dockerfile defined at the root of the project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/483b487ca2617e3f0ab86e7d2d966d86/href">https://medium.com/media/483b487ca2617e3f0ab86e7d2d966d86/href</a></iframe><p>To build the image, we will use a makefile with the following commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/837340eff86ebbd8c123b3f9ecf130cc/href">https://medium.com/media/837340eff86ebbd8c123b3f9ecf130cc/href</a></iframe><p>And then run:</p><p>$ make build</p><p>Now we have our docker image that can be deployed inside the minikube cluster.</p><h4>Manifest files</h4><p>Now what is left are the deployment manifests, if you are familiar with the kubernetes yaml manifests those are pretty much self explanatory:</p><ul><li><strong>artifacts/deploy/namespace.yaml</strong>:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a55365c611bd01d3dae3f547e86c0caa/href">https://medium.com/media/a55365c611bd01d3dae3f547e86c0caa/href</a></iframe><ul><li><strong>artifacts/deploy/service.yaml</strong>:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ebd041eb4f26255cff61d6e72ea901e/href">https://medium.com/media/1ebd041eb4f26255cff61d6e72ea901e/href</a></iframe><ul><li><strong>artifacts/deploy/service-account.yaml</strong>:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1baf7302fb1611b2ded4fa0f3066e3dc/href">https://medium.com/media/1baf7302fb1611b2ded4fa0f3066e3dc/href</a></iframe><ul><li><strong>artifacts/deploy/deployment.yaml</strong>:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e0bdd777063a22dfeba668cc0305c91/href">https://medium.com/media/2e0bdd777063a22dfeba668cc0305c91/href</a></iframe><ul><li><strong>artifacts/deploy/auth-delegator.yaml</strong>:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0de17db0a6190089e2ceb36c026fa1af/href">https://medium.com/media/0de17db0a6190089e2ceb36c026fa1af/href</a></iframe><ul><li><strong>artifacts/deploy/auth-reader.yaml</strong>:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/060fbcad6652ff71b147d56a8bacf3f9/href">https://medium.com/media/060fbcad6652ff71b147d56a8bacf3f9/href</a></iframe><ul><li><strong>artifacts/deploy/rbac.yaml:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfb66318abed570271edc68885160f6d/href">https://medium.com/media/bfb66318abed570271edc68885160f6d/href</a></iframe><ul><li><strong>artifacts/deploy/rbac-bind.yaml:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5768d1e46cb02be04c9f30cf4cb52f68/href">https://medium.com/media/5768d1e46cb02be04c9f30cf4cb52f68/href</a></iframe><ul><li><strong>artifacts/deploy/v1alpha1-apiservice.yaml:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b16aaeec8b8034c873a2c02afeeb5ade/href">https://medium.com/media/b16aaeec8b8034c873a2c02afeeb5ade/href</a></iframe><h4>Deployment</h4><p>Now we can deploy our server, the final makefile of the project is</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c63935464a4df2a27efe1595d196c326/href">https://medium.com/media/c63935464a4df2a27efe1595d196c326/href</a></iframe><p>To deploy ther server using this makefile run:</p><p>$ make deploy</p><p>You can verify the status of the Extension API Server with the command:</p><p>$ kubectl get apiservices</p><p>After the server initialization, to test if the server is working, let’s create our foo and bar manifests:</p><ul><li><strong>artifacts/example/bar.yaml</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ccc988f495c2c1130b799cc740347a0/href">https://medium.com/media/2ccc988f495c2c1130b799cc740347a0/href</a></iframe><ul><li><strong>artifacts/example/foo.yaml</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c4f687df51aef7d9ab8c4ef3a31cc9d/href">https://medium.com/media/8c4f687df51aef7d9ab8c4ef3a31cc9d/href</a></iframe><p>We first apply the Bar’s manifest with:</p><p>$kubectl apply -f artifacts/example/bar.yaml</p><p>And then the Foo’s manifest:</p><p>$kubectl apply -f artifacts/example/foo.yaml</p><p>You should get messages telling that the resources were successfully cerated indicating that the server is working as expected.</p><h4>Last Remarks</h4><p>The complete code of the project can be found in the following github repository:</p><p><a href="https://github.com/Marcos30004347/kubernetes-posts">GitHub - Marcos30004347/kubernetes-posts</a></p><p>You will also find some other examples of kubernetes custom servers there if you want more examples.</p><p>Of course the Server written in this series is pretty simple and not very usefull, but is should be easy to extend the knowledge presented here to do more useful stuff, like a robust automatic sidecar injection for example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7edddc974f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming a Kubernetes Extension API Server— Part 2]]></title>
            <link>https://medium.com/@marcos30004347/programming-a-kubernetes-extension-api-server-part-2-ab3b2123ad78?source=rss-4a2fb51caee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3b2123ad78</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Marcos Vinicius Moreira Santos]]></dc:creator>
            <pubDate>Fri, 17 Sep 2021 18:31:53 GMT</pubDate>
            <atom:updated>2021-09-17T18:31:53.075Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part of the Programming a Kubernetes Extension API Server series. Here we are going to continue writing the code started in part one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_990ZrVqZj0a3if1OR8BDg.jpeg" /></figure><h3><strong>Admission Plugin</strong></h3><p>From now on we will focus our attention on the admission process and the registries for our API resources.</p><p>After the resources are unmarshalled, defaulted and converted the resource will be sent to the admission plugins. Admission plugins can be both mutating and validating, in our case we will be focusing just on the second case and define our plugin to do just admission.</p><p>We need to define a new package. Inside the pkg/admission/initializer folder create two new files, bazinformer.go and interfaces.go.</p><p>Inside the interfaces.go paste:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fd075645d4bd541af23e7fac6e9063c/href">https://medium.com/media/2fd075645d4bd541af23e7fac6e9063c/href</a></iframe><p>Inside the bazinformer.go paste:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/164f1ded67d43bc0f76df4c67a5e8110/href">https://medium.com/media/164f1ded67d43bc0f76df4c67a5e8110/href</a></iframe><p>Those packages will be responsible for initializing the admission plugins, the initializer is almost entirely boilerplate code.</p><p>Now we’re going to define a plugin for the Foo Resource, you can repeat those steps for any resource that you want. This post focus just in the Foo resource to do the validation described in part one. Inside pkg/admission/plugin/foo create a file called admission.go since this will be our admission plugin.</p><p>The plugin that we’re going to create will be very simple, it will just verify if the Bars used inside the Foo resource being created already exist in the cluster. If not an error will be returned to the user during the <em>kubectl apply -f foo.yaml </em>command.</p><p>Lets add the boilerplate code that the plugin will need to work. The plugin will need a Register function that will register the plugin on the server, a structure that will represent the plugin itself and since we want to verify the Bars used inside the Foo resource, the plugin will need a Lister for the Bar resource.</p><p>All that can be added as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/112958ff76146069682ed472e0d5648c/href">https://medium.com/media/112958ff76146069682ed472e0d5648c/href</a></iframe><p>As you can see we define the Plugin structure with the k8s admission handler from the “k8s.io/apiserver/pkg/admission” package and add a Bar Lister to it, the other functions are responsible for the Bar Lister initialization, validation and creation.</p><p>Now comes the Admit function that will admit new Foo resources and make the validation of the Foo’s Bars as we described, lets define it as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/365e6cf81ab6a42634732c2f89ac72fc/href">https://medium.com/media/365e6cf81ab6a42634732c2f89ac72fc/href</a></iframe><p>The function receives three parameters, a context for the request, the attributes that contains the information useful for advanced checks and the attributes object have the following interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d09c9a8b07aa646b0f723853c409186/href">https://medium.com/media/1d09c9a8b07aa646b0f723853c409186/href</a></iframe><p>The third parameter is of type ObjectInterfaces that have the following interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69f4e95752c33c5d5f193e90c7ee6132/href">https://medium.com/media/69f4e95752c33c5d5f193e90c7ee6132/href</a></iframe><p>Our validation will first verify the resource kind. If it matches Foo, it will proceed to verify the Bars resources by using the Lister. It will try to find Bars resources inside the same namespace as the Foo resource being deployed. If they are not found, an error will be returned to the user telling it that the bar resource are unknown.</p><p>If you need a plugin that does more than Admission, you can define multiple functions, like for the validation case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f223edba26f4f28dc0184dd5eb6ad55c/href">https://medium.com/media/f223edba26f4f28dc0184dd5eb6ad55c/href</a></iframe><p>The interface that your plugins can have are one of the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52e1b7f64fae038861184e62ee2f89fc/href">https://medium.com/media/52e1b7f64fae038861184e62ee2f89fc/href</a></iframe><p>You can check the source of the “k8s.io/apiserver/pkg/admission” package for more information.</p><p>The full plugin will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b3b87b1c0bfe68f31bd6e132c973ac0/href">https://medium.com/media/6b3b87b1c0bfe68f31bd6e132c973ac0/href</a></iframe><h3><strong>Server initialization</strong></h3><p>Some of the code that will be presented can be seen as a lot of boilerplate, the packages will be responsible for configuring and running our server.</p><h4><strong>apiserver package</strong></h4><p>First, we need to define our apiserver package, that will be responsible for installing and configuring the API Server. Inside the package we will instantiate our schema and codecs that some of the functions in part one use. inside the pkg/apiserver/apiserver.go they can be defined as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/689d6fbb083399d2428872207c0b89a2/href">https://medium.com/media/689d6fbb083399d2428872207c0b89a2/href</a></iframe><p>We also need to install all the API resources and register the unversioned types to the scheme. It can be done inside the init function of the package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/576f95478539cbb117770fdffd721153/href">https://medium.com/media/576f95478539cbb117770fdffd721153/href</a></iframe><p>Now we have to define our API configuration and initialization process. The config structure will be a wrapper of the RecomendedConfig of the <em>k8s.io/apiserver/pkg/server</em> package. If needed, we will append extra configuration to it. After the configuration is completed, it will be able to create servers. This can be done by defining the following structures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62b10a8d7c0b86f565d9510c929bdb03/href">https://medium.com/media/62b10a8d7c0b86f565d9510c929bdb03/href</a></iframe><p>As you may have noticed, we have two completed config structures: completedConfig and CompletedConfig. A private and a public one respectively. This is going to be useful because the Complete method of <em>genericapiserver.CompletedConfig</em> needs to be called and defining the private completedConfig structure will help us force that call, the function that will perform this task is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24278b032133c09e0cc5fd319514d054/href">https://medium.com/media/24278b032133c09e0cc5fd319514d054/href</a></iframe><p>This funtion completes the Generic Config and sets some default configuration values. Now we have to create a custom server from that configuration. For this we can create the following function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/948b3faf966a582367f137ff2b71f82b/href">https://medium.com/media/948b3faf966a582367f137ff2b71f82b/href</a></iframe><p>The full package will be defined inside pkg/apiserver/apiserver.go and will have the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f1d5d7f0c15750052b51f1f92242a9c/href">https://medium.com/media/8f1d5d7f0c15750052b51f1f92242a9c/href</a></iframe><h4><strong>The server package</strong></h4><p>To have a working Extension API Server, an additional step is needed, that is create and call the code that will instantiate and run the server. The code will be defined in a server package inside pkg/cmd/server/server.go and the calling will happen on the main package as usual.</p><p>On the server package, defined in pkg/cmd/start.go, we will follow how kubernetes instantiate and handle command line commands by making use of the cobra package. It will be necessary to use the cobra.Command structure, and inside it we will need another structure that we will call CustomServerOptions that will config, complete, validate and run our API Server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e81b78332bc26d250bf77459cf7b52c/href">https://medium.com/media/4e81b78332bc26d250bf77459cf7b52c/href</a></iframe><p>This code already sets some etcd parameters and calls the Codecs from the apiserver package. Now we will introduce the Complete, Validate and Run methods for our CustomServerOptions. Those are going to be called when we use the cobra package to create our cobra.Command.</p><p>The Complete function will Register our admission plugin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4112e71236c6820e0d7f7d3c1fd71b/href">https://medium.com/media/cf4112e71236c6820e0d7f7d3c1fd71b/href</a></iframe><p>The validate function will just validate the RecomendedOptions from the “k8s.io/apiserver/pkg/server/options” package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/357a75549666861363b2b0c06d4c29cc/href">https://medium.com/media/357a75549666861363b2b0c06d4c29cc/href</a></iframe><p>The Run is the more complicated, and it will be splitted into two functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88978d158e1edaab18afcab0b306eeaf/href">https://medium.com/media/88978d158e1edaab18afcab0b306eeaf/href</a></iframe><p>Those are pretty straightforward functions, the Config function will define some configuration for the certificates that the server will use and where it should listen. It will also set some etcd configuration: the callback that will set up the Clientsets, the plugins initializer and Informers of our API and terminate returning the initialized apiserver.Config structure.</p><p>The Run function will receive the stop channel. That will be a channel used just for telling when everything should stop and will call the previous explained Config method for getting a apiserver.Config structure. It will complete it calling the Complete function and will instantiate a server by calling New from that config. It will end its execution by registering a PostStartHook called “start-baz-api-informers”. This hook will run when the server HTTPS is up and listening and will be responsible for starting the shared informer factory of our API at the correct time.</p><p>What is left now is just to create our cobra.Command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed2c510b021d3ba748f1b7e85c80dcb2/href">https://medium.com/media/ed2c510b021d3ba748f1b7e85c80dcb2/href</a></iframe><p>As you can see, the command will execute the Complete, Validade and Run functions in order when it’s called, Add to the RecommendedOptions and utilfeature the cmd flags and return the command at the end.</p><p>The full server package will be defined inside pkg/cmd/server/start.go and will have the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b60737ec8c5d2eec62f671e7061ae2e/href">https://medium.com/media/6b60737ec8c5d2eec62f671e7061ae2e/href</a></iframe><p>Now we will start the API Server in the main package. In the root of the project, you can create a main.go file and paste the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c791bade8520a2a45b1604fdcb37fe4d/href">https://medium.com/media/c791bade8520a2a45b1604fdcb37fe4d/href</a></iframe><p>You can now finally run the server outside the cluster by calling:</p><p>$ go get -d .</p><p>$ etcd &amp; go run . — etcd-servers localhost:2379 — authentication-kubeconfig ~/.kube/config — authorization-kubeconfig ~/.kube/config — kubeconfig ~/.kube/config</p><p>You can also compile it by calling:</p><p>$ CGO_ENABLED=0 go build .</p><p>But it may not run properly because remains one last thing to do, define the strategy and registry.</p><h3><strong>Creating the registry and strategy</strong></h3><h4><strong>Registry</strong></h4><p>Until now, we have seen how the API types are created and validated, but we still need to define the REST behaviour of the API. The most common registry that kubernetes gives us to use is the <em>generic registry</em> defined in the <em>k8s.io/apiserver/pkg/registry/rest</em> package. The generic registry defines the “normal” behaviour that a resource may have. Almost all kubernetes resources use this kind of registry, only the ones that do not persist objects use other types of registries. In <em>k8s.io/apiserver/pkg/registry/rest/rest.go</em> you can find a lot of interfaces for different kinds of registries. Because the generic registry implements most of the <em>k8s.io/apiserver/pkg/registry/rest</em> interfaces, resources that use the generic registry will support all the default Kubernetes HTTP verbs.</p><h4><strong>Strategy</strong></h4><p>The generic strategy can be customized by using an object called a strategy.</p><p>Lets define our registry, it is pretty simple, lets create file pkg/registry/registry.go and paste the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c064a161ae43aa3124ea144912e91934/href">https://medium.com/media/c064a161ae43aa3124ea144912e91934/href</a></iframe><p>You can see that it is pretty simple. We define a structure that will be responsible to handle the REST logic for storage of resources and a function that will handle errors and inform us about them.</p><p>Now we have to create the strategies. We’re going to describe the strategy only for the Foo resource type, but the code for the strategy for the Bar resource will be given, and you will see that it is very similar to the Foo code, only a few lines with different type names of difference.</p><p>Lets create the file pkg/registry/baz/foo/strategy.go, in this file, we will create an object that will match the interface of the generic REST strategy.</p><p>Add the following content to the pkg/registry/baz/foo/stretegy.go</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2002fa29e8d1fef81ec8e71ec780c903/href">https://medium.com/media/2002fa29e8d1fef81ec8e71ec780c903/href</a></iframe><p>The code is also very straightforward, it just adds a bunch of functions to the fooStrategy struct, remember that this function needs to match the interface of the chosen strategy. In this file were also defined helper functions that will be used to instantiate the registry REST API. Lets create a new file pkg/registry/baz/foo/etcd.go and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0dd2c122c369aa9b1af4d70a23ea2b3/href">https://medium.com/media/e0dd2c122c369aa9b1af4d70a23ea2b3/href</a></iframe><p>Now what remains is the strategy code for the Bar resource. Since it’s pretty much equal to the Foo resource, only a few names and types were changed. You can compare the two to see the differences, here is the code:</p><p>pkg/registry/baz/bar/strategy.go:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d99caf23cb8686c894a49f75393bc2e/href">https://medium.com/media/8d99caf23cb8686c894a49f75393bc2e/href</a></iframe><p>pkg/registry/baz/bar/etcd.go:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/599add3fe7066e15e1a52f495fac1dfd/href">https://medium.com/media/599add3fe7066e15e1a52f495fac1dfd/href</a></iframe><p>Now what remains is just the call to the NewREST functions in the apiserver package under pkg/apiserver that will instantiate our registries. Lets wrap the call in the RESTinPeace function to catch errors during the instantiation.</p><p>Add the following imports to the apiserver package</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a03feb032c865156a04b9c16fd04f098/href">https://medium.com/media/a03feb032c865156a04b9c16fd04f098/href</a></iframe><p>We are going to add the following code to the New method in the apiserver package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2950fc7eb117e4b42856cc743a2e2b2/href">https://medium.com/media/f2950fc7eb117e4b42856cc743a2e2b2/href</a></iframe><p>This code is responsable for creating our registries and add it to the storage map of the api v1alpha1 version. The full “New” function will be defined as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f28b9263b902f312067ad6765daca48/href">https://medium.com/media/9f28b9263b902f312067ad6765daca48/href</a></iframe><h3>Conclusion</h3><p>That’s all the code needed to have a full working Kubernetes Custom API Server. It is now possible to run and use it outside the cluster as desbribed previously without any errors. In part three all the manifest files for the deployment of the Extension API Server on a cluster will be defined.</p><p>If you want a closer look at the code, all the working code for the Extension API Server defined in this series can be found on:</p><p><a href="https://github.com/Marcos30004347/kubernetes-posts">GitHub - Marcos30004347/kubernetes-posts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3b2123ad78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming a Kubernetes Extension API Server — Part 1]]></title>
            <link>https://medium.com/@marcos30004347/programming-a-kubernetes-extension-api-server-part-1-60526e141a10?source=rss-4a2fb51caee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/60526e141a10</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Marcos Vinicius Moreira Santos]]></dc:creator>
            <pubDate>Tue, 14 Sep 2021 18:58:34 GMT</pubDate>
            <atom:updated>2021-09-14T18:58:34.786Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Programming a </strong>Kubernetes Extension<strong> API Server — Part 1</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOnG6mthtTiJrp9_HSiE4Q.png" /></figure><h3>Introduction:</h3><p>In some situations you may want to use a Custom Resource Definition to add new resources to your system or add new functionalities to kubernetes to better fit your needs through custom controllers. The problem with CRDs is that they can be limited in some situations like limited Validation, no graceful deletion, limited number of Subresources and significant performance cost to the Kubernetes API server.</p><p>Extension API Servers on the other hand didn’t have any of those problems, they have almost infinite flexibility and can extend your kubernetes functionalities by adding new REST endpoints.</p><p>A good example for a Custom API Server is the metrics-server:</p><p><a href="https://github.com/kubernetes-sigs/metrics-server">GitHub - kubernetes-sigs/metrics-server: Scalable and efficient source of container resource metrics for Kubernetes built-in autoscaling pipelines.</a></p><p>The metric-server adds some useful commands to Kubernetes that allow the DevOps team to see how much CPU and Memory your pods are using. The problem is that to write a Custom API Server you have to know about k8s development. Documentations are sometimes small and difficult to grasp if you are a beginner with kubernetes programming. If that’s the case and you want a deep dive into Kubernetes programming I recommend you the book “Programming Kubernetes: Developing Cloud-Native Applications” by Stefan Schimanski. Although I’m gonna try to give as much info and details as possible.</p><p>This series of posts are aiming to give you a quick introduction to kubernetes programming and some examples of code, and it’s deeply recommended that you check other resources to get a deeper dive. During this series of posts we’re going to create a simple Extension API Server and deploy it to a cluster.</p><p>At the end you will be able to write custom api servers and extend the knowledge to write embedded controllers and at least understand a little bit more about kubernetes development.</p><h4>Prerequisites:</h4><ul><li>Basic Kubernetes knowledge.</li><li>Basic Docker knowledge.</li><li>Basic Golang knowledge.</li><li>Basic Minikube knowledge.</li></ul><h3><strong>Kubernetes API concepts</strong>:</h3><p>Before we start to write our code, it will be useful to define some concepts.</p><ul><li><em>Etcd: Etcd is the key store database of kubernetes.</em></li><li><em>Client Sets: Client sets give the programmer access to multiple API groups and resources. With a ClientSet for a specific API group you will be able to manage resources in your cluster, like deployments, pods and whatever resource you may think just via code.</em></li><li><em>Listers: Listers are objects that allow the programmer to get and list a set of resources registered inside the cluster. They can be viewed as the programmer’s way of calling “kubectl list” and “kubectl get”.</em></li><li><em>Informers: As the name suggests, informers are objects that can inform about the lifecycle of a resource. With informers you can execute functions when a resource is created, updated and deleted. They are very useful when writing custom Controllers.</em></li><li><em>Codegen: When adding custom resources to Kubernetes, a lot of work may have to be done by the programmer, like creating all the listers, informers, client sets and the functions to set default values to the resource fields and conversions between versions. </em>Since all of those objects share a big chunk of code for all the different types inside our packages, writing those objects will be a very easy task with the help of templates, but since this isn’t a feature of the golang, codegen is generally used in its place. Instead of manually writing the boilerplate common code, we are going to tell a software how the code should be written and let the software write that boilerplate code for us.</li></ul><h4><em>API Versioning and Resources</em></h4><p>A given API group may have different versions like v1beta1, v1alpha1, v1, v2 … etc. All of those versions may add new resources to the API and handle data in a different way. The problem with this is that to handle those resources in different versions, the programmer would have to write the same business logic but for all the same types inside different versions. To avoid that burden, the API resources are converted between each other, so if you have a piece of code that runs over a specific version, it can be executed for other versions using the resources conversion.</p><p>The problem with this approach is that for each version, the programmer needs to write, for every API version Resource, a conversion method for each other API Version Resource, which may be a lot of work. To avoid the quadratic number of conversion methods between each version, the API Server uses an internal version that will be used only inside the API Server and that will be the version that your code will execute upon. Now you will only need a conversion between the external API version and the internal API version, and all the business logic for your API will execute upon the internal converted resource type.</p><h4><strong>Defining the resources:</strong></h4><p>Let’s now think about what group and resources we want to add to the kubernetes API. Because this is just for educational purposes, we are not going to do anything fancy. We will add two resources of Kind Foo and Bar respectively on the baz group. An example of the yaml manifest files that we will use to create our resources inside the cluster will look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48750fd4216c62a927fbad1ae06044b4/href">https://medium.com/media/48750fd4216c62a927fbad1ae06044b4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c460ffa20dee3dabd1df34113c653f9f/href">https://medium.com/media/c460ffa20dee3dabd1df34113c653f9f/href</a></iframe><p>As you can see, the Foo resource depends on the Baz resources, and if the Hommer resource does not exist at the type of creating the Foo resource, the server should return an error to the user during the “kubectl apply” command.</p><h3><strong>Introduction to Codegen</strong></h3><p>Before we start writing the code, we’re going to discuss a bit about the codegen needed to write the custom server.</p><p>Codegen is the process that will allow us to automatically write code for ClientSets, Informers, Listeners and more using the k8s.io/code-generator package.</p><p>The codegen can be controlled by flags in form of comments right above the struct types with a “+” character before them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40a6bea52de5ef1c4dd63364befcd282/href">https://medium.com/media/40a6bea52de5ef1c4dd63364befcd282/href</a></iframe><p>For a real example, all of the API versions have a file called doc.go that define some globall tags for the codegen process that is going to affect all of the types defined inside that version package. A commom doc.go fili typicall looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62718df80b5a718fcba652c994afd17b/href">https://medium.com/media/62718df80b5a718fcba652c994afd17b/href</a></iframe><p>Note that the tags must be separated at least by one empty line from a normal comment.</p><p>The first line of this file tells deepcopy-gen to create deep-copy methods by default for every type in that package. Deep Copy is used to make a full copy of objects as the name suggests, all the pointers inside the copied object will point to new copies of the original pointed objects. If you have types where deep copy is not necessary, you can opt them out with the local tag “+k8s:deepcopy-gen=false”. If you do not enable package-wide deep copy, you have to opt in the deep copy for each desired type via “k8s:deepcopy-gen=true” above every type.</p><p>The second tag, “+groupName=some.goup.example”, defines the fully qualified API group name. This tag is necessary if the Go parent package name does not match the group name.</p><h4>DeepCopyObject example:</h4><p>The DeepCopyObject() method does nothing more than calling the generated DeepCopy method. The signature of the latter varies from type to type (DeepCopy() *T depends on T).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01e7b11e91ec911f7c322fb292759c6d/href">https://medium.com/media/01e7b11e91ec911f7c322fb292759c6d/href</a></iframe><p>Put the local tag “+k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object” above your top-level API types to generate this method with deepcopy-gen. This tag tells deepcopy-gen to create such a method for runtime.Object, called DeepCopyObject().</p><p>It happens that other interfaces need a way to be deep-copied too. This is usually the case if, for example, API types have a field of interface type Foo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1af1500db3c303ffcb8dc12cc9277e4f/href">https://medium.com/media/1af1500db3c303ffcb8dc12cc9277e4f/href</a></iframe><p>Because API types must be deep-copyable, the field Foo must be deep-copied too. How could you do that in a generic way, without type-casts and without adding a DeepCopyFoo method to the Foo interface?</p><p>In that case the same tag can be used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/508df71195109f1b0dfc0c173ede8148/href">https://medium.com/media/508df71195109f1b0dfc0c173ede8148/href</a></iframe><p>Some other tags are:</p><ul><li><strong>+genclient </strong>— generate default client verb functions (create, update, delete, get, list, update, patch, watch and depending on the existence of the .Status field in the type the client is generated for also updateStatus).</li><li><strong>+genclient:nonNamespaced</strong> — all verb functions are generated without namespace.</li><li><strong>+genclient:onlyVerbs=create,get </strong>— only listed verb functions will be generated.</li><li><strong>+genclient:skipVerbs=watch</strong> — all default client verb functions will be generated except watch verb.</li><li><strong>+genclient:noStatus</strong> — skip generation of updateStatus verb even though the Status field exists.</li><li><strong>+k8s:deepcopy-gen:interfaces</strong> — tag can and should also be used in cases where you define API types that have fields of some interface type. Then “+k8s:deepcopy-gen:interfaces=example.com/pkg/apis/example.SomeInterface” will lead to the generation of a “DeepCopySomeInterface() SomeInterface” method. This allows it to deepcopy those fields in a type-correct way.</li><li><strong>+groupName=example.com </strong>defines the fully qualified API group name. If you get that wrong, client-gen will produce wrong code. Be warned that this tag must be in the comment block just above the package name.</li></ul><h3>Coding</h3><h4><strong>Setup</strong>:</h4><p>Let’s define the golang project. I’m going to create a package that will be stored on my github account, you can define your package as you want.</p><p>$ go mod init github.com/Marcos30004347/kubernetes-posts</p><h4><strong>The first packages:</strong></h4><p>We now have to define our package folder structure, the more common way of defining the api types is inside a pkg/apis folder. We are going to start with a folder structure that looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1286ca4e0b73eb73a85e158113c44f3/href">https://medium.com/media/c1286ca4e0b73eb73a85e158113c44f3/href</a></iframe><p>Under the /pkg/apis/ we create a folder called baz, that will define our API group, inside this folder we create two extra folders, v1alpha1 and v1beta1 that will be our external api versions, this means that the user will be able to create manifests under the apiVersion “baz/v1alpha1” and “baz/v1beta1”, we also define two files under the folders pkg/apis/baz, pkg/apis/baz/v1alpha1 and pkg/apis/baz/v1beta1, types.go and doc.go.</p><p>First, in the v1alpha1 docs.go, write:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/241ce6856047017580b72991c7a95068/href">https://medium.com/media/241ce6856047017580b72991c7a95068/href</a></iframe><p>As you can see, it defines the group as baz, and adds a couple of codegen flags to our v1alpha1 package. Now in the types.go in the same folder, we can add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/472510bec4519615410d86080eb77efc/href">https://medium.com/media/472510bec4519615410d86080eb77efc/href</a></iframe><p>Each resource, in this case Foo and Bar, need also an equivalent list Resource, in this case FooList and BazList respectively. We also define the JSON and protobuf marshalling rules for our structure. You can compare our golang structures definitions with our manifest examples and you will see the correspondence between them.</p><p>Now we have to define our internal versions.</p><p><em>The pkg/apis/baz/doc.go:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edadc6886eaec5525a34595d102be12b/href">https://medium.com/media/edadc6886eaec5525a34595d102be12b/href</a></iframe><p><em>The pkg/apis/baz/types.go:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0be21ee29002f8fd102700b89d61256/href">https://medium.com/media/c0be21ee29002f8fd102700b89d61256/href</a></iframe><p>We didn’t need marshalling rules for the internal version, this is because we don’t give the user the ability to define the resources in the internal form, only the external ones, so the internal types will never have the need to be unmarshalled. You may also have noticed that we define some of our equivalent structures in a different way, namely FooSpec of v1alpha1 is different from the one in the internal version, later we will use our codegen to define our conversion functions, and I want to use this different structures to show you how you will do the conversion between the different fields inside each API version.</p><h4><strong>Configuring the Codegen:</strong></h4><p>Let’s define a dockerfile and a script that we can use to call the codegen.</p><p>Inside the folder hack/docker/ on the same level that the go.mod file, add the following dockerfile:</p><p><em>hack/docker/codegen.dockerfile:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/553c0df2f2d400f36a21c92dfa9629f4/href">https://medium.com/media/553c0df2f2d400f36a21c92dfa9629f4/href</a></iframe><p>Remember to change the link to your project repository. Now we’re going to use the following script to call our dockerfile</p><p><em>hack/scripts/codegen.sh</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f68f873890901f24e15ea7a43d11c6f0/href">https://medium.com/media/f68f873890901f24e15ea7a43d11c6f0/href</a></iframe><p>From now two things can happen, the codegen may finish with an error, or the code is generated but you will have compiling errors, this is because the codegen didn’t know how to convert from the internal FooSpec:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b9c8e9a70df7955e4b3c178d795d020/href">https://medium.com/media/2b9c8e9a70df7955e4b3c178d795d020/href</a></iframe><p>To the external v1alpha1 version FooSpec</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8faecc104807a9b4871d9367b5112214/href">https://medium.com/media/8faecc104807a9b4871d9367b5112214/href</a></iframe><p>To resolve this, we will need to define a custom conversion function for them and to do that, create a file inside the pkg/apis/baz/v1alpha1 folder called conversion.go, and paste the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06fe7cdc461eb7fbe1524d0e43ccd6ec/href">https://medium.com/media/06fe7cdc461eb7fbe1524d0e43ccd6ec/href</a></iframe><p>As you may have noticed, the name of the functions follow the template:</p><p>Convert_{external-version}_{structure}_To_{internal-version}_{structure}</p><p>or</p><p>Convert_{internal-version}_{structure}_To_{external-version}_{structure}</p><p>This is important, as the codegen will follow this convention for calling the Conversion functions, now what we have to do is tell the codegen that it didn’t need to create those conversion functions, we will redefine the structures adding the following flags:</p><p>in the baz package (internal version):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a8df0ca6caa9ac4d306d74a124b2853/href">https://medium.com/media/5a8df0ca6caa9ac4d306d74a124b2853/href</a></iframe><p>In the v1alpha1 external version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/391afaf8ba8714ce031aeec470c5c145/href">https://medium.com/media/391afaf8ba8714ce031aeec470c5c145/href</a></iframe><p>Now we can run the codegen again and everything should run as expected</p><p><em>$ ./hack/scripts/codegen.sh</em></p><p>You will notice that a folder was created inside the pkg folder called gerenerated, that will contain the generated code for our Listers, ClientSets and Informers, you will also notice that inside the “apis/baz” and “apis/baz/v1alpha1” folder some files were created with a zz_generated prefix. Inside the v1alpha1 folder three files should be created:</p><ul><li>zz_generated.conversion.go</li><li>zz_generated.deepcopy.go</li><li>zz_generated.defaults.go</li></ul><p>In the internal version, only zz_generated.deepcopy.go should be created.</p><p>Our custom conversion function will be used because they are defined in the same package, this can be seen if you search for it in the zz_generated.conversion.go. If you do that, you will also notice a compile error depending on you IDE in the following section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fda66608e5891f52ba43ddb2a7c64b9/href">https://medium.com/media/3fda66608e5891f52ba43ddb2a7c64b9/href</a></iframe><p>This is because we didn’t define our localSchemaBuilder. To do that, create two files, “pkg/apis/baz/register.go” and “pkg/apis/baz/v1alpha1/register.go”. Inside these files we’re going to define the localSchemaBuilder and the functions that will register our resources to a given schema.</p><p>Inside the pkg/apis/baz/v1alpha1/register.go add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c78ec168372946d2197f264f992763/href">https://medium.com/media/09c78ec168372946d2197f264f992763/href</a></iframe><p>Inside the pkg/apis/baz/register.go add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7455369a026065abe680faededbed6e6/href">https://medium.com/media/7455369a026065abe680faededbed6e6/href</a></iframe><p>Now our API types are defined and we are correctly generating all the code. Last thing remaining is to call the addKnownTypes function to effectively register our API resources. Lets create a folder pkg/apis/baz/install and inside it create a file called install.go, inside that file paste the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34eaeeb9055ff7c03ff418c00a23e695/href">https://medium.com/media/34eaeeb9055ff7c03ff418c00a23e695/href</a></iframe><p>In the second part of this tutorial, this package will be used to install our resources in the custom API schema.</p><h4><strong>Defaulting:</strong></h4><p>You may want to define default values for some of the resources fields, if this is the case, inside the pkg/apis/baz/v1alpha1 folder, or inside the folder of whatever external version you want to define the default values, create a file called defaults.go and place the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17f9b52a66bfffef3b4e09368fd7cbf1/href">https://medium.com/media/17f9b52a66bfffef3b4e09368fd7cbf1/href</a></iframe><p>The “SetDefaults” functions name follows the template:</p><ul><li>SetDefaults_{structure name}</li></ul><p>They are used to set the default values for the structures defined inside the same package.</p><p>If you run the codegen again, you will notice that this function will be used inside the zz_generated.defaults.go file. Defaults for the internal versions are not needed since they are created from the external version and will consequently inherit their default values.</p><h3>Last remarks</h3><p>If you want to take a look at the complete code of this series, it can be found on the following github repository:</p><p><a href="https://github.com/Marcos30004347/kubernetes-posts">GitHub - Marcos30004347/kubernetes-posts</a></p><p>In the second part of this tutorial we are going to continue writing the code started here by adding the Admission plugins, Server Initialization, Registry, Strategy and finally being able to compile and run our server in a standalone form.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60526e141a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configurando uma API REST + GraphQL com Fastify!]]></title>
            <link>https://medium.com/nosebitz/configurando-uma-api-rest-graphql-com-fastify-5f00805baae9?source=rss-4a2fb51caee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f00805baae9</guid>
            <dc:creator><![CDATA[Marcos Vinicius Moreira Santos]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 17:53:19 GMT</pubDate>
            <atom:updated>2019-12-05T17:53:19.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7DGBBNweITXY_8qn9ZnZQ.jpeg" /></figure><p>Eae Pessoal, belê? Hoje vou apresentar para vocês o <a href="https://github.com/fastify/fastify">Fastify</a> que é conhecido por ser o web framework mais rápido do NodeJS no momento.</p><p>Vamos fazer isso criando um servidor simples capaz de suportar requisições REST e GraphQL.</p><h4>Mas o que é o Fastify?</h4><p><a href="https://github.com/fastify/fastify">Fastify</a> é um web frameword para NodeJS que está se popularizando cada vez mais em decorrência de sua velocidade, simplicidade e por ser um framework extremamente bem testado em todos os sistemas operacionais.</p><h4>Introdução</h4><p>Para fornecer alguma introdução ao framework, vamos iniciar criando uma API REST simples usando alguns recursos básicos do <a href="https://github.com/fastify/fastify">Fastify</a>. Depois disso, faremos a integração entre nosso servidor e o Apollo Server para que também possamos fazer requisições GraphQL.</p><h4>API REST:</h4><p>Primeiro de tudo, criaremos o projeto e instalaremos o <a href="https://github.com/fastify/fastify">Fastify</a>:</p><pre>npm install fastify</pre><p>Após isso podemos definir um arquivo <em>index.js</em> para nosso servidor:</p><pre><strong>const</strong> fastify = <strong>require</strong>(‘fastify’)({ logger: true })</pre><pre>fastify.get(‘/’, <strong>async</strong> (request, reply) =&gt; ({ hello: ‘world’ }));</pre><pre><strong>const</strong> run = <strong>async</strong> () =&gt; {</pre><pre><strong>  try</strong> {</pre><pre><strong>    await</strong> fastify.listen(3000)</pre><pre>    fastify.log.info(`Server escutando na porta          ${fastify.server.address().port}`);</pre><pre>  } <strong>catch</strong> (err) {</pre><pre>    fastify.log.error(err);</pre><pre>    process.exit(1);</pre><pre>  }</pre><pre>}</pre><pre>run();</pre><p>Agora você pode rodar seu servidor:</p><pre>node index.js</pre><p>E pronto, já temos um servidor rodando, você pode testá-lo fazendo uma requisição:</p><pre>curl <a href="http://localhost:3000/">http://localhost:3000</a></pre><p>Repare no Terminal que o <a href="https://github.com/fastify/fastify">Fastify</a> já nos retorna alguns logs, isso faz sentido já que ativamos essa opção durante a instanciação do servidor:</p><pre><strong>const</strong> fastify = <strong>require</strong>(‘fastify’)({ logger: true })</pre><p>Logs:</p><pre>…</pre><pre>{“level”:30,”time”:1574869668814,”pid”:21953,”hostname”:”MBP-de-Marcos”,”msg”:”Server listening at http://127.0.0.1:3000&quot;,&quot;v&quot;:1}</pre><pre>{“level”:30,”time”:1574869668815,”pid”:21953,”hostname”:”MBP-de-Marcos”,”msg”:”Server escutando na porta 3000&quot;,”v”:1}</pre><pre>{“level”:30,”time”:1574869681912,”pid”:21953,”hostname”:”MBP-de-Marcos”,”reqId”:1,”req”:{“method”:”GET”,”url”:”/”,”hostname”:”localhost:3000&quot;,”remoteAddress”:”127.0.0.1&quot;,”remotePort”:52897},”msg”:”incoming request”,”v”:1}</pre><pre>{“level”:30,”time”:1574869681921,”pid”:21953,”hostname”:”MBP-de-Marcos”,”reqId”:1,”res”:{“statusCode”:200},”responseTime”:8.021118998527527,”msg”:”request completed”,”v”:1}</pre><pre>…</pre><p>O <a href="https://github.com/fastify/fastify">Fastify</a> usa o pino(<a href="https://github.com/pinojs/pino">https://github.com/pinojs/pino</a>) como logger por default, caso queira você pode alterá-lo e usar um de sua preferência, vá em <a href="https://www.fastify.io/docs/latest/Logging/">https://www.fastify.io/docs/latest/Logging/</a> para mais detalhes.</p><p>Bem… Nosso servidor ainda não está muito interessante certo? Vamos deixa-lo um pouco mais robusto, mas primeiro temos que falar um pouco sobre uma das features mais poderosas do <a href="https://github.com/fastify/fastify">Fastify</a>, os plugins.</p><h4>Plugins:</h4><p>O <a href="https://github.com/fastify/fastify">Fastify</a> permite que você estenda suas funcionalidades usando o método:</p><pre>fastify.register(<strong>plugin</strong>, [options])</pre><p>Aqui podemos passar dois parâmetros, o primeiro é o plugin, e o segundo é um conjunto de opções que contém alguns parâmetros usados pelo <a href="https://github.com/fastify/fastify">Fastify</a> durante o registro, e caso o autor queira, ele pode estender as opções para uso interno.</p><p>O <a href="https://github.com/fastify/fastify">Fastify</a> faz uso de dois parâmetros, logLevel e prefix, neste exemplo será relevante para nós somente “prefix”, que indica o prefixo sobre o qual o plugin será registrado, explicaremos esse parâmetro melhor um pouco mais a frente.</p><p>Agora, para deixar nosso servidor um pouco mais interessante, vamos registrar um plugin chamado fastify-sensible (<a href="https://github.com/fastify/fastify-sensible">https://github.com/fastify/fastify-sensible</a>) que irá adicionar ao <a href="https://github.com/fastify/fastify">Fastify</a> diversos métodos utilitários, também adicionaremos o fastify-autoload (<a href="https://github.com/fastify/fastify-autoload">https://github.com/fastify/fastify-autoload</a>), um plugin utilizado para registrar outros plugins de forma dinâmica.</p><pre>npm install fastify-sensible</pre><pre>npm install fastify-autoload</pre><p>Utilizaremos o autoload para registrar novas rotas ao servidor, para isso, criaremos uma pasta chamada /rest que conterá duas outras pastas, /public e /private, adicionaremos um endpoint em cada uma dessas pastas e faremos alguma validação somente no endpoint que estiver sobre /private.</p><pre><strong>index.js</strong></pre><pre>/rest</pre><pre>    /public</pre><pre>         <strong>hello.js</strong></pre><pre>    /private</pre><pre>         <strong>hello.js</strong></pre><p><em>/rest/public/hello.js:</em></p><pre>function hello(fastify, _opts, next) {</pre><pre>fastify.get(“/hello”, (req, res) =&gt; {</pre><pre>   res.send({ message: “Olá pra você de uma rota pública!” });</pre><pre>});</pre><pre>  next();</pre><pre>}</pre><pre>module.exports = hello;</pre><p><em>/rest/private/hello.js:</em></p><pre>function hello(fastify, _opts, next) {</pre><pre>fastify.route({</pre><pre>method: ‘GET’,</pre><pre>url: ‘/hello’,</pre><pre>preHandler: <strong>async</strong> (req, _res) =&gt; {</pre><pre>fastify.log.info(“autorizando…”);</pre><pre>fastify.assert(</pre><pre>req.headers.authorization === “password”,</pre><pre>400,</pre><pre>“Beeeh”</pre><pre>);</pre><pre><strong>return</strong>;</pre><pre>},</pre><pre>handler: <strong>async</strong> (req, reply) =&gt; {</pre><pre><strong>return</strong> { message: “Olá pra você de uma rota privada!” };</pre><pre>}</pre><pre>})</pre><pre>next();</pre><pre>}</pre><pre>module.exports = hello;</pre><p>No nosso exemplo, usamos os plugins para registrar duas rotas, a primeira é um endpoint /hello em public que irá responder “Olá pra você de uma rota pública!” e a outra é um outro endpoint /hello em private que irá responder “Olá pra você de uma rota privada!” em caso de a requisição conter o header “authorization” com o valor “password”, se isso não acontecer, um erro com código 400 será retornado com uma mensagem “<em>Beeeh</em>”.</p><p>Utilizamos o <a href="https://github.com/fastify/fastify/blob/master/docs/Hooks.md">hook</a> “preHandler” para fazer a autenticação, nosso foco aqui não é a segurança, mas o exemplo ainda é válido háhá.</p><p>Você pode reparar que essa é a declaração padrão de um plugin no <a href="https://github.com/fastify/fastify">Fastify</a>:</p><pre><strong>function</strong> plugin(fastify, opts, next) {</pre><pre><em>// Do something…</em></pre><pre>next();</pre><pre>}</pre><p>O primeiro parâmetro passado é a instância do <a href="https://github.com/fastify/fastify">Fastify</a>, o segundo é um conjunto de opções, e o terceiro é um callback que quando for chamado dirá ao servidor que o registro do plugin foi feito com sucesso.</p><p>Agora que já definimos nossas rotas públicas e privadas, podemos adicionar ao nosso <em>index.js</em> o código:</p><pre>fastify.register(require(‘fastify-sensible’));</pre><pre>fastify.register(require(‘fastify-autoload’), {</pre><pre>dir: path.join(__dirname, ‘rest’),</pre><pre>options: {</pre><pre><strong><em>/**</em></strong></pre><pre><strong><em>* Aqui definimos que os plugins carregados através</em></strong></pre><pre><strong><em>* do autoload serão registrados sobre o prefixo</em></strong></pre><pre><strong><em>* /api</em></strong></pre><pre><strong><em>*</em></strong></pre><pre><strong><em>* Como temos 2 plugins em /rest, um dentro de /public,</em></strong></pre><pre><strong><em>* e outro dentro de /private, ambos registrando</em></strong></pre><pre><strong><em>* endpoints /hello, teremos após p registro desse plugins</em></strong></pre><pre><strong><em>* 2 enpoints em nosso servidor.</em></strong></pre><pre><strong><em>*</em></strong></pre><pre><strong><em>* /api/public/hello</em></strong></pre><pre><strong><em>* /api/private/hello</em></strong></pre><pre><strong><em>**/</em></strong></pre><pre>prefix: ‘/api/’</pre><pre>},</pre><pre>});</pre><p>Primeiramente, registramos o fastify-sendible já que iremos utilizar o método fastify.assert registrado por ele dentro de uma das rotas. Em seguida, registramos o fastify-autoload sobre o prefixo /api/ passando como parâmetro o diretório /rest em que definimos nossas rotas, logo, o fastify-autoload irá utilizar nossa estrutura de pastas como prefixo para registrar os novos plugins. Estes novos plugins, por sua vez, registram endpoints REST sobre o prefixo /hello, logo após o registro do autoload, teremos as rotas /api/public/hello e /api/private/hello em nosso servidor.</p><h4>GraphQL:</h4><p>Agora vamos integrar nosso servidor com o Apollo, faremos uso de um plugin chamado <a href="https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-fastify">apollo-server-fastify</a> desenvolvido pela galera do Apollo.</p><p>Primeiramente, instalaremos o plugin:</p><pre>npm install apollo-server-fastify</pre><p>Agora podemos adicionar ao nosso<em> index.js</em>:</p><pre><strong>const</strong> { ApolloServer } = <strong>require</strong>(‘apollo-server-fastify’);</pre><pre><strong>const</strong> server = <strong>new</strong> ApolloServer({});</pre><pre>fastify.register(server.createHandler());</pre><p>Pronto, já temos uma instância do Apollo integrada no servidor, porém, ele ainda não faz muita coisa, vamos adicionar algumas querys para deixá-lo um pouco mais interessante.</p><p>Criaremos uma pasta chamada <em>graphql/</em> e adicionaremos dois arquivos:</p><pre><em>graphql/</em></pre><pre>   <strong>typeDefs.js</strong></pre><pre>   <strong>resolvers.js</strong></pre><p><em>typeDefs.js:</em></p><pre><strong>const</strong> { gql } = <strong>require</strong>(‘apollo-server-fastify’);</pre><pre><strong>const</strong> typeDefs = gql`</pre><pre><em>type Book {</em></pre><pre><em>title: String</em></pre><pre><em>author: String</em></pre><pre><em>}</em></pre><pre><em>type Query {</em></pre><pre><em>books: [Book]</em></pre><pre><em>}</em></pre><pre>`;</pre><pre>module.exports = {</pre><pre>typeDefs,</pre><pre>}</pre><p><em>resolvers.js:</em></p><pre><strong>const</strong> books = [</pre><pre>{</pre><pre>title: ‘Harry Potter and the Chamber of Secrets’,</pre><pre>author: ‘J.K. Rowling’,</pre><pre>},</pre><pre>{</pre><pre>title: ‘Jurassic Park’,</pre><pre>author: ‘Michael Crichton’,</pre><pre>},</pre><pre>];</pre><pre><strong>const</strong> resolvers = {</pre><pre>Query: {</pre><pre>books: () =&gt; books,</pre><pre>},</pre><pre>};</pre><pre><strong>module.exports</strong> = {</pre><pre>resolvers,</pre><pre>}</pre><p>Agora basta adicionar as configurações do nosso ApolloServer:</p><pre><strong>const</strong> { resolvers } = <strong>require</strong>(“./graphql/resolvers”);</pre><pre><strong>const</strong> { typeDefs } = <strong>require</strong>(“./graphql/typeDefs”);</pre><pre><strong>const</strong> server = <strong>new</strong> ApolloServer({</pre><pre>typeDefs,</pre><pre>resolvers,</pre><pre>introspection: true,</pre><pre>playground: true,</pre><pre>tracing: true,</pre><pre>});</pre><p>Pronto, você já pode executar as querys!</p><p>Repare que ativamos 3 opções, introspection, playground e tracing. Essas são opções úteis para debugging e caso você vá no seu browser no endereço <a href="http://localhost:3000/graphql">http://localhost:3000/graphql</a> você terá uma interface gráfica para testar suas querys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zHF8zhDvqmC9N8yN" /></figure><p>Repare que o plugin já adiciona para nós o prefixo <em>/graphql</em> por trás dos panos, você pode alterá-lo nas configurações caso precise.</p><h4>Conclusão:</h4><p>Bom, agora já temos uma API simples que pode receber requisições REST e GraphQL.</p><p>Por hoje é tudo pessoal, se vocês quiserem, podem checar o código no github:</p><p><a href="https://github.com/Marcos30004347/fastify-medium">https://github.com/Marcos30004347/fastify-medium</a></p><p>Benchmarks do fastify: <a href="https://www.fastify.io/benchmarks/">https://www.fastify.io/benchmarks/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f00805baae9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nosebitz/configurando-uma-api-rest-graphql-com-fastify-5f00805baae9">Configurando uma API REST + GraphQL com Fastify!</a> was originally published in <a href="https://medium.com/nosebitz">Nosebitz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>