<?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[Scum-Gazeta - Medium]]></title>
        <description><![CDATA[Technical notes and reflections on programming - Medium]]></description>
        <link>https://medium.com/scum-gazeta?source=rss----e57d89036328---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Scum-Gazeta - Medium</title>
            <link>https://medium.com/scum-gazeta?source=rss----e57d89036328---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:32:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/scum-gazeta" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pet-Project]]></title>
            <link>https://medium.com/scum-gazeta/pet-project-1af0bc00aca0?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/1af0bc00aca0</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 20:13:29 GMT</pubDate>
            <atom:updated>2023-12-20T20:23:47.858Z</atom:updated>
            <content:encoded><![CDATA[<h4>R-Stat</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8zeSkaORt4Mb0OHSteZKg.jpeg" /></figure><p>Today, I wanted to tell you about my pet project, which I’ve been working on for several years, and in general, about the benefits of such hobbies.</p><p>You probably guess that such projects bring certain benefits to developers — in it, you can feel like any member of a regular development team:</p><ul><li>Product Owner</li><li>Software Architect</li><li>SRE/DevOps</li><li>QA</li><li>Frontend dev</li><li>Backend dev</li></ul><p>And if your product is really useful, you’re lucky to work with real clients, their needs, requests, and complaints.</p><p>The most challenging part, of course, is to come up with an idea that will solve someone’s problems. But if nothing sensible comes to mind, start with solving your own problems. Of course, there are already enough to-do lists and calculators in life, so list your own problems and routines and try to solve or automate them.</p><p>The second positive aspect is technology. In our technical world, there are too many fascinating and useful things that you need to see or try — you won’t be able to do everything, but you must use something different from your standard working stack. Experience is a broad outlook; you should be able to choose and experiment — a pet project is the best place for experiments.</p><p>A bit about my project. I love sports; I have been involved in and continue to engage in various sports. Consequently, my interests found realization in my product. I wrote a system that helps you organize competitions for team sports (football, hockey, etc.). My system helps you create a competition structure according to the regulations, register all participants, and keep track of game statistics. It can simply fill your website with sports-related content and more, such as news, videos, photos, and so on. In general, it’s a find for those who want to organize competitions of any size.</p><p>But since we are engineers, I would like to delve a bit more into the technical aspects of my project.</p><h3>Business Logic</h3><p>Well, my solution is capable not only of organizing competitions from scratch but also of storing existing and publicly available competitions. For this purpose, I use parsers that crawl popular sports websites and gather all the necessary information about them — teams, players, matches, and their calendars. And most importantly, protocols of completed games.<br>Later, when I gathered enough data, I wanted to process it with AI and make predictions for upcoming games. However, the main purpose is to allow the creation and organization of competitions from scratch. You upload players, and teams, create a calendar, and start playing. That’s it! Of course, don’t forget to enter scores and protocols, and you will definitely have statistics that I can easily provide to your website through an API.<br>This is implemented with the help of another cool product of mine — <a href="https://github.com/ihippik/wal-listener">Wal-Listener</a>. As soon as new information about played matches appears in the database, the heart of the project, the Stat Processor, receives a message about it and starts counting statistics. This is my main Coca-Cola formula :)<br>In addition to all this, I have Telegram notifications connected. For example, I can direct my parsers to a website with the World Cup, and as soon as the scores change in the games or the regular time ends, I will receive a notification.<br>Currently, I support only football and hockey, but implementing any other team sport will not be difficult for me — clean architecture and clean code will help me do it in the shortest possible time. <strong>Feel free to reach out!</strong></p><h3>Infrastructure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGKro4k1Taeb3Ssrvkv4qw.png" /></figure><p>I chose <a href="https://www.hetzner.com/cloud">Hetzner Cloud </a>— no managed solutions, let’s do it ourselves. Only servers, networks, volumes, and a firewall. I used infrastructure as code — <a href="https://www.terraform.io/">Terraform</a> is a fantastic tool for this.</p><p>As the orchestrator for my applications, I use <a href="https://kubernetes.io/">Kubernetes</a> — I’m a big DevOps fan, and there’s no alternative here. I even consider writing an Operator for my project at the application level and a <a href="https://www.terraform.io/">Terraform</a> provider at the infrastructure level. It’s a bare-metal cluster that I deployed using <a href="https://github.com/kubernetes-sigs/kubespray">Kubespray</a> — I have a separate <a href="https://medium.com/scum-gazeta/kubernetes-cluster-production-ready-6ba1bab5533d">article</a> about it. The Ingress controller/load balancer is implemented using the excellent modern tool — <a href="https://traefik.io/traefik/">Traefik</a>.</p><p>My private repositories are on <a href="https://about.gitlab.com/">GitLab</a>, so I can use their powerful GitLab CI — as the implementation of CI/CD processes, but perhaps it’s worth getting closer to people and moving to the lighter <a href="https://github.com/features/actions">GitHub Actions</a>. I mainly use clean manifests, but I’m gradually moving to <a href="https://helm.sh/">Helm</a>. Secrets should move from regular secrets to <a href="https://www.vaultproject.io/">Vault</a> soon, but maybe regular <a href="https://github.com/bitnami-labs/sealed-secrets">Sealed Secrets</a> from Bitnami would be more suitable for GitOps.</p><p>For logs, I use the <a href="https://github.com/grafana/helm-charts">Loki stack</a>, <a href="https://github.com/prometheus-community/helm-charts">Prometheus</a> for metrics, and a configured alert manager with notifications in <a href="https://web.telegram.org/">Telegram</a>. Also, for error aggregation, I use <a href="https://sentry.io/">Sentry</a>.</p><p>As you know, GitLab has its own container registry, but at one point, the runners deployed in my Kubernetes cluster were blocked (I understand that IPs were blacklisted) — I lost the ability to store images of my services in the centralized GitLab storage. This is the best moment to switch to <a href="https://aws.amazon.com/ecr/">Amazon ECR</a>. I’ve wanted to use their services as a grown-up for a long time, but due to the cost, I used only the cheapest. I also used S3 to store database backups, which were kindly prepared for K8S CronJob.</p><p>In the GitOps framework, I also use <a href="https://argo-cd.readthedocs.io/en/stable/">ArgoCD</a>, but until I have large clients, I can neglect them and sometimes deploy manifests from the JetBrains plugin.</p><p>For network access, instead of the classic IngressController, I use <a href="https://traefik.io/traefik/">Traefik</a>, and not just because it’s written in Go — it also has very flexible settings.</p><h3>Architecture</h3><p>What are the key points we can see here?</p><p>The programming language I use is Golang, and I had several parser services in Python (Beautiful Soup) before, but I’ve long since rewritten them in Go. I plan to implement remote configuration in <a href="https://etcd.io/">Etcd</a> for all services, and I think I’ll do it soon.</p><p>The services are interconnected with the <a href="https://nats.io/">NATS</a> data bus — a powerful and easy-to-configure message broker. This simplifies the process of scaling and ensuring the availability of the service overall. I might have used <a href="https://kafka.apache.org/">Kafka</a> — I love its scalability model, but Java solutions are currently discouraging me, and NATS is just a single binary, you understand, written on what. For this reason, we’ve already moved away from the <a href="https://www.elastic.co/elastic-stack">ELK</a> stack.</p><p>Another architectural decision is the use of two gateways for two different purposes (API for client websites and API for the management system). The task is to divide traffic between two different gateways, each of which has its own settings, access levels, and goals.</p><p>Also, the idea of Kafka Connect gave rise to two senders in my system — one for sending Telegram messages, the other for working with WebSocket notifications. All we need to do is simply send a message to the appropriate topic.</p><h3>Security Considerations</h3><p>Perhaps discussing this is a new attack vector, but let’s consider it as my personal Honeypot. There is certainly a lot of work to be done, but some things have already been implemented.</p><p>The first and most important is, of course, the use of TLS, and I don’t buy certificates for my domains but use <a href="https://letsencrypt.org/">LetsEncrypt</a>. Obtaining these certificates is automated with <a href="https://cert-manager.io/">CertManager</a>. HTTP traffic should be redirected to the HTTPS protocol.</p><p>As for authentication and authorization, I use two API Gateways (<a href="https://www.krakend.io/">KrakenD</a>) for these purposes. One for external clients and the other for internal use. They have different access levels and, accordingly, different settings, but the general principle is the same. I have implemented an IdentityProvider service that issues <a href="https://jwt.io/">JWT</a> tokens to registered users, signed with an <a href="https://en.wikipedia.org/wiki/RSA_(cryptosystem)">RSA</a> private key. The API Gateway then verifies these tokens using the provided public keys in the form of <a href="https://datatracker.ietf.org/doc/html/rfc7517">JWK</a>.</p><p>The network security is handled by the firewall; all ports except standard ones should be closed by it. Sometimes I need remote access to my infrastructure, for example, to the database — in these cases, I set up temporary port forwarding, but in normal conditions, all their ports are closed to the world.</p><p>Of course, I have several endpoints necessary for observing my system. <a href="https://grafana.com/">Grafana</a> dashboards, <a href="https://prometheus.io/">Prometheus</a> admin interfaces and its Alert Manager, Load Balancer dashboard, and ArgoCD — all this data is required in defense, especially those that do not require a password for access. <a href="https://doc.traefik.io/traefik/https/tls/">MutualTLS</a> of Traefik and my self-signed certificates work well here.</p><p>User action auditing is not yet implemented, but I have long wanted to do it with the familiar <a href="https://clickhouse.com/">Clickhouse</a>. However, for the sake of exploring new technologies, I want to try using <a href="https://cassandra.apache.org/">Cassandra</a>. Its resemblance to Apache has made its distributed model similar to <a href="https://kafka.apache.org/">Kafka</a>, which again makes it a more preferable choice for me.</p><h3>Frontend</h3><p>I have a complex frontend written in <a href="https://react.dev/">React</a>/<a href="https://react-redux.js.org/">Redux</a>, using the <a href="https://mui.com/">Material Design</a> library as a bootstrap. After transitioning to go modules, working with npm was quite frustrating. I remember how, after long breaks, I tried to update dependencies, for example, switch to a new version of React, and everything else refused to work.</p><p>Maybe when I have time, I’ll try transitioning to Vue.</p><p>I used to dabble a bit in <a href="https://www.qt.io/">QT</a>, and I had a dream of creating a desktop version of my site, but now I’m not sure if I’ll ever have time for that.</p><p>But overall, this whole full-stack vibe gives me the feeling that you control everything, from updating the cluster and the number of backups to the color of your buttons. However, you fully pay for it with your time — a pet project is a black hole that swallows everything :)</p><h3>Bonus</h3><p>For those who have read to the end, a small bonus. Let’s count how many products and technologies written in Golang, aside from my services, I use in my project?</p><ul><li><a href="https://kubernetes.io/">Kubernetes</a></li><li><a href="https://www.docker.com/">Docker</a></li><li><a href="https://prometheus.io/">Prometheus</a></li><li><a href="https://traefik.io/traefik/">Traefik</a></li><li><a href="https://www.jaegertracing.io/">Jaeger</a></li><li><a href="https://nats.io/">NATS</a></li><li><a href="https://cert-manager.io/">Cert Manager</a></li><li><a href="https://etcd.io/">Etcd</a></li><li><a href="https://www.vaultproject.io/">Vault</a></li><li><a href="https://www.krakend.io/">KrakenD</a></li><li><a href="https://argo-cd.readthedocs.io/en/stable/">ArgoCD</a></li><li><a href="https://helm.sh/">Helm</a></li><li><a href="https://grafana.com/">Grafana</a></li><li><a href="https://docs.gitlab.com/runner/">Gitlab Runner</a></li></ul><p>Impressive, isn’t it?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1af0bc00aca0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/pet-project-1af0bc00aca0">Pet-Project</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Lambda Infrastructure in Go]]></title>
            <link>https://medium.com/scum-gazeta/how-to-build-a-lambda-infrastructure-in-go-6ec5341dd10f?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/6ec5341dd10f</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 20:27:10 GMT</pubDate>
            <atom:updated>2023-09-09T20:49:14.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joRJQQWuhBhnEvQ0Z7xnXA.jpeg" /></figure><h3>Introduction</h3><p>I really enjoy it when engineers create their own versions of popular solutions. One article where they created their own Kubernetes is worth reading!</p><p>I already <a href="https://medium.com/scum-gazeta/writing-your-own-postgresql-driver-ebd5fd6d187d">made</a> a driver for PostgreSQL, and now I decided to take on the holy grail: <a href="https://aws.amazon.com/">AWS</a></p><p>When I took the exam for the AWS-Developer certificate, I was impressed that they have all the solutions you could ever dream of. But how they work, I was lucky not to be asked about that. It’s time to figure it out.</p><p>Let’s dream a little.</p><p>So I decided to travel back in time for 10 years and start my cloud empire. I decided to start with the game-changer: Lambda.</p><p>Of course, if you go back to the future and compare how far AWS has come in that time, you’ll be surprised. But 10 years ago, my solution would have changed the rules of the game in development.</p><p>Golang has been around for a few years, and Docker is just about to appear. I would immediately enter the market with my <a href="https://github.com/ihippik/lambda-go">product</a>.</p><p>Let’s compare what AWS has now and what I had 10 years ago:</p><pre>| Function                      | AWS-Lambda | Lambda-Go    |<br>|-------------------------------|------------|--------------|<br>| Serverless computing          | yes        | yes          |<br>| Events                        | all        | HTTP         |<br>| Various programming languages | yes        | Golang       |<br>| Flexible scalability          | yes        | One instance |<br>| Development period            | 10 years   | 1 day        |</pre><h3>Bitter truth</h3><p>Okay, enough joking around — let’s be serious now. Let’s see how it works for me.</p><p>Of course, I chose the simplest architectural solution, and the project is currently in its early stages. I want to bring it to production and implement the missing functionality — but I will need your architectural help! I probably could have made a mistake in my implementation, so I would be happy to get any feedback.</p><p>It all started with the fact that I was very interested in how AWS services work, in particular Lambda. I Googled, but I couldn’t find anything specific — only assumptions about how it probably works:</p><p><a href="https://www.bschaatsbergen.com/behind-the-scenes-lambda/">https://www.bschaatsbergen.com/behind-the-scenes-lambda/</a></p><p><a href="https://matthewleak.medium.com/aws-lambda-under-the-hood-how-lambda-works-43efba14d899">https://matthewleak.medium.com/aws-lambda-under-the-hood-how-lambda-works-43efba14d899</a></p><p>AWS is a big player and it appears to be isolating its processes using virtualization and <a href="https://github.com/firecracker-microvm/firecracker">Firecracker</a>, all I had at the time was the fact that the term “cold function start” led me to believe that it was containerization, and that was fine with me.</p><h3>The plan in my head was as follows</h3><ol><li>The user prepares a simple Go program and uploads it to the server.</li><li>The server builds an image based on the program and creates a container from it.</li><li>When the user wants to use their function, they make an HTTP request to it.</li><li>The server starts the prepared container, proxies the request to it, gets the response, and then stops the container.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VpE-2SRS8UWCE0aqtRq0Gg.jpeg" /></figure><p>Only 4 steps, but of course each one has some pitfalls.</p><h4>Function preparation</h4><p>I didn’t reinvent the wheel, and I started with the existing AWS <a href="https://github.com/aws/aws-lambda-go">library</a>.</p><p>The library supports different signature options, which I think is due to the different types of events that Lambda supports. For example, for queues, you probably don’t need to do anything other than acknowledge the event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed2c0897df2a13ecd6cd5de6a1db3c88/href">https://medium.com/media/ed2c0897df2a13ecd6cd5de6a1db3c88/href</a></iframe><p>But I only left myself one signature which is very well suited for HTTP:</p><pre>type Handler func(ctx context.Context, payload []byte) ([]byte, error)</pre><p>As a result, we get the code that is already familiar to us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dba04a121e3cb059fb8ceb957675a62/href">https://medium.com/media/5dba04a121e3cb059fb8ceb957675a62/href</a></iframe><h4>Preparing artifacts for the Docker</h4><p>At first, I thought that using the Docker API would be overhead because it uses ContainerD under the hood. So I wanted to do the same, but I decided not to waste time and use the Docker API that I am familiar with.</p><p><a href="https://docs.docker.com/engine/api/sdk/examples/">https://docs.docker.com/engine/api/sdk/examples/</a></p><p>In any case, according to clean architecture, this is behind the interfaces and we can change the implementation at any time.</p><p>When a user sends us their Lambda function in a <strong>tar-gz</strong> archive, we unpack it into a folder with a prepared Dockerfile and build the image.</p><p>Once the image is built, we create a container from it. The container is not running yet, but we are almost ready to start it. When creating the container, we expose a random port inside the container and remember it.</p><h4>Proxy user requests</h4><p>When a user requests a Lambda function, we start a pre-prepared container. We then forward the user’s request to the container. We get the response and return it to the user. It’s a simple process, but I added a retry-pattern to wait until the container is ready to receive requests.</p><p>This is a good place to collect metrics that I can use to scale the function in future releases.</p><p>You can familiarize yourself with the final product code in my repository:<br><a href="https://github.com/ihippik/lambda-go">https://github.com/ihippik/lambda-go</a></p><p>The main thing is to remember that it currently has many shortcomings that I will try to follow up on to eliminate, but it is great for the awareness of how complex and interesting the world around us is ❤️</p><h4>My next steps:</h4><p>Here are some ideas I have for code changes, and maybe for a follow-up article:</p><ul><li>write tests :)</li><li>move to <a href="https://kubernetes.io/">Kubernetes</a></li><li>add auto-scaling with <a href="https://keda.sh/">Keda</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ec5341dd10f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/how-to-build-a-lambda-infrastructure-in-go-6ec5341dd10f">How to Build a Lambda Infrastructure in Go</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing your own PostgreSQL driver]]></title>
            <link>https://medium.com/scum-gazeta/writing-your-own-postgresql-driver-ebd5fd6d187d?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/ebd5fd6d187d</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[driver]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 19:22:15 GMT</pubDate>
            <atom:updated>2022-09-30T19:22:15.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*KWvjtot5UdTG0I85NPRkZQ.jpeg" /></figure><p>The most common task is getting data from a database — we all know how to do this very well, but let’s see how it works.<br>You can see all this in a well-documented library, but I will simplify this process for you — focusing only on essential things.</p><p>What do we have to work with the database?</p><ul><li>standard library “<strong>database/sql</strong>”</li><li>various drivers implementing the standard library interface</li></ul><h4>Standard library</h4><p>The main goals of the standard library are described in the doc.txt file</p><ul><li>provide a generic database API</li><li>make type casting / conversions consistent between all drivers</li><li>take on the complexity of implementing some things</li></ul><p>The sense is clear, the general work for all databases is placed in a separate package. And then we just use the implementation (driver) necessary for a particular database.</p><blockquote>Since today we will consider working with a database using PostgreSQL as an example, some of you probably use a fairly popular ORM — <a href="https://github.com/go-pg/pg">https://github.com/go-pg/pg</a>, but if you look at the usage example, you will notice that in the imports there is no standard library.<br>It’s simple — the guys went their own way and did not implement the standard interface, and problems started from here — at least I could not mock work with the repository for tests and had to manage with integration tests. But now the project seems to be already outdated and they ask to use <a href="https://bun.uptrace.dev/">https://bun.uptrace.dev/</a> in which this dependency reappears! Standardization is our common success! :)</blockquote><p>By the way, you can read about mocking a database connection here:</p><p><a href="https://medium.com/scum-gazeta/database-mocking-in-go-5925c2cc1079">Database Mocking in Go</a></p><h3>Driver Implementation</h3><p>I will skip some non-critical points for easier reading — let’s see the driver.</p><p>We start working with the database by connecting to it</p><pre>sql.Open(“driver_name”, connStr)</pre><p>As I already said, there are no specific driver implementations in the standard library — third-party ones are used.</p><p>It usually looks like this in code:</p><pre>_ &quot;github.com/lib/pq&quot;</pre><p>How can you implement this simple approach in Go like plugins at runtime — everything we love so much, global variables, init functions, etc.</p><p>Map with drivers declared globally</p><pre>drivers   = make(map[string]driver.Driver)</pre><p>And then they are initialized by the driver using a method from the standard library</p><pre>func init() {</pre><pre>  sql.Register(&quot;driver_name&quot;, &amp;Driver{})</pre><pre>}</pre><p>Next, we are already trying to use the driver specified when connecting, and if it is not registered, we get a familiar error for everyone.</p><pre>sql: unknown driver `driver_name` (forgotten import?)</pre><p>And if everything is fine, then when working with the database, we will already use a specific implementation of the driver. Today we are just with you and will analyze the principle of its work.</p><p>The first thing that is needed to implement communication between two objects is to develop a protocol. Our program with PostgreSQL needs to communicate in the same language — everything is like in ordinary life. If we want to communicate, we must understand each other.</p><h4>Protocol</h4><p>We go to the PostgreSQL documentation and collect the postulates we need.</p><p><a href="https://www.postgresql.org/docs/current/protocol.html">Chapter 55. Frontend/Backend Protocol</a></p><p>Looking ahead, I was already familiar with this protocol, because I had already worked with logical replication in my open source project:<br><a href="https://github.com/ihippik/wal-listener">https://github.com/ihippik/wal-listener</a></p><p>And logical replication differs from the usual just in that it is the sequential execution of the SQL instructions we need instead of the usual copying of files.</p><p>Let’s put the highlights together</p><ul><li>client and server can communicate with each other via TCP/IP</li><li>the first step is to verify your identity</li><li>next comes the standard interaction — question (SQL) — answer (data)</li></ul><p>Let’s see how the protocol itself looks like</p><ul><li>first byte — message type</li><li>the next 4 bytes are the length of the message</li><li>next comes the message itself — its content depends on the type of message</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*U-c8VS5E7opbj608fqoDyg.png" /></figure><h4>Message type</h4><p>There are several types of messages in the protocol, which you can find here:<br><a href="https://www.postgresql.org/docs/current/protocol-message-formats.html">https://www.postgresql.org/docs/current/protocol-message-formats.html</a><br>In the same section, you can see the format of each type of message (a specific sequence of bytes)</p><p>And here the ability to create a new driver is a few knowledge:</p><ul><li>know the required message types and their format</li><li>be able to parse server responses depending on the message type</li><li>be able to compose your messages and send them to the server</li><li>know the sequence of actions</li></ul><p>This is probably all we need to be successful.</p><h4>Sequencing</h4><p>Of course, we also take the sequence of actions from the documentation<br><a href="https://www.postgresql.org/docs/current/protocol-flow.html">https://www.postgresql.org/docs/current/protocol-flow.html</a></p><ol><li>we form the start message (pass the username and database)</li><li>we authenticate using one of the available methods (in our case, we use the SASL framework, the SCRAM mechanism: <a href="https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer">https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer</a>)</li><li>making a request</li><li>to parse the answer</li></ol><p>Everything else is done for us by the standard library. For example, efficient connection pooling or type casting (PostgreSQL / Golang) using the familiar <em>scanner/valuer</em> interface and much more.</p><h3>Let’s get down to practice</h3><p>Our goal is to make this simple piece of code work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6445d8dbf139b8f7895731803344457/href">https://medium.com/media/f6445d8dbf139b8f7895731803344457/href</a></iframe><p>for this simple table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00385c91654edfe994edcc874452b0f5/href">https://medium.com/media/00385c91654edfe994edcc874452b0f5/href</a></iframe><h3>Driver structure</h3><h4>Driver</h4><p>The main entity that implements the driver interface has an Open method that returns a connection to the database.</p><h4>Connector</h4><p>An entity that implements the interface of the same name from the standard library.<br>As we can see from the name, it is well able to connect to the database.</p><h4>Connection</h4><p>The main workhorse of our driver. This structure contains:</p><ul><li>TCP/IP connection to the DB</li><li>reader to read data from our connection</li><li>configuration in which we store connection parameters for convenience</li></ul><h4>Buffer</h4><p>An entity that helps us prepare a message before sending it over our connection.</p><p>Here we have standard recording methods that help us build a message in protocol format:</p><ul><li>write int32</li><li>write string</li><li>write bytes</li><li>calculate and write message size</li></ul><p>Anyone who has not worked with bytes before should know that for messages containing data longer than one byte, the sequence of bytes is very important.</p><p>Order from oldest to youngest (our version) is called <strong><em>big-endian.</em></strong></p><p>All other information in the novel <em>Gulliver’s Travels</em> :)</p><h4>Rows</h4><p>A structure that helps parse the response with data from the database<br>It also stores the connection to the database and the description of the received data, the type, and the name of each field.</p><h3>Startup message</h3><p>Let’s see how I form it in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24594a257b2918a005c06a60dd7d80d1/href">https://medium.com/media/24594a257b2918a005c06a60dd7d80d1/href</a></iframe><p>This is the only place where we do not need the first byte with the message type — the size comes right away.<br>Empty 4 bytes are written to the size, which will be overwritten at the end of the message.</p><h3>Authentification</h3><p>Here I implemented a minimum, ideally, several authentication mechanisms should be supported.<br>Also, I did not get into the process of this mechanism itself — I took a ready-made library for this using the example of one of the drivers.</p><p><a href="https://mellium.im/sasl/">https://mellium.im/sasl/</a></p><p>It remains our responsibility only to prepare messages of the required type and read the server’s response, and the result of this work should be approved by the server (<em>AuthenticationOk</em>), which will allow us to make SQL-query already. In case of failure, we can get an <em>ErrorResponse.</em></p><h3>Making a request</h3><p>First of all, we will substitute all the arguments in the request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9263c7ba8d0327d9e58384c32af20e3d/href">https://medium.com/media/9263c7ba8d0327d9e58384c32af20e3d/href</a></iframe><p>Here we write the first byte of the message type (also 4 bytes message size), which means the beginning of the request<br>then the query itself in text format, we calculate the size of the message and send it.</p><h4>Read the answer</h4><p>First of all, we must read the message with the description of the fields (<em>RowDescription</em>), and the data which we will further receive in the <em>Next</em> and <em>Scan</em> method.</p><p>The description consists of the column name and its type.</p><p>We have a <strong><em>Rows</em></strong> structure that we all know has as a <strong><em>Next</em></strong> method.</p><p>The Next method simply reads the next piece from the reader connection of data row by row until it encounters <strong><em>EOF</em></strong><em> </em>and returns <strong><em>false</em></strong>.</p><p>Because we already know the types of each column (<strong><em>OID</em></strong>) that we got from the description and size in bytes of each column we can easily bring each type of PostgreSQL to a similar one in Golang and pass this array to the standard library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fb6834dc1002ea89db275d92c71567d/href">https://medium.com/media/0fb6834dc1002ea89db275d92c71567d/href</a></iframe><p>Here I’m only interested in two types because I have only two columns in the table.</p><h3>Wireshark</h3><p>Let’s see what our communication looks like from the outside. We will look at the traffic using a sniffer.</p><h4>Startup message</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*NehgVAk5LXkF-6VjdLjcZA.png" /></figure><h4>Authentication</h4><p>SCRAM mechanisms consist of several iterations — I left only the first one. Who cares how it works can read here:</p><p><a href="https://www.rfc-editor.org/rfc/rfc5802">https://www.rfc-editor.org/rfc/rfc5802</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*sq_FW8KGPmzKRtfgaPhtvg.png" /></figure><h4>Request</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*hdyIPAWfaJCT01mcFEmeLA.png" /></figure><h4>Response</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*dUsKvTJOojFJQ8JnK-zOEw.png" /></figure><h3>The result of the work</h3><p>Of course, I had ready-made drivers as an example:</p><ul><li><a href="https://github.com/uptrace/bun">https://github.com/uptrace/bun</a></li><li><a href="https://github.com/lib/pq">https://github.com/lib/pq</a></li></ul><p>Using these examples and documentation, I got my own driver with a minimal set of features.</p><p><a href="https://github.com/ihippik/tiny-driver">https://github.com/ihippik/tiny-driver</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd5fd6d187d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/writing-your-own-postgresql-driver-ebd5fd6d187d">Writing your own PostgreSQL driver</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: simple optimization notes]]></title>
            <link>https://medium.com/scum-gazeta/golang-simple-optimization-notes-70bc64673980?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/70bc64673980</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Sat, 26 Mar 2022 11:03:07 GMT</pubDate>
            <atom:updated>2022-03-26T11:03:07.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HazIk3cciXyiA4EthlZJIA.png" /></figure><p>Today I want to bring to your attention an article on the simplest optimizations in Golang projects.</p><p>To begin with, I wanted to talk a little about the optimizations themselves. We will not discuss the theory, but we will start immediately with practical examples.</p><p>In the era of cloud computing, we often create serverless applications. And if we create them for our pet projects, then the infrastructure maintenance budget comes to the front. If our service is lightly loaded, then it really can be practically free. But if something goes wrong — you will pay a lot for it! And when it comes to money, you will definitely react to it somehow.</p><p>The second case is when you have, for example, your own VPS running several services. And one of them sometimes takes up all the resources, so much so that you cannot access the server via ssh.<br>We move to a Kubernetes cluster, set limits for all our applications and see that some of our applications are restarting — OOM-killer comes and solves the problem of our memory “leaks”.</p><p>Of course, this is not always a leak, it can also be a common overspending of resources, and we will try to avoid this today. And memory leaks are closer to bugs and you can talk about them.</p><blockquote>Too much resource consumption hurts the wallet, which means it requires immediate action.</blockquote><p>Now let’s talk about optimization. I hope you all understand why we do not prematurely optimize and against it?! This is likely to be useless work, since we will need to study the entire application first and your piece of code will most likely not be a bottleneck. We need a quick result, MVP, and only then we will think about his problems.</p><p>Second moment. that every optimization must be justified. That is, each optimization should be built on a <strong>benchmark</strong>. We must prove and show how much profit it brought us.</p><p>You also need to understand that most optimizations complicate the readability of the code. You will have to determine this balance for your projects yourself.</p><p>We have finished with the theory, now let’s look at practical advice grouped by standard entities.</p><h3>Arrays and slices</h3><h4>Allocate memory for slices in advance</h4><p>Try to always use the third parameter: <em>make([]T, 0, len)</em></p><p>If you don’t know the exact amount in advance and the slice is short lived, you can allocate more, as long as the slice doesn’t grow at runtime.</p><h4>Don’t forget to use “copy”</h4><p>We try not to use append when copying or, for example, when merging two or more slices.</p><h4>We iterate correctly</h4><p>If we have a slice with many elements, or with large elements, we try to use “for” or range with a single element. With this approach, we will avoid unnecessary copying.</p><h4>Reusing slices</h4><p>If we need to carry out some kind of manipulation with the incoming slice and return the result, we can return it, but already modified. This way we avoid new memory allocations.</p><h4>We do not leave unused slices</h4><p>If we need to cut off a small piece from a slice and use only it, remember that the main part will also remain with you forever. We use copy for a new piece to send the old one to the GC.</p><h3>Strings</h3><h4>Doing concatenation correctly</h4><p>If gluing strings can be done in one statement, then we use “+”, if we need to do this in a loop, then we use <em>string.Builder</em>. Specify the size for the builder in advance through “Grow”</p><h4>Using transformation optimization</h4><p>Since strings under the hood consist of a slice of bytes, sometimes conversions between these two types allow you to avoid memory allocation.</p><h4>Using Internment</h4><p>We can pool strings, thereby helping the compiler store identical strings only once.</p><h4>Avoiding Allocations</h4><p>We can use a map (concatenation) instead of a composite key, we can use a slice of bytes. We try not to use the <em>fmt</em> package, because all of its functions use reflection.</p><h3>Structures</h3><h4>Avoid copying large structures</h4><p>Small structures in our understanding, these are structures with no more than 4 fields no more than a <em>machine word</em>.</p><p><strong>Standard copy cases</strong></p><ul><li>cast to interface</li><li>receiving and sending to channels</li><li>replacing an entry in a map</li><li>adding an element to a slice</li><li>iteration (range)</li></ul><h4>Avoid accessing struct fields through pointers</h4><p>Dereferencing is expensive, we can do it as little as possible especially in a loop. We also lose the ability to use fast registers.</p><h4>Work with small structures</h4><p>This work is optimized by the compiler, which means it is cheap.</p><h4>Reduce structure size with alignment</h4><p>We can align our structures (arrange the fields in the right order, depending on their size) and thus we can reduce the size of the structure itself.</p><h3>Functions</h3><h4>Use inline functions or inline them yourself</h4><p>We try to write small functions available for inlining by the compiler — it’s fast, but it’s even faster to embed code from functions yourself. This is especially true for <strong>hot path</strong> functions.</p><p><strong>What won’t inlined?</strong></p><ul><li>recovery func</li><li>select blocks</li><li>type declarations</li><li>defer</li><li>goroutine</li><li>for-range</li></ul><h4>Choose your function arguments wisely</h4><p>We try to use “small” arguments, as their copying will be specially optimized. We also try to keep a balance between copying and growing the stack with a load on the GC.<br>Avoid a large number of arguments — let your program use super fast registers (there are a limited number of them)</p><h4>Declaring a named result</h4><p>This seems to be a bit more performant than declaring these variables in the body of the function.</p><h4>Saving intermediate results</h4><p>Help the compiler to optimize your code, save intermediate results and then there will be more options to optimize your code.</p><h4>Use “defer” carefully</h4><p>Try not to use defer, or at least not use it in a loop.</p><h4>Facilitating the “hot path”</h4><p>Avoid allocating memory in these places, especially for short-lived objects. Make the most common branches first (if, switch).</p><h3>Map</h3><h4>Allocate memory in advance</h4><p>Everything is like everywhere else. When initializing the map, specify its size.</p><h4>Using an empty structure as values</h4><p><strong><em>struct{}</em></strong> is nothing, so using this approach for example for signal values is very beneficial.</p><h4>Clearing the map</h4><p>The map can only grow and cannot shrink. We need to control this — reset the maps completely and explicitly, because. deleting all of its elements won’t help.</p><h4>We try not to use pointers in keys and values</h4><p>If the map does not contain pointers, then the GC will not waste its precious time on it. And know that strings are also pointers — use an array of bytes instead of strings for keys.</p><h4>Reducing the number of changes</h4><p>Again, we do not want to use a pointer, but we can use a composite of a map and a slice and store the keys in the map, and in the slice the values ​​that we can already change without restrictions.</p><h3>Interface</h3><h4>Counting memory allocations</h4><p>Remember, to assign a value to an interface, you first need to copy it somewhere and then paste a pointer to it. The keyword is copy. And it turns out that the cost of boxing and unboxing will be approximate to the size of the structure and one allocation</p><h4>Choosing the optimal types</h4><p>There are some cases when there will be no allocations during boxing / unboxing. For example, small and boolean values of variables and constants, structures with one simple field, pointers (<em>map, chan, func</em> including)</p><h4>Avoiding memory allocation</h4><p>As elsewhere, we try to avoid unnecessary allocations. For example, to assign an interface to an interface, instead of boxing twice.</p><h4>Use only when needed</h4><p>Avoid using interfaces in the parameters and results of small, frequently called functions. We do not need extra packing and unpacking.<br>Use interface method calls less frequently, if only because it prevents inlining.</p><h3>Pointers, channels, BCE</h3><h4>Avoid unnecessary dereferences</h4><p>Especially in a loop, because it turns out to be too expensive. Dereferencing is a whole complex of necessary actions that we do not want to perform at our expense.</p><h4>Channel usage is inefficient</h4><p>Channels are slower than other synchronization methods. In addition, the more cases in select, the slower our program. But <em>select, case + default </em>are optimized.</p><h4>Try to avoid unnecessary boundary checks</h4><p>This is also expensive and we should avoid it in every possible way. For example, it is more correct to check (get) the maximum slice index once, instead of several checks. It is better to immediately try to get extreme options.</p><h3>Сonclusion</h3><p>Throughout this article, we see the same optimization rules.</p><p>Help the compiler make the right decision and it will thank you. Allocate memory at compile time, use intermediate results, and try to keep your code readable.</p><p>And i repeat once again that benchmarks are mandatory for implicit optimizations. If only because our compiler changes too much from version to version and what worked yesterday will not work tomorrow and vice versa.</p><p>Don’t forget to use the built-in profiling and tracing tools.</p><p><strong>Good luck with your optimizations!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70bc64673980" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/golang-simple-optimization-notes-70bc64673980">Golang: simple optimization notes</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes-cluster: production ready]]></title>
            <link>https://medium.com/scum-gazeta/kubernetes-cluster-production-ready-6ba1bab5533d?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/6ba1bab5533d</guid>
            <category><![CDATA[loki]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Tue, 26 Oct 2021 17:21:59 GMT</pubDate>
            <atom:updated>2021-11-01T04:20:41.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2q_8-DSCCCColxDzgUUtyg.png" /></figure><blockquote>I had a childhood dream — to have my own Kubernetes cluster, and I fulfilled it!</blockquote><h4>Today’s tech stack</h4><ul><li>Kubernetes</li><li>Helm</li><li>Terraform</li><li>Ansible</li><li>Lens</li><li>Argo-CD</li><li>Prometheus</li><li>Loki</li><li>Traefik</li><li>Gitlab</li></ul><h3>Let`s rock!</h3><p>I have long wanted to use the Kubertnetes cluster for my own purposes. But I didn’t want to use something artificial and single-noded.</p><p>And now I have matured, my pet projects have matured and I thought about the cluster.</p><p>Of course, the easiest start was with managed solutions.</p><p>By that time, I already used the services of a cloud provider, but their solutions with a Kubernetes cluster turned out to be too expensive for pet projects.</p><p>The choice fell on low-cost hosters. And a friend, a DevOPS engineer, suggested <em>Hetzner</em> to me.</p><p><a href="https://www.hetzner.com/cloud">Truly thrifty cloud hosting - Hetzner Online GmbH</a></p><p>Ordering virtual servers is not a problem, but who will configure the cluster?</p><p>The Kubernetes community has already prepared an answer to this question:</p><p><strong><em>Kubespray!</em></strong></p><p>This is a set of Ansible roles for automated cluster configuration.</p><p>The only thing left to do is to write manifests for the deployment of services. We can do it ourselves :)</p><h3>Creating nodes for the cluster</h3><h4>Terraform</h4><p>Here again I got acquainted with the amazing Terraform tool that provide the idea of “infrastructure as a code”.</p><p><a href="https://www.terraform.io/">Terraform | HashiCorp Developer</a></p><p>The process of creating our infrastructure is that we describe its configuration (server, network, firewall), the token of the cloud provider and we get a ready-made, but bare cluster.</p><p>Here is my repository. Customize it for you:</p><p><a href="https://github.com/ihippik/terraform-hetzner">https://github.com/ihippik/terraform-hetzner</a></p><p>Later, you can create additional assets manually, but this is a bit century — please describe your infrastructure in Terraform.</p><h3>Creating a Kubernetes cluster</h3><p>We go to the repository in Kubespray and see <em>Quick Start</em>.</p><p><a href="https://github.com/kubernetes-sigs/kubespray">https://github.com/kubernetes-sigs/kubespray</a></p><p>There are a few simple things to do here:</p><ul><li>install dependencies (Ansible, etc.)</li><li>make a copy for the new cluster from the example</li><li>specify the IP addresses of the nodes created at first stage (together with the master-node)</li><li>if we are good at the subject, then we can adjust the cluster more accurately</li><li>run the Ansible scripts under the root</li></ul><p>It is important that under the root you can get connected to your nodes via ssh. Your key must be on the nodes. Luckily for us, Terraform provides this.</p><p>Do not be alarmed if at startup there are some non-critical errors — I also had them, but despite this my cluster was working.</p><p>Now you can grab your cluster configuration from the master node:</p><blockquote>cat /etc/kubernetes/admin.conf</blockquote><p>With this configuration, you can connect to your Kubernetes cluster from your local computer (remember to replace localhost with the IP master node)</p><p>We now have a fully operational cluster. Let’s set it up now.</p><p><strong><em>Attention</em></strong></p><p><em>This is the most mysterious stage in this entire article. Please follow the instructions on GitHub carefully. At this stage, I made one serious mistake, and I spent a lot of time finding and fixing it:</em></p><p><em>In the cluster settings, I have specified external IP addresses everywhere in the file. And the cluster still worked, but I could not get access to it from the outside. Only the help of qualified specialists corrected the situation.</em></p><h3>Setting up a Kubernetes cluster</h3><h4>Lens</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUL77QJSSVMknSTl8f-pCw.png" /></figure><p>For the first start, it will be quite convenient to use the Lens — IDE to manage the cluster.</p><p><a href="https://k8slens.dev/">Lens | The Kubernetes IDE</a></p><p>It is also, of course, nice to be able to work with the cluster from the console:</p><p><a href="https://kubernetes.io/docs/reference/kubectl/cheatsheet/">kubectl Cheat Sheet</a></p><p>We add cluster configuration that we downloaded from the master node, connect to our cluster and then can use this wonderful product.</p><h4>Prometheus</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naWtruCYhVx-FA4yltIqjQ.png" /></figure><p>Since we will need to monitor not only our services, but also our cluster, we can use Prometheus using kube-prometheus-stack.</p><p><a href="https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack">https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack</a></p><p>But not Prometheus itself will be deployed in the cluster, a separate Pod, which will further deploy Prometheus and <em>alertmanager</em>.</p><p>Our action:</p><ul><li><em>helm repo add prometheus-community </em><a href="https://prometheus-community.github.io/helm-charts"><em>https://prometheus-community.github.io/helm-charts</em></a></li><li><em>helm repo add stable </em><a href="https://charts.helm.sh/stable"><em>https://charts.helm.sh/stable</em></a></li><li><em>kubectl create namespace prometheus</em></li><li>helm install prometheus-community/kube-prometheus-stack — generate-name — namespace prometheus</li></ul><p>If you want, you can set up an alert about various cluster incidents in the <em>alertmanager</em>.</p><h4>Loki</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3-2sIUg9jN6zPa5fYeiIA.png" /></figure><p>We will store and view the logs in Loki, collect them through <em>promtail</em>, and again view them together with our monitoring dashboards in Grafana.</p><ul><li><em>helm repo add loki </em><a href="https://grafana.github.io/loki/charts"><em>https://grafana.github.io/loki/charts</em></a></li><li><em>helm repo update</em></li><li><em>kubectl create namespace loki-stack</em></li><li><em>namespace/loki-stack created</em></li><li><em>helm upgrade — install loki — namespace=loki-stack loki/loki-stack</em></li></ul><p>Next, in Grafana, add a new Loki source and point it to the location of the service. The format is classic for Kubernetes:</p><blockquote>[service]. [Namespace]: [port]</blockquote><p>We get: <em>http: //loki.loki-stack: 3100</em></p><p>And that’s all. From now on, you can view the logs of your Pods in Explorer or make convenient dashboards for them.</p><p>Now. The cluster is ready to receive guests. Guests from Gitlab.</p><h4>Gitlab</h4><p>Many years ago, I was to shy to share my code with the world and used the private repositories of Bitbucket, then Gitlab. Now I’m not shy, but the code is under the NDA, so i continue there :)</p><p>For me, this is the most familiar environment.</p><p><strong>Runner</strong></p><p>We will definitely want to build our projects automatically, for this dirty work we need Gitlab-Runner.</p><p>Install it via Helm: <a href="https://docs.gitlab.com/runner/install/kubernetes.html">https://docs.gitlab.com/runner/install/kubernetes.html</a></p><p>I did this directly from Lens in the Apps section by specifying the Gitlab url and the token in the values.</p><p><strong>Pull-Secret</strong></p><p>If you work with private Gitlab repositories, then <em>kubelet</em> will need to somehow log into the docker registry, from where you will offer him to download application images. To do this, you need to create an object of type Secret.</p><ul><li>create a deploy token</li><li>get base-64 string from it</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e544fef1e7d4dcec974491d984e88331/href">https://medium.com/media/e544fef1e7d4dcec974491d984e88331/href</a></iframe><p>we form a secret that we will use in our manifests</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/887a34f80c323de38c78c6ceb959ff99/href">https://medium.com/media/887a34f80c323de38c78c6ceb959ff99/href</a></iframe><h3>Preparing the cluster for work</h3><h4>Persistent volume</h4><p>If we do not want our data to disappear after restarting the pods of our services, we will have to use persistent storages.</p><p>We will use the driver kindly provided by Hetzner.</p><p>Details here:</p><p><a href="https://github.com/hetznercloud/csi-driver">GitHub - hetznercloud/csi-driver: Kubernetes Container Storage Interface driver for Hetzner Cloud Volumes</a></p><p>Now let’s ask the driver for a small area for our experiments. At least we can order 10Gb.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ee7dfb42c599483e822bc522a94b043/href">https://medium.com/media/7ee7dfb42c599483e822bc522a94b043/href</a></iframe><p>If you need a more flexible solution, try using:</p><p><a href="https://rook.io/">Rook</a></p><h4>Traefik</h4><p>In order to send traffic to the cluster we need to work with Ingresses. The most common solution is NGINX Ingress Controller, but this is a matter of taste and we will use Traefik here since we are Gophers :)</p><p>You could also use Hetzner’s balancer but it is paid.</p><p><a href="https://doc.traefik.io/traefik/providers/kubernetes-crd/">Kubernetes IngressRoute - Traefik</a></p><p>Install it as a DaemonSet:</p><p><a href="https://doc.traefik.io/traefik/getting-started/install-traefik/#use-the-helm-chart">Traefik Installation Documentation - Traefik</a></p><p>Next, we can already use a custom tool for flexible routing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac4aaefce7f326ed1c9e27486cb42851/href">https://medium.com/media/ac4aaefce7f326ed1c9e27486cb42851/href</a></iframe><p>Since I relocate the site, I already had a certificate for https access to the site.</p><p>I already needed keys and chains obtained from LetsEncrypt. I just added them to the cluster. But remember that you will have to update them regularly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef9ecd0ab10593c74fbaa54158d74f44/href">https://medium.com/media/ef9ecd0ab10593c74fbaa54158d74f44/href</a></iframe><p>But the correct solution would be to configure Traefik’s resolver, which will receive and renew certificates for you:</p><p><a href="https://doc.traefik.io/traefik/https/acme/">Traefik Let&#39;s Encrypt Documentation - Traefik</a></p><h4>Argo-CD</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkQl_gmWjQcwf6UaYO0Ncw.png" /></figure><p>Since we are modern people, we will use modern GitOps tools. Argo-CD is a continuous delivery tool for Kubernetes.</p><p><a href="https://argo-cd.readthedocs.io/en/stable/">Argo CD - Declarative GitOps CD for Kubernetes</a></p><p>Put single, it will monitor our manifests and as soon as they change, it will try to apply them in our cluster.</p><p>Everything is simple here:</p><ul><li>create a namespace and deploy Argo there</li><li>make a port-forward for the UI service and go in (we can see the login password in secrets)</li><li>if you are using a private repository, like me, then you will need to suggest how to connect to it. I used Deploy Token.</li><li>create an application</li></ul><p>Argo-CD will now monitor the delivery of our applications. Don’t forget to register <em>IngressRoute</em> to make Argo-CD access nice and convenient.</p><h3>Conclusion</h3><p>Congratulations, now we have our own cluster with the required minimum for work!</p><p>For the cluster, I took inexpensive servers, up to 6 euros — for a home project, it is enough. And our cluster costs less than 20 euros per month.</p><p><strong>PS</strong>: <em>For more professional solutions you need to approach the question more carefully. For example, set up a backup of the etcd storage on the master node. Etc.</em></p><p><em>But for home use it doesn’t cost us anything to complete all the steps in this article again if our cluster breaks :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ba1bab5533d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/kubernetes-cluster-production-ready-6ba1bab5533d">Kubernetes-cluster: production ready</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explaining Gitlab-Runner: research]]></title>
            <link>https://medium.com/scum-gazeta/explaining-gitlab-runner-research-12cbfe9938cd?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/12cbfe9938cd</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 19:05:20 GMT</pubDate>
            <atom:updated>2021-02-18T19:51:48.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mk9Mbbudn0hHtrKZVAnZ0Q.png" /></figure><p>Hi everyone!<br>While doing one of the tasks, I needed to reproduce the logic of the <strong>Gitlab-Runner</strong>. I was delighted, as I had long wanted to understand the logic of its work.</p><p>When I first met the runner, I was delighted, he dutifully followed all my sophisticated instructions. I could log in and arrange the house for myself.<br>Magic? And as it turned out, there is no magic.<br>The only thing that bothered me was my “pending” tasks on common runners :)</p><p>Gitlab-runner is a workhorse that we will use for CI/CD processes.<br>All the tasks for building our go-project, launching linters and tests and subsequent deployment to the service are classic tasks for a runner. You can read about them in the Gitlab <a href="https://docs.gitlab.com/runner/">documentation</a>.</p><p><a href="https://docs.gitlab.com/ee/development/cicd/">Here</a> you can see their role in the overall CI/CD ecosystem.</p><p>Runners are of different types to solve different problems. Namely, they differ in the executer — execution environment.</p><p><a href="https://docs.gitlab.com/runner/executors/README.html">Executors</a></p><ul><li>SSH</li><li>Shell</li><li>Paralels</li><li>VirtualBox</li><li>Docker</li><li>Kubernetes</li><li>Custom</li></ul><p>Here are the types of executors that can even help us solve some specific problems.<br>Today we will look at the simplest of them — the <strong>shell</strong>.</p><blockquote><strong>The Shell executor is a simple executor that you use to execute builds locally on the machine where GitLab Runner is installed.</strong></blockquote><p>The runner is a normal intermediary between Gitlab and an execution environment (<em>executor</em>). We receive a task from Gitlab and send it to execute (<em>shell</em>).</p><p>Gitlab needs to know who it can delegate its job to. Job types can be specified with tags. Runners are marked with the same tags during registration. Thus, we help Gitlab choose the right runner for a specific task.</p><p>Also, runners can have different visibility zones — common, for a group or for a specific project ..</p><p>The first thing we need to do to work with the runner is to install it and register it.<br>Since we are Gophers and the runner is happily written in Go, we will not install the runner in the usual way, but rather run it in a debug mode.<br>Here’s our test subject: <a href="https://gitlab.com/gitlab-org/gitlab-runner">https://gitlab.com/gitlab-org/gitlab-runner</a></p><h4>Let’s go!</h4><p><strong>Registration (</strong><em>command: register</em><strong>)</strong></p><p>Launching a project in a registration mode. The application kindly asks us to answer a few questions — the theme is thus formed by the configuration file that will be used at startup. We also notify Gitlab about our registration.<br>The product of the registration stage would be a configuration toml file (<em>~/.gitlab-runner/config.toml</em>) similar to mine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4837fe535058abd27aba5ccf47ea289/href">https://medium.com/media/e4837fe535058abd27aba5ccf47ea289/href</a></iframe><p>Out of the main settings, these are your Gitlab URL and registration token, which you can find on the CI/CD setup page of your repository.<br>This concludes the registration of a new runner.</p><p><a href="https://docs.gitlab.com/ee/api/runners.html#register-a-new-runner">Runners API</a></p><p>We go into our repository and see that our runner has appeared in the repository settings. He has not been online yet, though.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/0*WNAi0eOD5OEuMnH4" /></figure><p><strong>Run (</strong><em>command: run</em><strong>)</strong><br>Let’s run the runner and see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/0*KUEBfeVKOOPVC3zv" /></figure><p>Good enough — we are now online!<br>From now on, we are ready to accept jobs from Gitlab.<br>We started in a concurrency mode, which means we can perform several tasks at the same time. You can also run in a run-single mode.</p><p>Let’s take a look at the runner’s algorithm:</p><ul><li>we launch the application as a service, set up the infrastructure (logger, monitoring, profiling ..)</li><li>we warn the user if we are not running as root (since the tasks will be performed under this user), I was running as root.</li><li>using the channel, we manage runners launch (<em>feedRunner</em>), which in turn creates a pool of workers limited by the number from the config (<em>Config.Concurrent</em>)</li></ul><h4>Status: pending</h4><p>Then each runner prepares for the task. Gets an executor from the global list of service providers and looks at what an executor is capable of taken current infrastructure.</p><p>Now we are ready to perform one of the main functions of the runner — we receive a task from Gitlab using its API.</p><p><a href="https://docs.gitlab.com/ee/api/README.html">API Docs</a></p><p>The task is issued for us according to a certain <a href="https://docs.gitlab.com/ee/ci/runners/#how-shared-runners-pick-jobs">algorithm</a>, which is defined by the Gitlab server.</p><p>If there are no tasks, then we exit and find ourselves again in the cycle (<em>processRunners</em>) and everything is repeated again … we are waiting for the task again.</p><p>Here is my <em>.gitlab-ci.yml</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89198e4a7ae5067a24ef6fff5f4dcd27/href">https://medium.com/media/89198e4a7ae5067a24ef6fff5f4dcd27/href</a></iframe><p>The task comes in the form of a certain stage, at which the scripts (<em>build</em>) are executed sequentially — this is what our runner will do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUoX_YC02ivSCJ2h4mKLDQ.png" /><figcaption>task debug</figcaption></figure><p>Create a Build and return the runner back to the channel — it is ready to receive buildings again.</p><h4>Status: running</h4><p>Run the task and wait for one of the signals to arrive:</p><ul><li><em>SystemInterrupt</em></li><li><em>buildFinish</em></li><li><em>buildPanic</em></li></ul><p>We will not review the execution of the task in detail, so as not to complicate the article.<br>I would like to abstract from this, since the type of executor can be any, but in simple words:</p><ul><li>get repository data according to Git Strategy.</li><li>use the cache</li><li>load artifacts from previous stages</li><li>run the <strong>before_script</strong> section</li><li>run our task (<em>scripts</em>)</li><li>run <strong>after_script </strong>section</li><li>depending on the received signal of the completion of these signal tasks, set the status (<strong>failed</strong>, <strong>success</strong>, <strong>terminated)</strong>.</li><li>marks the build execution as complete</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/0*tZnAAih_ADyWHUJV" /></figure><h3>Epilogue</h3><p>Studying the runner project, I concluded that it was written by a person with extensive experience in another language (maybe i’m wrong). It seemed to me that the code was overloaded with unnecessary abstractions. Although it is possible to get along without them — let’s try it ourselves.<br>It is also morally outdated — it often happens to me, when my experience goes to the next level, then looking at overpast projects could be not very pleasant.</p><p>In such cases, I just rewrote my old projects.<br>But from a business and a wifes point of view, remember — this is usually not the best idea! :)</p><p>In the next article we will try to <strong>write a Gitlab-runner</strong> with the minimal functionality using proven design patterns such as Solid &amp; clean architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12cbfe9938cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/explaining-gitlab-runner-research-12cbfe9938cd">Explaining Gitlab-Runner: research</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Mocking in Go]]></title>
            <link>https://medium.com/scum-gazeta/database-mocking-in-go-5925c2cc1079?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/5925c2cc1079</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 16:03:01 GMT</pubDate>
            <atom:updated>2020-12-01T16:03:01.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqCjDsC3nG3kW4c9y0rk0A.png" /></figure><p>Today we’ll talk about unit testing.<br>Namely, about testing our repository — working with a database.<br>The indicator of a good and clean application are beautifully and clearly written tests, with almost complete coverage of this service.<br>Let’s do what we can do well with you — write a web application :)</p><p>But first we will talk a little about the architecture of our application.</p><h3>Application architecture</h3><p>Our architecture will be close to perfect and will consist of several layers.</p><ul><li>Middlewares</li><li>Endpoint layer</li><li>Business layer</li><li><strong>Repository layer </strong>(today we are here)</li></ul><h4>Middlewares</h4><p>Here we will log and authorize incoming requests.<br>From here there will be errors like: <strong><em>401</em></strong>, <strong><em>403</em></strong>.</p><h4>Endpoints</h4><p>Here we will accept user HTTP-requests,<br>deseralize them into our go-structure and call our service methods with this data.<br>Errors such as <strong><em>400</em></strong> will be generated here.</p><h4>Business logic</h4><p>There will be our application logic, which we will change from service to service, changing the behavior of the application.<br>Usually, if your team uses code generation services,<br>then this is exactly the service that will need to be “revived” manually. Errors of this level will be: <strong><em>404</em></strong>, <strong><em>409</em></strong>, <strong><em>422</em></strong></p><h4><strong>Repository</strong></h4><p>And this is exactly what we are going to do now :) The layer that implements the work with your repository.<br>Most likely a database. From this Mariana Trench already <strong><em>500</em></strong> serious errors will appear.</p><h3>Testing the repository</h3><p>According to the testing pyramid, we need unit tests to cover almost everything and to execute them as quickly as possible.<br>To achieve this, we abandon the use of a real database, and replace it with mock.<br>For this we will use the popular SQLMock library.</p><p><a href="https://github.com/DATA-DOG/go-sqlmock">GitHub - DATA-DOG/go-sqlmock: Sql mock driver for golang to test database interactions</a></p><p>By the way, the developer of this wonderful library is looking for a maintainer and after reading this article you have every chance of becoming one :)</p><p>Let’s see how it works from the inside:</p><p>As you know, the SQL-driver standard library allows you to register any driver. In your code, this is exactly the import that you constantly forget about :)</p><pre>_ “github.com/go-sql-driver/mysql</pre><p>in the library it looks like this (registering a new sqlMock driver):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49f6f888fd2e4be7b8513461ee13a40a/href">https://medium.com/media/49f6f888fd2e4be7b8513461ee13a40a/href</a></iframe><p>And now instead of interacting with a real database, we will interact with the following object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/789d78782ef43cb2ae81a32a369f0273/href">https://medium.com/media/789d78782ef43cb2ae81a32a369f0273/href</a></iframe><p>Now let’s see how we start our testing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16001f8034b96e07f3a279bc366dfd6a/href">https://medium.com/media/16001f8034b96e07f3a279bc366dfd6a/href</a></iframe><p>Here we are interested in the first two, returned parameters <strong><em>db</em></strong> and <strong><em>mock</em></strong>.</p><p>We will use the first one instead of connecting in our repository.<br>It returns a pointer to the standard <strong><em>*sql.DB</em></strong>, so you can use it wherever you are using your real database connection.<br>In our case, this will be the essence of the mock library, which will implement standard SQL-driver methods. Only these methods will not contact our database, they will simply remember the sequence of your actions.</p><p>With the second object, we will set our expectations. Fill in the <em>expected [] expectation</em> array.<br>Roughly speaking, we will add our SQL query to the expectation array. Why an array? Well, because we may have a whole definite sequence of actions (remember transactions).</p><p>Here we will also indicate whether our SQL query should return an error or just successfully complete.</p><p>This is a normal query, for example: Update, Delete ..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4051a973572f270134111bc92e1cfc1e/href">https://medium.com/media/4051a973572f270134111bc92e1cfc1e/href</a></iframe><p>Here we perform a request for certain data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eb3b8c0cebb2363f2bd017b7ae0402c/href">https://medium.com/media/8eb3b8c0cebb2363f2bd017b7ae0402c/href</a></iframe><p>We indicate the <strong>regularity</strong> of the request that we expect. We specify what data the request should return and if it should succeed or return some specific error (for ex. <em>sql.NoRows</em>)</p><p>In the data, we indicate which columns are present in the request and the data that we will return for them. We can return a few lines or not return anything.</p><p>Well, that’s the principle and that’s it. We have a contract, let’s try to execute it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/485158e3319ffa95877413e45a9d34fa/href">https://medium.com/media/485158e3319ffa95877413e45a9d34fa/href</a></iframe><p>Inside we simply check the executed SQL query against the regex we described above. Further, the request returns the data that we specified or there may be an error. We can already check this in our test-cases.<br>This is basically all we need to know to write simple test scripts with a separate database.</p><p>There are some other useful features in the library, which I recommend that you familiarize yourself with as your homework :)</p><p>See the official examples of this library usage. You will find there is everything you need. <br><a href="https://github.com/DATA-DOG/go-sqlmock/tree/master/examples">https://github.com/DATA-DOG/go-sqlmock/tree/master/examples</a></p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5925c2cc1079" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/database-mocking-in-go-5925c2cc1079">Database Mocking in Go</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: OAuth2 & OpenID]]></title>
            <link>https://medium.com/scum-gazeta/golang-oauth2-openid-d69d09cb84db?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/d69d09cb84db</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Tue, 05 May 2020 19:32:37 GMT</pubDate>
            <atom:updated>2020-05-06T06:31:51.355Z</atom:updated>
            <content:encoded><![CDATA[<p>In my upcoming articles, I implemented authentication on the API Gateway side using <strong>JWT</strong> tokens.<br>But it’s time to take a big step forward (of course with little effort)<br>It’s time to implement <strong>OAuth2</strong> and <strong>OpenID</strong> protocol to access our resources. And we will no longer have to solve the problem with revoked tokens and many more with what.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3ugbSsJCr6E_KrdCxhk7A.png" /></figure><p>Of course, we don’t have much time at home to implement these protocols, and we also didn’t want to create new errors, so we’ll take the finished certified product <a href="https://www.ory.sh/hydra/">ORY Hydra</a>.</p><h4>What we need:</h4><ol><li><a href="https://www.docker.com/">Docker</a></li><li><a href="https://www.ory.sh/hydra/">ORY Hydra</a></li><li><a href="https://github.com/ihippik/idp-example">Identity&amp;Consent provider</a> (our service)</li></ol><p>The resources to which we request access will be our many services and their APIs.<br>We will validate and update the received tokens on the API Gateway and we will not consider this article.</p><h4><a href="https://oauth.net/2/">OAuth2</a></h4><p>What is the <a href="https://oauth.net/2/">OAuth2</a> protocol, we will not particularly consider. I will only remind you that it was invented by some smart people and implemented by others, which are still far from us :)</p><blockquote>OAuth 2.0 is the industry-standard protocol for authorization. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices.</blockquote><h4>ORY Hydra</h4><p>This is a wonderful open source application that will do all the magic for us on implementing the OAuth2 &amp; OpenID protocols.</p><blockquote>Hydra is an OAuth 2.0 and OpenID Connect Provider. In other words, an implementation of the OAuth 2.0 Authorization Framework as well as the OpenID Connect Core 1.0 framework. As such, it issues OAuth 2.0 Access, Refresh, and ID Tokens that enable third-parties to access your APIs in the name of your users.</blockquote><h4>Why do we need OpenID?</h4><p>OpenID a simple credential layer on top of OAuth, сonnect allows clients of all types, to receive information about authenticated sessions and end users.</p><p>In our example, we will store additional user information that we can always get from Hydra.</p><h4>OAuth Grant Types</h4><p>OAuth2.0, as written above, this authorization protocol supports several interaction scenarios.</p><ol><li><strong>Authorization Code</strong></li><li>Client Credentials</li><li>Device Code</li><li>Refresh Token</li></ol><p>We are interested in the first, most common option with an authorization code. It is just right for our interaction scenario. Good for server-side applications.</p><h3>Let’s get started</h3><p>The first thing we need to do is deploy Hydra. The most convenient option, of course, is Docker.</p><p>We’ll clone her project and take a look at the numerous options for docker-compose files.</p><pre>git clone <a href="/service/mailto:git@github.com">git@github.com</a>:ory/hydra.git</pre><p>You can run Hydra with different types of databases. But if you already have a database of data, then you can select a separate scheme in it and register DSN. Or maybe you will like to store everything you need in memory:</p><pre>version: &#39;3&#39;<br><br>services:<br><br>  hydra:<br>    image: oryd/hydra:1.4.8<br>    ports:<br>      - &quot;4444:4444&quot; <em># Public port<br>      </em>- &quot;4445:4445&quot; <em># Admin port<br>    </em>command:<br>      serve all --dangerous-force-http<br>    environment:<br>      - URLS_SELF_ISSUER=http://127.0.0.1:4444<br>      - URLS_CONSENT=http://127.0.0.1:3000/consent<br>      - URLS_LOGIN=http://127.0.0.1:3000/login<br>      - URLS_LOGOUT=http://127.0.0.1:3000/logout<br>      - DSN=memory<br>      - SECRETS_SYSTEM=youReallyNeedToChangeThis<br>      - OIDC_SUBJECT_IDENTIFIERS_SUPPORTED_TYPES=public,pairwise<br>      - OIDC_SUBJECT_IDENTIFIERS_PAIRWISE_SALT=youReallyNeedToChangeThis<br>    restart: unless-stopped</pre><p>What else do we see in this configuration?</p><pre>serve all --dangerous-force-http</pre><p>We allow communication through HTTP. Understand this is not safe!<br>Read the documentation for running the <strong><em>serve</em></strong> command.</p><blockquote>ORY Hydra exposes two ports, a public and an administrative port. The public port is responsible for handling requests from the public internet, such as the OAuth 2.0 Authorize and Token URLs. The administrative port handles administrative requests like creating OAuth 2.0 Clients, managing JSON Web Keys, and managing User Login and Consent sessions.</blockquote><p>Start the service with the parameter all (both ports) for the house project just right.</p><p>Let’s look at environment variables:</p><p><strong>URLS_SELF_ISSUER — </strong>this is the hydra public API</p><p><strong>URLS_CONSENT — </strong>content provider (method consent)</p><p><strong>URLS_LOGIN — </strong>identity provider(method login)</p><p><strong>URLS_LOGOUT — </strong>identity provider(method logout)</p><p><strong>OAUTH2_ERROR_URL —</strong> authorization error page</p><p>It is worth noting that the implementation of business logic is identification, rendering interfaces (login,registration ..pages)— falls on your shoulders. Hydra, you only tell what address that is located. And already she takes care of the rest. And please do not implement any sessions on the side of your Identity Providers — this also takes Hydra.</p><p>For a quick start, run Hydra together with PostgreSQL. Just let’s remove form <strong><em>quickstart.yml </em></strong>the service <strong><em>consent</em></strong> from the file — we will write it ourselves on Golang. The file should turn out as we considered above.</p><p>We execute from the root of the Hydra project:</p><pre>docker-compose -f quickstart.yml \<br> -f quickstart-postgres.yml \<br> up --build</pre><p>Next we need to create a grant issuer:</p><pre>docker-compose -f quickstart.yml exec hydra \<br> hydra clients create \<br> --endpoint http://127.0.0.1:4445 \<br> --id auth-code-client \<br> --secret secret \<br> --grant-types authorization_code,refresh_token \<br> --response-types code,id_token \<br> --scope openid,offline \<br> --callbacks <a href="http://127.0.0.1:5555/callback">http://127.0.0.1:5555/callback</a></pre><blockquote><em>Note that you need to add </em><em>--token-endpoint-auth-method none if your clients are public (such as SPA apps and native apps) because the public clients cannot provide client secrets.</em></blockquote><p>What else do we see here?</p><p><strong>grand-types </strong>— grants for acquiring an access token.</p><p><strong>scope</strong> (openid, offline)— <em>openid</em>: request an OpenID Connect ID Token, <em>offline</em>: required when requesting refresh tokens</p><p><strong>response-types </strong>— this is what we want to get in the end.</p><p><strong>callbacks</strong> — the address to which the Get-parameter will ultimately return the authorization code to us</p><h3>Sign in</h3><p>For example, click the button to enter your application and get to the Hydra at this address:</p><pre>http://127.0.0.1:4444/oauth2/auth?audience=&amp;client_id=scum-client&amp;redirect_uri=http://127.0.0.1:5555/callback&amp;response_type=code&amp;scope=openid+offline&amp;state=pnaqqipwwpbrdkosbqflsnya</pre><p>Here we are all familiar with the parameters.</p><p>As soon as we get to the Hydra, it checks whether we have cookies set for successful login earlier and in any case redirect to the <strong>URLS_LOGIN</strong> set in its configuration.</p><p>Our identity-provider intercepts this request, takes the login_challenge from it and goes with it to the hydra, thereby confirming the running login process.</p><p>By the way, the Hydra project already has a kindly generated HTTP-client by swagger.</p><p>We get the challenge from the query and make a request with it.</p><p>In the description to the code I will indicate a link to the Hydra API.</p><p>A request comes from Hydra:</p><pre>http://127.0.0.1:3000/login?login_challenge=123</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da67263dc548bbbaa419eaa58309b54a/href">https://medium.com/media/da67263dc548bbbaa419eaa58309b54a/href</a></iframe><p>Here we draw the login page if the user has not logged in yet and in case of successful entry of data, we complete the login process - confirm the started process and indicate the duration of the login.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/556365b4cb5b213479f6ed2754fb89f2/href">https://medium.com/media/556365b4cb5b213479f6ed2754fb89f2/href</a></iframe><p>If everything went without errors, we redirect to the address that came to us in the response object.</p><p>Next, the flow returns us to the <em>consent handler</em> and the login-like process is repeated.</p><p>Hydra throws the user to:</p><pre>http://127.0.0.1:3000/consent?consent_challenge=123</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb37a3c78406ba67aa545b65e6cfd041/href">https://medium.com/media/cb37a3c78406ba67aa545b65e6cfd041/href</a></iframe><p>Next, you can display an interface with the confirmation of the requested scope, or if this is your application, then allow everything that was requested.</p><p>We confirm the request. And note that you can also save additional information about the user here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f050f772016e77f5d4db289999b9971b/href">https://medium.com/media/f050f772016e77f5d4db289999b9971b/href</a></iframe><p>Later, by completing this request, you will be able to get all the additional information saved about users:</p><pre><a href="https://www.ory.sh/hydra/docs/reference/api/#openid-connect-userinfo">https://www.ory.sh/hydra/docs/reference/api/#openid-connect-userinfo</a></pre><p>Well, you can be congratulated! Since if everything is ok on callback url the authorization code set earlier will return to you!</p><p>And with the authorization code, you can already get the <strong>access token</strong> and <strong>refresh token:</strong></p><pre><a href="https://www.ory.sh/hydra/docs/reference/api#the-oauth-20-token-endpoint">https://www.ory.sh/hydra/docs/reference/api#the-oauth-20-token-endpoint</a></pre><p>The logout process will be your homework :)</p><p>You can view the repository with an example <a href="https://github.com/ihippik/idp-example">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d69d09cb84db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/golang-oauth2-openid-d69d09cb84db">Golang: OAuth2 &amp; OpenID</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: pack db migration]]></title>
            <link>https://medium.com/scum-gazeta/golang-pack-db-migration-e9713eaed99d?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/e9713eaed99d</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[migration]]></category>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 12:59:12 GMT</pubDate>
            <atom:updated>2020-03-28T12:59:12.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg7butbLmlf9YeA-P0Oe6w.png" /></figure><p>We continue a series of tips for a home project.</p><p>Today I wanted to write a small article, which should slightly improve your life as a developer, as well as the lives of people supporting your application. In our case, ours too :)</p><p>About the benefits of writing migrations, we will not today,<br>I hope everyone knows about it for a long time, today we’ll talk about how to write <em>self-contained applications</em> (one binary)</p><p>Let me describe a few advantages of this approach.</p><p>Why do we all love Golang? Of course for one executive file after assembly.<br>We try to drag everything into it, often we collect it together with static dependencies .</p><p>Migration is not an exception.<br>You must admit that having one binary of our service working with the database and being able to roll them with one command is great:</p><blockquote>./myapp migrate up</blockquote><p>Well, roll back accordingly</p><blockquote>./myapp migrate down</blockquote><p>Your application is just spreading. You do not need to download and install and store the dependencies of the utilities and the files of the migrations themselves separately.<br>Now they are all inside your application.</p><p>And to do all this is very simple.</p><h4>Of the tools we will use</h4><ul><li><a href="https://github.com/rubenv/sql-migrate">https://github.com/rubenv/sql-migrate</a> — tool for migrations</li><li><a href="https://github.com/gobuffalo/packr/tree/master/v2">https://github.com/gobuffalo/packr</a> — simple solution for bundling static assets inside of Go binaries.</li><li><a href="https://github.com/urfave/cli">https://github.com/urfave/cli</a> — a library for creating console applications.</li></ul><p>We create a new project with a migration directory in which our sql migrations will be stored.</p><h4>Make migration</h4><p>We set up our migration tool using the full <a href="https://github.com/rubenv/sql-migrate/blob/master/README.md">instruction</a> of their project:</p><p>First — install the library and command line program, use the following:</p><pre>go get -v github.com/rubenv/sql-migrate/...</pre><p>To execute the commands of this tool (create new migration), a configuration file for the database is required (<em>dbconfig.yml</em>). It can describe several of your development environments:</p><pre>production:<br>  dialect: postgres<br>  datasource: host=prodhost dbname=proddb user=produser password=prodpass sslmode=required<br>  dir: migrations<br>  table: migrations</pre><pre>development:<br>  dialect: postgres<br>  datasource: host=${DB_HOST} dbname=${DB_NAME} user=${DB_USER} password=${DB_PASS} sslmode=disable<br>  dir: migrations<br>  table: migrations</pre><p><em>I use environment variables here, but you can just fill it yourself.</em></p><p>Now we can create our first migration:</p><pre>sql-migrate new create_users_table</pre><p>This command will create a migration in the folder specified in the configuration file. It remains only to fill it:</p><pre>-- +migrate Up<br>CREATE TABLE users<br>(<br>    id         UUID CONSTRAINT users_pk PRIMARY KEY,<br>    name       VARCHAR(255)                           NOT NULL,<br>    created_at TIMESTAMP WITH TIME ZONE DEFAULT <em>now</em>() NOT NULL,<br>    updated_at TIMESTAMP WITH TIME ZONE DEFAULT <em>now</em>() NOT NULL,<br>    deleted_at TIMESTAMP WITH TIME ZONE<br>);<br>-- +migrate Down<br><br>DROP TABLE users;</pre><p>You can create a manual migration file. Then you do not need config (<em>dbconfig.yml</em>). The main thing is to write the name of the migration file in the desired format. For example:</p><blockquote>20200328085739-creat_user_table.sql</blockquote><h4>Service template</h4><p>Now we create a simple console application with <a href="https://github.com/urfave/cli">urfave</a>.</p><p>You will find what to optimize in it and how to create an optimal project structure for you. This is just a demo template:</p><pre>package main<br><br>import (<br>   &quot;database/sql&quot;<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;os&quot;<br><br>   &quot;github.com/gobuffalo/packr/v2&quot;<br>   _ &quot;github.com/lib/pq&quot;<br>   migrate &quot;github.com/rubenv/sql-migrate&quot;<br>   &quot;github.com/urfave/cli/v2&quot;<br>)<br><br>//<strong><em>go:generate </em></strong>packr2<br><br>func main() {<br>   pgConString := fmt.Sprintf(<br>      &quot;port=%d host=%s user=%s password=%s dbname=%s sslmode=disable&quot;,<br>      os.Getenv(&quot;DB_PORT&quot;),<br>      os.Getenv(&quot;DB_HOST&quot;),<br>      os.Getenv(&quot;DB_USER&quot;),<br>      os.Getenv(&quot;DB_PASS&quot;),<br>      os.Getenv(&quot;DB_NAME&quot;),<br>   )<br>   db, err := sql.Open(&quot;postgres&quot;, pgConString)<br>   if err != nil {<br>      log.Fatal(err)<br>   }<br><br>   migrationSource := &amp;migrate.PackrMigrationSource{<br>      Box: packr.New(&quot;migrations&quot;, &quot;migrations&quot;),<br>   }<br><br>   app := &amp;cli.App{<br>      Commands: []*cli.Command{<br>         {<br>            Name:    &quot;migrate&quot;,<br>            Aliases: []string{&quot;m&quot;},<br>            Usage:   &quot;work with migration&quot;,<br>            Subcommands: []*cli.Command{<br>               {<br>                  Name:  &quot;up&quot;,<br>                  Usage: &quot;migrate up&quot;,<br>                  Action: func(c *cli.Context) error {<br><br>                     n, err := migrate.Exec(db, &quot;postgres&quot;, migrationSource, migrate.<em>Up</em>)<br>                     if err != nil {<br>                        log.Fatalln(err)<br>                     }<br>                     fmt.Printf(&quot;Applied %d migrations!\n&quot;, n)<br>                     return nil<br>                  },<br>               },<br>               {<br>                  Name:  &quot;down&quot;,<br>                  Usage: &quot;migrate down&quot;,<br>                  Action: func(c *cli.Context) error {<br>                     n, err := migrate.ExecMax(db, &quot;postgres&quot;, migrationSource, migrate.<em>Down</em>, 1)<br>                     if err != nil {<br>                        log.Fatalln(err)<br>                     }<br>                     fmt.Printf(&quot;rollback %d migrations!\n&quot;, n)<br>                     return nil<br>                  },<br>               },<br>            },<br>         },<br>      },<br>   }<br><br>   err = app.Run(os.Args)<br>   if err != nil {<br>      log.Fatal(err)<br>   }<br>}</pre><p>Here we created a console application with a <strong>migrate</strong> command and two <strong>up</strong> and <strong>down </strong>subcommands for migration management.</p><p><em>Please note that I roll all the migrations, and roll back one at a time. I do this with different commands.</em></p><p>Sql-migrate already supports the packer, therefore we can only pack our migrations and pass the <strong>migrationSource </strong>with<strong> packr2 </strong>box to the sql tool.</p><p>Next we perform:</p><blockquote>go generate</blockquote><p>And look what happened.</p><p>We have a <strong>packrd</strong> folder in which our packed migrations will be stored. And of course now we can use them directly from our code.</p><p>Now after each added migration do not forget to pack them! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9713eaed99d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/golang-pack-db-migration-e9713eaed99d">Golang: pack db migration</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The second version with pgoutput support has been released!]]></title>
            <link>https://medium.com/scum-gazeta/the-second-version-with-pgoutput-support-has-been-released-a18587514636?source=rss----e57d89036328---4</link>
            <guid isPermaLink="false">https://medium.com/p/a18587514636</guid>
            <dc:creator><![CDATA[Konstantin Makarov]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 01:01:57 GMT</pubDate>
            <atom:updated>2020-02-06T01:22:39.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXF3RmULXaTWmEKk0mnhkA.png" /></figure><p>The second version with pgoutput support has been released!<br>Now you do not need to install third-party plugins for the database, we use the native one.<br><a href="https://github.com/ihippik/wal-listener">https://github.com/ihippik/wal-listener</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a18587514636" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scum-gazeta/the-second-version-with-pgoutput-support-has-been-released-a18587514636">The second version with pgoutput support has been released!</a> was originally published in <a href="https://medium.com/scum-gazeta">Scum-Gazeta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>