<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jan Pieter Bruins Slot on Medium]]></title>
        <description><![CDATA[Stories by Jan Pieter Bruins Slot on Medium]]></description>
        <link>https://medium.com/@0x4a50?source=rss-759fb6cac80c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*1pqjx9WMUl-yqLQ3b5lFsA.jpeg</url>
            <title>Stories by Jan Pieter Bruins Slot on Medium</title>
            <link>https://medium.com/@0x4a50?source=rss-759fb6cac80c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:35:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@0x4a50/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Encrypt data with a password in Go]]></title>
            <link>https://itnext.io/encrypt-data-with-a-password-in-go-b5366384e291?source=rss-759fb6cac80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5366384e291</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Jan Pieter Bruins Slot]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 09:39:05 GMT</pubDate>
            <atom:updated>2020-03-18T09:39:05.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jy250MvJVLAIn5I8" /><figcaption>Photo by <a href="https://unsplash.com/@shaneavery?utm_source=medium&amp;utm_medium=referral">Shane Avery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>When we’re encrypting data, typically we will create a random key that is able to decrypt that data. In some specific cases one wants to use a user specified key to decrypt that data like a password. However, the key that is used for cryptographic algorithms typically needs to be at least 32 bytes. But, it is likely that our password won’t make that criteria, so we need to have a solution for that. Recently, I needed such a method, and in this post I’ll lay out what I’ve done in order to solve it. But before we get into the nitty-gritty.</p><p><strong>DISCLAIMER</strong>: I’m not an expert at encryption, I’ve mentioned the sources that I’ve used to come to the solutions provided in this post. I implore you read/watch those sources to better understand it. And, as such if there are any errors in the post/code please let me know or leave a comment so I can update it, so that there is no perpetuation of wrong methods/techniques.</p><p>OK, since we’ve got that out of the way, let’s begin! (Note: you can also view this post <a href="https://bruinsslot.jp/post/golang-crypto">here</a>)</p><h3>Encrypt</h3><p>Let’s first start with encrypting our data. We’ll start with creating the Encrypt function that will accept a key and a data argument. Based on that we will encrypt the data that can be decrypted using the key. First, we will generate that key by using 32 random bytes, later on we&#39;ll replace that with our password. Below, shows the code that is able to encrypt our data, provided by a generated key.</p><pre>import (<br>    &quot;crypto/aes&quot;<br>    &quot;crypto/cipher&quot;<br>    &quot;crypto/rand&quot;<br>)<br><br>func Encrypt(key, data []byte) ([]byte, error) {<br>    blockCipher, err := aes.NewCipher(key)<br>    if err != nil {<br>        return nil, err<br>    }<br><br>    gcm, err := cipher.NewGCM(blockCipher)<br>    if err != nil {<br>        return nil, err<br>    }<br><br>    nonce := make([]byte, gcm.NonceSize())<br>    if _, err = rand.Read(nonce); err != nil {<br>        return nil, err<br>    }<br><br>    ciphertext := gcm.Seal(nonce, nonce, data, nil)<br><br>    return ciphertext, nil<br>}</pre><p>So, let’s go over the code, and inspect what we’re doing.</p><pre>func Encrypt(key, data []byte) ([]byte, error)</pre><p>First, we start by creating our Encrypt function, and it will accept a key and a data argument. We&#39;ll be using a byte slice instead of an io.Reader as the data argument. While using io.Reader would allow us to use the Encrypt function with every other type that implements the io.Reader interface. (Ryer <a href="https://gist.github.com/erroneousboat/d01e57e3c0470c645e72ae663c7955fa#ref-ryer2015">2015</a>) It is however because of the nature of io.Reader, being a stream of data, that when we want to decrypt the ciphertext, we need to see it in its entirety. A solution would be to break the stream into discrete chunks, however this would add significant complexity to the problem.<a href="#f6d0">¹</a> (Isom <a href="#efb4">2015</a>)</p><pre>blockCipher, err := aes.NewCipher(key)</pre><p>We’re initializing the block cipher based on the key that we provided. Here we&#39;re using the crypto/aes<a href="#63b9">²</a> package that implements the AES<a href="#5627">³</a> <a href="#bf25">⁴</a> (Advanced Encryption Standard) encryption algorithm. AES is a symmetric-key encryption algorithm, that will be secure enough for modern use cases. Additionally, AES uses hardware acceleration on most platforms, so it&#39;ll be pretty fast to use. (Tankersley <a href="#985d">2016</a>)</p><pre>gcm, err := cipher.NewGCM(blockCipher)</pre><p>Here we’re wrapping the block cipher, with a specific <em>mode</em>. We do this because we shouldn’t use a cipher.Block interface directly. This is because the block cipher only encrypts 16 bytes of data, nothing more. So if you would call blockCiper.Encrypt() it would only encrypt the first 16 bytes. Thus we need something on top of that, and wrap the block cipher, and those are called <em>modes</em>. Again we have several <em>modes</em> to choose from, and here we&#39;re going to use the <em>Galois Counter Mode</em> (GCM)<a href="#4df4">⁵</a>, with a standard nonce length.</p><p>Only GCM provides authenticated encryption, and it implements the cipher.AEAD interface (Authenticated Encryption with Associated Data)<a href="#810e">⁶</a>. Authenticated encryption means that not only is your data going to be confidential, secret, and encrypted, it&#39;s also now going to be tamper proof. If someone alters the ciphertext you will not then be able to validly decrypt it. When you&#39;re using authenticated encryption and someone messes with your data it just fails to decrypt. (Tankersley <a href="#985d">2016</a>; Isom <a href="#efb4">2015</a>)</p><pre>nonce := make([]byte, gcm.NonceSize())<br>if _, err = rand.Read(nonce); err != nil {<br>    return nil, err<br>}</pre><p>Before we can encrypt our bytes we need to generate a randomized nonce, and its length is specified by the GCM. The nonce stands for: <em>number once used</em>, and it&#39;s a piece of data that should not be repeated and only used once in combination with any particular key. Meaning: don&#39;t repeat the combination of a key and a nonce more than once. But, how do you keep track of that? If we use sufficiently large numbers for a nonce we should probably be fine for this use-case. (Isom <a href="#efb4">2015</a>; Viega and Messier <a href="#be38">2003</a>, 134-35) We do that by using Go&#39;s crypto/rand package to read randomized bytes into the nonce byte slice.<a href="#c9f0">⁷</a></p><pre>encryptedData := gcm.Seal(nonce, nonce, bData, nil)</pre><p>The nonce that we&#39;re going to use for encrypting our data, is also needed to decrypt it. So we need to be able to refer to it while decrypting, and one of the strategies is to add it to the encrypted data. In this example we will prepend the nonce to the encrypted data. We do that by passing in the nonce as the first argument dst of the Seal function, and as such the encrypted data will be appended to it.<a href="#1aa0">⁸</a> We can do this because the nonce doesn&#39;t have to be secret, it just has to be unique. (Tankersley <a href="#985d">2016</a>)</p><h3>Decrypt</h3><p>Now, we’re able to encrypt our data, and let’s implement the Decrypt function.</p><pre>import (<br>    &quot;crypto/aes&quot;<br>    &quot;crypto/cipher&quot;<br>)</pre><pre>func Decrypt(key, data []byte) ([]byte, error) {<br>    blockCipher, err := aes.NewCipher(key)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    gcm, err := cipher.NewGCM(blockCipher)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>   nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]</pre><pre>    plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    return plaintext, nil<br>}</pre><p>Again let’s go over the code and check what it does. It is largely the same code as the Encrypt function, so let&#39;s inspect the parts that differ.</p><pre>nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]</pre><p>Remember from the last section, that we prepended the nonce to the data using gcm.Seal to create the ciphertext? Now we need to split those parts so we can use them independently. And we&#39;re creating those part by slicing the data based on the size of the nonce that gcm provides.</p><pre>plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)</pre><p>Now, we’re using gcm.Open to decrypt the ciphertext into plaintext.<a href="#9327">⁹</a></p><h3>Key</h3><p>We’ve been passing in a key to both the Encrypt and Decrypt functions, but we have yet to make it, so let&#39;s do that.</p><pre>import (<br>    &quot;crypto/rand&quot;<br>)</pre><pre>func GenerateKey() ([]byte, error) {<br>    key := make([]byte, 32)</pre><pre>    _, err := rand.Read(key)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    return key, nil<br>}</pre><p>Here we’re generating a random key using Go&#39;s crypto/rand package. For AES we need a key that has the length of 32 bytes, so we make a byte slice of size 32. Then we let rand.Read() fill the slice with random bytes.<a href="#dcc0">¹⁰</a></p><p>Now we have enough to encrypt and decrypt some data, so let’s put it all together and test it out:</p><pre>// crypto.go<br>package main</pre><pre>import (<br>    &quot;crypto/aes&quot;<br>    &quot;crypto/cipher&quot;<br>    &quot;crypto/rand&quot;<br>    &quot;encoding/hex&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>)</pre><pre>func Encrypt(key, data []byte) ([]byte, error) {<br>    blockCipher, err := aes.NewCipher(key)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    gcm, err := cipher.NewGCM(blockCipher)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    nonce := make([]byte, gcm.NonceSize())<br>    if _, err = rand.Read(nonce); err != nil {<br>        return nil, err<br>    }</pre><pre>    ciphertext := gcm.Seal(nonce, nonce, data, nil)</pre><pre>    return ciphertext, nil<br>}</pre><pre>func Decrypt(key, data []byte) ([]byte, error) {<br>    blockCipher, err := aes.NewCipher(key)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    gcm, err := cipher.NewGCM(blockCipher)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]</pre><pre>    plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    return plaintext, nil<br>}</pre><pre>func GenerateKey() ([]byte, error) {<br>    key := make([]byte, 32)</pre><pre>    _, err := rand.Read(key)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    return key, nil<br>}</pre><pre>func main() {<br>    data := []byte(&quot;our super secret text&quot;)</pre><pre>    key, err := GenerateKey()<br>    if err != nil {<br>        log.Fatal(err)<br>    }</pre><pre>    ciphertext, err := Encrypt(key, data)<br>    if err != nil {<br>        log.Fatal(err)<br>    }</pre><pre>    fmt.Printf(&quot;ciphertext: %s\n&quot;, hex.EncodeToString(ciphertext))</pre><pre>    plaintext, err := Decrypt(key, ciphertext)<br>    if err != nil {<br>        log.Fatal(err)<br>    }</pre><pre>    fmt.Printf(&quot;plaintext: %s\n&quot;, plaintext)<br>}</pre><p>And, we can run this example with:</p><pre>$ go run crypto.go</pre><p>Now, we have enough to encrypt and decrypt our data with a randomized key. This is cool and now we have a key that allows us to encrypt and decrypt our data. But that means that the key now becomes our password and weren&#39;t able to choose it ourselves, additionally it has a length of 32 bytes.</p><p>But, as mentioned in the start of the post, we want to be able to encrypt and decrypt the data by providing our own key namely a password that we&#39;ve chosen to use. We will be doing that in the following section.</p><h3>Password</h3><p>Now, the aes.NewCipher() needs a 16, 24, or a 32 byte key, and in this example we are using a 32 byte key. However, our password likely isn&#39;t going to be 32 bytes. So we need to transform our password to a suitable key. And we do that by using a <em>key derivation function</em> (KDF)<a href="#89bb">¹¹</a> to &#39;stretch&#39; the password to make it a suitable cryptographic key. This key-stretching<a href="#3f07">¹²</a> characterizes itself by being slow. This is done in order to make it that, an attacker needs to spend a lot of resources to attempt to brute force an attack the on the password. We have several options for KDF&#39;s: Argon2<a href="#ea51">¹³</a>, scrypt<a href="#a85f">¹⁴</a>, bcrypt<a href="#38e8">¹⁵</a>, and pbkdf2<a href="#af62">¹⁶</a>. Choosing one depends on several factors, but mainly how safe it is.<a href="#3055">¹⁷</a> <a href="#c87a">¹⁸</a> <a href="#9de3">¹⁹</a> <a href="#cc38">²⁰</a> <a href="#0c55">²¹</a> <a href="#f629">²²</a></p><p>Typically in a KDF we have a password, a salt, and an iterations argument. The salt<a href="#fcb3">²³</a> is used to prevent an attacker from just storing password/key pairs, and prevents an attacker from precomputing a dictionary of derived keys, as a different salt yields a different output. Each password has to be checked with the salt used to derive the key. (Isom <a href="#efb4">2015</a>; Wikipedia <a href="#7ac3">2020</a>) The salt is related to the nonce in that it also needs to be randomly generated. And as with the nonce, the salt doesn&#39;t need to be secret, it needs to be unique. The iterations argument or the <em>difficulty parameter</em>, signifies how many times to repeat the process. This is because, even with salt, a <em>dictionary attack</em> is still possible, but with the iterations count, it will slow down the time it takes to compute a key from a password. (Viega and Messier <a href="#be38">2003</a>, 141-42)</p><p>In this example we’ll be using <em>scrypt</em>, so let’s see how we can implement that into our program.</p><pre>import (<br>    &quot;crypto/rand&quot;</pre><pre>    &quot;golang.org/x/crypto/scrypt&quot;<br>)</pre><pre>func DeriveKey(password, salt []byte) ([]byte, []byte, error) {<br>    if salt == nil {<br>        salt = make([]byte, 32)<br>        if _, err := rand.Read(salt); err != nil {<br>            return nil, nil, err<br>        }<br>    }</pre><pre>    key, err := scrypt.Key(password, salt, 1048576, 8, 1, 32)<br>    if err != nil {<br>        return nil, nil, err<br>    }</pre><pre>    return key, salt, nil<br>}</pre><p>Again let’s go over the code and see what it does.</p><pre>func DeriveKey(password, salt []byte) ([]byte, []byte, error)</pre><p>Here we accept the password as a slice of bytes as the argument, and we return the resulting key, and salt.</p><pre>salt := make([]byte, 32)<br>if _, err := rand.Read(salt); err != nil {<br>    return err<br>}</pre><p>Just like our Encrypt function, we&#39;ll be creating the salt with 32 random bytes.</p><pre>key, err := scrypt.Key(password, salt, 1048576, 8, 1, 32)</pre><p>Here we’re using the scrypt package from golang.org/x/ library.<a href="#e5f2">²⁴</a> From the documentation we can read that the Key function accepts the following arguments:</p><pre>func Key(password, salt []byte, N, r, p, keyLen int) ([]byte, error)</pre><p>The arguments password and salt speak for themselves. N is the number of iterations. In a presentation given by C. Percival it is recommended that for interactive logins 16384 (2^14) iterations, and for file encryption 1048576 (2^20) iterations are used. (Percival <a href="#bbcd">2005a</a>, <a href="#3f6a">2005b</a>; Isom <a href="#efb4">2015</a>) The arguments r and p must satisfy <em>r</em> * <em>p</em> &lt; 2^30, if it doesn&#39;t satisfy the limits, the function returns a nil byte slice and an error. (Golang Documentation <a href="#ea28">2020</a>). The r argument defines the relative memory cost parameter it controls the blocksize in the underlying hash, the recommended value is 8. The p argument is the relative CPU cost parameter and the recommended value for this is 1. (Isom <a href="#efb4">2015</a>; Percival <a href="#bbcd">2005a</a>) The keyLen argument defines the length of the bytes that are returned as key, as discussed this will be 32 bytes.</p><h3>Result</h3><p>Now that we’ve created our DeriveKey function we need to update our code to support it. So let&#39;s do that, it should resemble the code below:</p><pre>// scrypt.go<br>package main</pre><pre>import (<br>    &quot;crypto/aes&quot;<br>    &quot;crypto/cipher&quot;<br>    &quot;crypto/rand&quot;<br>    &quot;crypto/sha256&quot;<br>    &quot;encoding/hex&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;</pre><pre>    &quot;golang.org/x/crypto/scrypt&quot;<br>)</pre><pre>func Encrypt(key, data []byte) ([]byte, error) {<br>    key, salt, err := DeriveKey(key, nil)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    blockCipher, err := aes.NewCipher(key)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    gcm, err := cipher.NewGCM(blockCipher)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    nonce := make([]byte, gcm.NonceSize())<br>    if _, err = rand.Read(nonce); err != nil {<br>        return nil, err<br>    }</pre><pre>    ciphertext := gcm.Seal(nonce, nonce, data, nil)</pre><pre>    ciphertext = append(ciphertext, salt...)</pre><pre>    return ciphertext, nil<br>}</pre><pre>func Decrypt(key, data []byte) ([]byte, error) {<br>    salt, data := data[len(data)-32:], data[:len(data)-32]</pre><pre>    key, _, err := DeriveKey(key, salt)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    blockCipher, err := aes.NewCipher(key)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    gcm, err := cipher.NewGCM(blockCipher)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]</pre><pre>    plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)<br>    if err != nil {<br>        return nil, err<br>    }</pre><pre>    return plaintext, nil<br>}</pre><pre>func DeriveKey(password, salt []byte) ([]byte, []byte, error) {<br>    if salt == nil {<br>        salt = make([]byte, 32)<br>        if _, err := rand.Read(salt); err != nil {<br>            return nil, nil, err<br>        }<br>    }</pre><pre>    key, err := scrypt.Key(password, salt, 1048576, 8, 1, 32)<br>    if err != nil {<br>        return nil, nil, err<br>    }</pre><pre>    return key, salt, nil<br>}</pre><pre>func main() {<br>    var (<br>        password = []byte(&quot;mysecretpassword&quot;)<br>        data     = []byte(&quot;our super secret text&quot;)<br>    )</pre><pre>    ciphertext, err := Encrypt(password, data)<br>    if err != nil {<br>        log.Fatal(err)<br>    }</pre><pre>    fmt.Printf(&quot;ciphertext: %s\n&quot;, hex.EncodeToString(ciphertext))</pre><pre>    plaintext, err := Decrypt(password, ciphertext)<br>    if err != nil {<br>        log.Fatal(err)<br>    }</pre><pre>    fmt.Printf(&quot;plaintext: %s\n&quot;, plaintext)<br>}</pre><p>And, we’re able to run and test it:</p><pre># First we need to get the scrypt package<br>$ go get -u golang.org/x/crypto/scrypt</pre><pre>$ go run scrypt.go</pre><p>We’ve updated some parts, so let’s go over it.</p><pre>key, salt, err := DeriveKey(key, nil)</pre><p>In the Encrypt function we create our key by passing in our password, which is contained in the key argument. We pass in nil as the salt argument, that is because we want to create the salt since it is the first time we encrypt our data.</p><pre>ciphertext = append(ciphertext, salt...)</pre><p>Additionally, in the Encrypt function, we append the salt to our ciphertext.</p><pre>salt, data := data[len(data)-32:], data[:len(data)-32]</pre><p>And, because we append the salt to the ciphertext, we need to split and slice it in the Decrypt function, because we&#39;re going to use it in the DeriveKey function.</p><pre>key, _, err := DeriveKey(key, salt)</pre><p>As you can see here we pass in the salt to the DeriveKey function and we&#39;ll be able to retrieve the key that we used in order to encrypt our data.</p><h3>Conclusion</h3><p>With that, we’ve created two ways in order to encrypt and decrypt our data in Go. First we’ve encrypted our data by using the AES encryption algorithm, for which we’ve created a randomized key to be used for decrypting our data. Subsequently, we’ve updated our code to support using a password as our key. We’ve done that by <em>key-stretching</em> our password using a <em>key derivation function</em>, and we’ve used <em>scrypt</em> to achieve that. Hopefully, you found this post useful, and again I advice you to read and watch the sources that I’ve listed, and check out other sources to get a good overview on how to correctly and securely encrypt your data, and if you have any suggestions let me know.</p><h3>References</h3><p>Golang Documentation. 2020. “Package Scrypt.” 2020. <a href="https://godoc.org/golang.org/x/crypto/scrypt">https://godoc.org/golang.org/x/crypto/scrypt</a>.</p><p>Isom, Kyle. 2015. <em>Practical Cryptography with Go</em>. Leanpub. <a href="https://leanpub.com/gocrypto/read">https://leanpub.com/gocrypto/read</a>.</p><p>Percival, C. 2005a. “scrypt: A new key derivation function.” <a href="https://www.bsdcan.org/2009/schedule/attachments/86_scrypt_slides.pdf">https://www.bsdcan.org/2009/schedule/attachments/86_scrypt_slides.pdf</a>.</p><p>— -. 2005b. “Strong Key Derivation via Sequential Memory-Hard Functions.” <a href="https://www.tarsnap.com/scrypt/scrypt.pdf">https://www.tarsnap.com/scrypt/scrypt.pdf</a>.</p><p>Ryer, M. 2015. “io.Reader in Depth.” 2015. <a href="https://medium.com/@matryer/golang-advent-calendar-day-seventeen-io-reader-in-depth-6f744bb4320b">https://medium.com/@matryer/golang-advent-calendar-day-seventeen-io-reader-in-depth-6f744bb4320b</a>.</p><p>Tankersley, G. 2016. “Go for Crypto Developers.” <a href="https://youtu.be/2r_KMzXB74w">https://youtu.be/2r_KMzXB74w</a>.</p><p>Viega, J., and M. Messier. 2003. <em>Secure Programming Cookbook for C and C++</em>. O’Reilly Media.</p><p>Wikipedia. 2020. “Key Derivation Function — Wikipedia, the Free Encyclopedia.” 2020. <a href="https://en.wikipedia.org/wiki/Key_derivation_function">https://en.wikipedia.org/wiki/Key_derivation_function</a>.</p><h3>Footnotes</h3><p>[1] Some references on how to implement encryption with streams: <a href="https://www.reddit.com/r/golang/comments/87wcik/how_do_you_encrypt_large_ioreader_streams/dwp2k0g?utm_source=share&amp;utm_medium=web2x">Reddit Comment</a>; <a href="https://medium.com/blend-engineering/encrypting-streams-in-go-6cff6062a107">Michael Turner — Encrypting Streams in Go</a>; <a href="https://github.com/minio/sio/issues/26#issuecomment-378012290">Minio — Github Issue</a></p><p>[2] <a href="https://golang.org/pkg/crypto/aes/">Go Documentation: AES</a></p><p>[3] <a href="https://en.wikipedia.org/wiki/Advanced_Encryption_Standard">Wikipedia: AES</a></p><p>[4] <a href="https://www.youtube.com/watch?v=O4xNJsjtN6E">Computerphile — AES Explained</a></p><p>[5] <a href="https://en.wikipedia.org/wiki/Galois/Counter_Mode">Wikipedia: GCM</a></p><p>[6] <a href="https://golang.org/pkg/crypto/cipher/#AEAD">Go Documentation: AEAD</a></p><p>[7] <a href="https://golang.org/pkg/crypto/rand/#Read">Go Documentation: rand.Read</a></p><p>[8] <a href="https://golang.org/src/crypto/cipher/gcm.go">Go Source Code: GCM</a></p><p>[9] <a href="https://golang.org/src/crypto/cipher/gcm.go">Go Source Code: GCM</a></p><p>[10] <a href="https://golang.org/pkg/crypto/rand/#Read">Go Documentation: rand.Read</a></p><p>[11] <a href="https://en.wikipedia.org/wiki/Key_derivation_function">Wikipedia: KDF</a></p><p>[12] <a href="https://en.wikipedia.org/wiki/Key_stretching">Wikipedia: Key Stretching</a></p><p>[13] <a href="https://en.wikipedia.org/wiki/Argon2">Wikipedia: Argon2</a></p><p>[14] <a href="https://en.wikipedia.org/wiki/Scrypt">Wikipedia: scrypt</a></p><p>[15] <a href="https://en.wikipedia.org/wiki/Bcrypt">Wikipedia: bcrypt</a></p><p>[16] <a href="https://en.wikipedia.org/wiki/PBKDF2">Wikipedia: pbkdf2</a></p><p>[17] <a href="https://medium.com/@mpreziuso/password-hashing-pbkdf2-scrypt-bcrypt-and-argon2-e25aaf41598e">Michele Prezioso — Password Hashing: PBKDF2, Scrypt, Bcrypt</a></p><p>[18] <a href="https://medium.com/@mpreziuso/password-hashing-pbkdf2-scrypt-bcrypt-and-argon2-e25aaf41598e">Michele Prezioso — Password Hashing: Scrypt, Bcrypt and ARGON2</a></p><p>[19] <a href="https://crypto.stackexchange.com/questions/35275/whats-the-difference-between-pbkdf-and-sha-and-why-use-them-together/61306#61306">StackExchange — What’s the difference between PBKDF and SHA and why use them together?</a></p><p>[20] <a href="https://github.com/bitwarden/jslib/issues/52">Github — Bitwarden Issue 52</a></p><p>[21] <a href="https://github.com/bitwarden/server/issues/589">Github — Bitwarden Issue 589</a></p><p>[22] <a href="https://en.wikipedia.org/wiki/PBKDF2#Alternatives_to_PBKDF2">Wikipedia: pbkdf2 alternatives</a></p><p>[23] <a href="https://en.wikipedia.org/wiki/Salt_(cryptography)">Wikipedia: Salt (cryptography)</a></p><p>[24] <a href="https://godoc.org/golang.org/x/crypto/scrypt">Go Documentation: scrypt</a></p><p><em>Originally published at </em><a href="https://bruinsslot.jp/post/golang-crypto/"><em>https://bruinsslot.jp/post/golang-crypto/</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5366384e291" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/encrypt-data-with-a-password-in-go-b5366384e291">Encrypt data with a password in Go</a> was originally published in <a href="https://itnext.io/">ITNEXT</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 profile Go applications inside a docker container]]></title>
            <link>https://itnext.io/how-to-profile-go-applications-inside-a-docker-container-d29431fbb427?source=rss-759fb6cac80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d29431fbb427</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Jan Pieter Bruins Slot]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 12:00:00 GMT</pubDate>
            <atom:updated>2020-03-03T12:07:57.109Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this post I’ll give a quick overview of several methods you can use for profiling/debugging Go applications that are running in a docker container. To get a more in-depth overview of the several methods, I’ve added the source links you can reference at the end of the post. I really advise you to read the sources listed, and read up on how to use and interpret the created profiles in order to debug/optimize your application. This post aims to help you to create those profiles when using a Docker container to run your Go applications. The main idea is that we are going to leverage the remote profiling capabilities that is supplied by the net/http package.</p><h3>Application</h3><p>We will be using pprof to profile your Go applications, you&#39;ll typically use pprof when you&#39;re able to access the binary of your application locally. When you&#39;re using a docker container you&#39;d need to have the go tool installed in the container to be able to profile it. However there is another way for profiling Go applications running in a docker container. For this we need to create an HTTP webserver, which will enable the pprof HTTP endpoints. From these endpoints we&#39;re able to download profiles of the running application.</p><p>So first we need to create an HTTP webserver, that we will run in a goroutine. We can then import the net/http/pprof package, which automatically enables the pprof HTTP endpoints of the webserver we&#39;ve created, and it will install the handlers under the http://localhost:6060/debug/pprof URL.</p><p>So we can add the following to our code:</p><pre>// main.go<br>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;math/rand&quot;<br>    &quot;net/http&quot;<br>    &quot;net/http/pprof&quot;<br>)</pre><pre>func main() {</pre><pre>    // Add the following<br>    go func() {<br>        http.ListenAndServe(&quot;:6060&quot;, nil)<br>    }()</pre><pre>    // Some sample code<br>    for {<br>        n := rand.Intn(10) + 1<br>        fmt.Printf(&quot;Fibonacci sequence for %d:\n&quot;, n)<br>        for i := 1; i &lt;= n; i++ {<br>            fmt.Println(fibonacci(i))<br>        }<br>    }<br>}</pre><pre>func fibonacci(n int) int {<br>    if n &lt; 2 {<br>        return n<br>    }<br>    return fibonacci(n-1) + fibonacci(n-2)<br>}</pre><p>When you are using a different router, we can do the following to make the pprof HTTP endpoints work. Below is an example how you would do this if you&#39;re using <a href="https://github.com/gorilla/mux">gorilla/mux</a></p><pre>// main.go<br>package main</pre><pre>import (<br>    _ &quot;expvar&quot;<br>    &quot;net/http&quot;<br>    &quot;net/http/pprof&quot;<br>    _ &quot;net/http/pprof&quot;<br>    <br>    &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br>    router := mux.NewRouter()</pre><pre>    router.HandleFunc(<br>        &quot;/debug/pprof/&quot;, pprof.Index,<br>    )<br>    router.HandleFunc(<br>        &quot;/debug/pprof/cmdline&quot;, pprof.Cmdline,<br>    )<br>    router.HandleFunc(<br>        &quot;/debug/pprof/profile&quot;, pprof.Profile,<br>    )<br>    router.HandleFunc(<br>        &quot;/debug/pprof/symbol&quot;, pprof.Symbol,<br>    )<br>    router.HandleFunc(<br>        &quot;/debug/pprof/trace&quot;, pprof.Trace,<br>    )<br>    router.Handle(<br>        &quot;/debug/pprof/goroutine&quot;, pprof.Handler(&quot;goroutine&quot;),<br>    )<br>    router.Handle(<br>        &quot;/debug/pprof/heap&quot;, pprof.Handler(&quot;heap&quot;),<br>    )<br>    router.Handle(<br>        &quot;/debug/pprof/threadcreate&quot;, pprof.Handler(&quot;threadcreate&quot;),<br>    )<br>    router.Handle(<br>        &quot;/debug/pprof/block&quot;, pprof.Handler(&quot;block&quot;),<br>    )<br>    router.Handle(<br>        &quot;/debug/vars&quot;, http.DefaultServeMux,<br>    )</pre><pre>    http.ListenAndServe(&quot;:6060&quot;, router)<br>}</pre><h3>Docker</h3><p>For the docker container we’ll create the following Dockerfile:</p><pre># Dockerfile<br>FROM golang:1.13<br><br>WORKDIR /go/src/app<br>COPY . .<br><br>RUN go get -d -v ./...<br>RUN go install -v ./...<br><br>CMD [&quot;app&quot;]</pre><p>Next, we can build and start our Docker container:</p><pre>$ docker build -t pprof-app .<br>$ docker run -p 6060:6060 -it --rm --name my-running-app pprof-app</pre><p>Once you’ve updated the files you’ll be able to access the endpoints by using your browser and to go to <a href="http://localhost:8888/tree">http://localhost:6060/debug/pprof/</a>, or you can use go tool pprof. We&#39;ll explore a few of the methods we can profile the application using go tool pprof</p><h3>pprof</h3><p>Now, that we’ve set everything up to use pprof, we&#39;ll profile our application for cpu, and heap. Additionally we&#39;ll also trace the application.</p><p><strong>CPU</strong></p><p>When we want to start to profile our application to determine where an application spends time, we first need to make a CPU profile. And we have several methods to do so. Below I’ll give the common ones. The gist of it is that we’re fetching the profile over HTTP, on the endpoints that we’ve created in our application.</p><ol><li>Go to <a href="http://localhost:6060/debug/pprof/profile">http://localhost:6060/debug/pprof/profile</a>, and after 30 seconds you’ll automatically download the profile, or</li><li>Use go tool pprof. It will tell you where the profile is being stored, and will open up an interactive terminal that you can use to interpret the results. Like so: go tool pprof <a href="http://localhost:6060/debug/pprof/profile">http://localhost:6060/debug/pprof/profile</a></li></ol><p>After that we can interpret the results, and for this we again have several options, and tools we can use to interpret the results You can read more about additional ways to interpret the results at the sites I’ve listed in the “Sources” section at the end of the post.</p><p>Here I’ll show you a few of them. One of them is that we’re able to inspect the results in an automatically created web interface.</p><pre>$ go tool pprof -http=&quot;:8080&quot; [path-to-profile-dump]</pre><p>This will open up a webbrowser, in which we can inspect, for instance, the flamegraph of the created profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*kd4fNkT9UFLtewhP.png" /></figure><p>The horizontal axis represents the total number of samples collected. So the larger the area, the more time has been spent executing the associated function. The vertical axis represents the depth of the call stack. So the higher the peak, the deeper the call stack. Colors don’t represent anything specific; they’re just there to make a visual contrast.<a href="#a60c">¹</a></p><p>Another method is that we can use the command line based interactive interface by using the go tool:</p><pre>$ go tool pprof [path-to-profile-dump]</pre><p>We can also instantly go to the web interface, and step over the whole download profile step, by using the following command:</p><pre>$ go tool pprof \<br>    -http=&quot;:8080&quot; \<br>    <a href="http://localhost:6060/debug/pprof/profile">http://localhost:6060/debug/pprof/profil</a>e</pre><p>One thing to remember is: if you’re making cpu profiles that takes a certain amount of time you need to specify that your server is able to handle those long request times. You typically want to add the following to your http.Server:</p><pre>srv := &amp;http.Server{<br>     WriteTimeout: 30 * time.Second,<br>}</pre><h3>Heap</h3><p>In order to get a heap profile, so that we can inspect the memory usage of the application, we again can issue the following commands:</p><ol><li>Go to <a href="http://localhost:6060/debug/pprof/heap">http://localhost:6060/debug/pprof/heap</a>, and we will automatically download the heap profile, or</li><li>Using the go tool, it will tell you were the profile is being stored, and it opens up an interactive terminal that you can use to interpret the results:</li></ol><pre># Heap profile<br>#<br># optional flags:<br>#   –alloc_space tells you how many megabytes have been allocated.<br>#   –inuse_space tells you know how many are still in use.<br>$ go tool pprof http://localhost:6060/debug/pprof/heap</pre><p>And, just like with the CPU profile, we’re able to interpret it with go tool pprof, and the web interface:</p><pre># Go tool<br>$ go tool pprof [path-to-profile-dump]<br><br># Web interface<br>$ go tool pprof -http=&quot;:8080&quot; [path-to-profile-dump]<br><br># Create profile and start web interface<br>$ go tool pprof -http=&quot;:8080&quot; http://localhost:6060/debug/pprof/heap</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*V13O2hFPr6nsgqta.png" /></figure><h3>Trace</h3><p>To trace the runtime activities/events of an application, we can do the following. First, we need to download the trace file, and we can use curl for this. Specify for how many seconds you want to create a trace and make sure to create some load in that time frame. Once downloaded you can use the go tool to start up a web interface in which you can inspect the results.</p><p>The trace tool will capture execution events like the creation, blocking, unblocking of goroutines, garbage collection events, processor starting and stopping, enter, exit, and block syscalls.<a href="#a00a">²</a></p><p>Issue the following commands:</p><pre>$ curl \<br>    http://localhost:6060/debug/pprof/trace?seconds=20 &gt; \<br>    trace.out<br>$ go tool trace trace.out</pre><p>This will open up your webbrowser, and you’ll be able to interpret the results of your trace with the provided web interface.</p><h3>Conclusion</h3><p>We’ve explored some methods that allows us to profile our Go applications when it is run in a Docker container. There’s a lot more information out there, that can help you optimize your applications using these methods. I’ve listed several of those below in the “Sources” section. Be sure to check them out they have some great additional information that can help you.</p><h3>Sources</h3><ul><li><a href="https://golang.org/doc/diagnostics.html">golang.org: Diagnostics</a></li><li><a href="https://golang.org/pkg/runtime/pprof/">golang.org: Package runtime/pprof</a></li><li><a href="https://golang.org/pkg/net/http/pprof/">golang.org: Package net/http/pprof</a></li><li><a href="https://blog.golang.org/profiling-go-programs">golang.org: Profiling go programs</a></li><li><a href="https://github.com/google/pprof/blob/master/doc/README.md">github.com: Go tool pprof</a></li><li><a href="https://jvns.ca/blog/2017/09/24/profiling-go-with-pprof/">Julia Evans: Profiling Go with pprof</a></li><li><a href="https://gist.github.com/Jimmy-Xu/85fb01cd7620454c6d65">Jimmy-Xu: pprof in docker daemon</a></li><li><a href="https://about.sourcegraph.com/go/an-introduction-to-go-tool-trace-rhys-hiltner">Rhys Hiltner: An introduction to go tool trace</a></li><li><a href="https://youtu.be/mmqDlbWk_XA">Rhys Hiltner: Go’s execution tracer (youtube)</a></li><li><a href="http://blog.ralch.com/tutorial/golang-performance-and-memory-analysis/">Svet Ralchev: Performance and memory analysis of Golang programs</a></li><li><a href="https://github.com/bradfitz/talk-yapc-asia-2015/blob/master/talk.md">Brad Fritzpatrick: Profiling &amp; Optimizing in Go</a></li><li><a href="https://making.pusher.com/go-tool-trace/">Will Sewell: go tool trace</a></li></ul><ol><li><a href="http://www.brendangregg.com/flamegraphs.html">http://www.brendangregg.com/flamegraphs.html</a></li><li><a href="https://golang.org/doc/diagnostics.html">https://golang.org/doc/diagnostics.html</a></li></ol><p><em>Originally published at </em><a href="https://bruinsslot.jp/post/profiling-golang-docker-2"><em>https://bruinsslot.jp/post/profiling-golang-docker-2</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d29431fbb427" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-profile-go-applications-inside-a-docker-container-d29431fbb427">How to profile Go applications inside a docker container</a> was originally published in <a href="https://itnext.io/">ITNEXT</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 profile Python applications inside a docker container]]></title>
            <link>https://itnext.io/how-to-profile-python-applications-inside-a-docker-container-ed59bcc22696?source=rss-759fb6cac80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed59bcc22696</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Jan Pieter Bruins Slot]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 14:28:00 GMT</pubDate>
            <atom:updated>2020-03-06T08:45:13.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P8G4VLrSSounF203" /><figcaption>Photo by <a href="https://unsplash.com/@templecerulean?utm_source=medium&amp;utm_medium=referral">Temple Cerulean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the following post I’ll explain how you can profile a running Python program in a Docker container using <a href="https://github.com/benfred/py-spy">py-spy</a>. py-spy is able to generate <a href="http://www.brendangregg.com/flamegraphs.html">flame graphs</a>, and it can give us profiling capabilities in order to debug our Python programs. Now, when your Python code is running in a Docker container it can be a bit more difficult to profile your code, and this post sets out to show you how this can be done with these tools.</p><p>Before we can profile the Python application, we need to set up the tools, and example files, that we will be using in this project. You can inspect the finished result <a href="https://github.com/erroneousboat/profile-python-docker">here</a>.</p><h3>1.1 Project</h3><p>Let’s get started with the project outline, and create the following files and folders, the docker-compose.yml is optional because I will show you how to use plain docker as well.</p><pre>$ tree -L 1 --dirsfirst<br>.<br>├── app/<br>├── pyspy/<br>└── docker-compose.yml</pre><h3>1.2 py-spy</h3><p>In the pyspy/ folder we will be creating a Dockerfile that we&#39;re going to use to create a Docker container that contains the py-spy program. The Dockerfile should contain the following:</p><pre># pyspy/Dockerfile<br>FROM python:3.6<br>RUN pip install py-spy<br>WORKDIR /profiles<br>ENTRYPOINT [ &quot;py-spy&quot; ]<br>CMD []</pre><p>Let’s test if is is working:</p><pre>$ cd pyspy/<br>$ docker build -t pyspy .<br>$ docker run -it pyspy</pre><pre>py-spy 0.3.0<br>Sampling profiler for Python programs</pre><pre>USAGE:<br>    py-spy &lt;SUBCOMMAND&gt;</pre><pre>OPTIONS:<br>    -h, --help       Prints help information<br>    -V, --version    Prints version information</pre><pre>SUBCOMMANDS:<br>    record    Records stack trace information to a flamegraph, speedscope<br>              or raw file<br>    top       Displays a top like view of functions consuming CPU<br>    dump      Dumps stack traces for a target program to stdout<br>    help      Prints this message or the help of the given subcommand(s)</pre><p>Cool, that worked! Now, you’re also able to install py-spy locally on your host system. When you do, be sure to read the documentation at: <a href="https://github.com/benfred/py-spy">https://github.com/benfred/py-spy</a>, on how to do this.</p><h3>1.3 Python</h3><p>Next, we want to create a Python program that we will use to profile. Create a new file in the app/ folder name run.py and copy the contents into it.</p><pre># app/run.py<br>import random</pre><pre>def factorial(n):<br>    factorial = 1<br>    for i in range(1, n + 1):<br>        factorial *= i</pre><pre>    return factorial</pre><pre>if __name__ == &quot;__main__&quot;:<br>    while True:<br>        n = random.choice(range(1, 5))<br>        f = factorial(n=n)</pre><pre>        print(&quot;Factorial of {n} is {f}&quot;.format(n=n, f=f))</pre><p>Next, create a Dockerfile in the app/ folder:</p><pre># app/Dockerfile<br>FROM python:3.6<br>WORKDIR /usr/src/app<br>COPY run.py .<br>CMD [ &quot;python&quot;, &quot;./run.py&quot; ]</pre><p>And again, let’s see if it is working:</p><pre>$ cd app/<br>$ docker build -t app .<br>$ docker run -t app</pre><p>Press Control-C to exit the program.</p><h3>1.4 Docker Compose</h3><p>I promised that I’ll show you how to also use Docker Compose to orchestrate our containers. Create docker-compose.yml file and add the following to it:</p><pre># docker-compose.yml<br>version: &quot;3&quot;<br>services:</pre><pre>pyspy:<br>    build:<br>      context: pyspy/<br>    pid: &quot;host&quot;<br>    privileged: &quot;true&quot;<br>    volumes:<br>      .:/profiles</pre><pre>app:<br>    build:<br>      context: app/<br>    cap_add:<br>     - sys_ptrace</pre><p>Now, we can build the containers like so:</p><pre>$ docker-compose build</pre><p>You’ll probably wondering about what the pid, privileged and cap_add is used for, and I&#39;ll get to that in the next section.</p><p>We’ve set everything up and we’re ready to test everything. First, let’s run the python program. We need to add --cap-add sys_ptrace, because by default Docker images do not have the SYS_PTRACE capability. And this is because Docker is restricting the process_vm_readv system call that py-spy uses to directly read the memory of the Python program.</p><pre># docker<br>$ docker run --cap-add sys_ptrace -t app --name py-app</pre><pre># docker-compose<br>$ docker-compose up app</pre><p>Now, before we’re able to use the py-spy program, we need to get the PID of the Python program that is running in the container. We will be using the PID of the program, and py-spy is going to sample from it.</p><pre># docker<br>$ docker inspect --format &#39;{{.State.Pid}}&#39; py-app<br>26982</pre><pre># docker-compose<br>$ docker inspect --format &#39;{{.State.Pid}}&#39; profile-python-docker_app_1<br>26982</pre><p>Now, that we’ve got the PID we need the py-spy container to be able to use this PID inside it&#39;s container. So we need to use the host&#39;s PID namespace inside this container, and we do that by adding the flag--pid=host to the run command. Additionally, we need to add the--privileged flag, so that it allows the container the same access to the host as processes running outside containers on the host.</p><pre># docker: change $(pwd) where you want the profiles to be saved<br>$ docker run \<br>    --pid=host \<br>    --privileged \<br>    -v $(pwd):/profiles \<br>    -it pyspy record -o myprofile.svg --pid 26982</pre><pre># docker-compose<br>$ docker-compose run pyspy record -o myprofile.svg --pid 26982</pre><p>You can now open the myprofile.svg file with a browser and look at the flamegraph that was created, and you&#39;ll be able to interpret the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3EcHtQCfgrSS0t1q.png" /></figure><p>The horizontal axis represents the total number of samples collected. So the larger the area, the more time has been spent executing the associated function. The vertical axis represents the depth of the call stack. So the higher the peak, the deeper the call stack. Colors don’t represent anything specific; they’re just there to make a visual contrast. ( <a href="http://www.brendangregg.com/flamegraphs.html">source</a>)</p><p>A cool feature of py-spy is that we can also create our profiles in the <a href="https://www.speedscope.app/">speedscope</a> and inspect it with the online tool. Add the--format speedscope flag to the command and you&#39;ll be able to import the profile in the speedscope format.</p><h3>Conclusion</h3><p>Now, you’ve got a basic setup to profile your Python applications in a Docker container. So, be sure to read up on all the features and options of so that you can fully utilize it and, profile your Python applications in Docker containers.</p><p><em>Originally published at </em><a href="https://bruinsslot.jp/post/profiling-python-docker/"><em>https://bruinsslot.jp</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed59bcc22696" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-profile-python-applications-inside-a-docker-container-ed59bcc22696">How to profile Python applications inside a docker container</a> was originally published in <a href="https://itnext.io/">ITNEXT</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 profile Go applications inside a docker container]]></title>
            <link>https://medium.com/@0x4a50/how-to-profile-go-applications-inside-a-docker-container-461466645356?source=rss-759fb6cac80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/461466645356</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Jan Pieter Bruins Slot]]></dc:creator>
            <pubDate>Tue, 19 Nov 2019 09:45:13 GMT</pubDate>
            <atom:updated>2020-03-03T13:52:07.073Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>NOTE: This post has been updated and you can view its updated version </em></strong><a href="https://itnext.io/how-to-profile-go-applications-inside-a-docker-container-d29431fbb427"><strong><em>here</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UmV6WP-sEp2fOyZk" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post I’ll give a quick overview of several methods you can use for profiling/debugging Go applications that are running in a docker container. To get a more in-depth overview of the several methods, I’ve added the source links you can reference.</p><h3>general sources</h3><ul><li><a href="https://deferpanic.com/blog/understanding-golang-memory-usage/">Defer Panic — understanding golang memory usage</a></li><li><a href="https://blog.golang.org/profiling-go-programs">golang.org — profiling go programs</a></li><li><a href="https://gist.github.com/Jimmy-Xu/85fb01cd7620454c6d65">Jimmy-Xu — pprof in docker daemon</a></li></ul><h3>pprof</h3><p>When you want to use pprof to profile your Go applications, that are running in a container, we need to make sure we turn on the internal pprof HTTP endpoints. We’ll do this by updating the source code of your application. What follows is an example of how you would enable those endpoints.</p><pre>// main.go<br>import (<br>    _ &quot;net/http/pprof&quot;<br>    _ &quot;expvar&quot;<br>    &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br>    // OPTION 1: Add this to your application<br>    go func() {<br>        http.ListenAndServe(&quot;0.0.0.0:6060&quot;, nil)<br>    }()</pre><pre>    // OPTION 2: When using gorilla mux you can do the following:<br>    router := mux.NewRouter()<br>    router.HandleFunc(&quot;/debug/pprof/&quot;, pprof.Index)<br>    router.HandleFunc(&quot;/debug/pprof/cmdline&quot;, pprof.Cmdline)<br>    router.HandleFunc(&quot;/debug/pprof/profile&quot;, pprof.Profile)<br>    router.HandleFunc(&quot;/debug/pprof/symbol&quot;, pprof.Symbol)<br>    router.HandleFunc(&quot;/debug/pprof/trace&quot;, pprof.Trace)<br>    router.Handle(&quot;/debug/pprof/goroutine&quot;, pprof.Handler(&quot;goroutine&quot;))<br>    router.Handle(&quot;/debug/pprof/heap&quot;, pprof.Handler(&quot;heap&quot;))<br>    router.Handle(&quot;/debug/pprof/threadcreate&quot;, pprof.Handler(&quot;threadcreate&quot;))<br>    router.Handle(&quot;/debug/pprof/block&quot;, pprof.Handler(&quot;block&quot;))<br>    router.Handle(&quot;/debug/vars&quot;, http.DefaultServeMux)<br>    http.ListenAndServe(&quot;0.0.0.0:6060&quot;, router)<br>}</pre><p>Now, we need to make sure that we’re able to access those endpoints. When you’re using docker-compose update your docker-compose.yaml file as follows:</p><pre>// docker-compose.yaml<br>version: &quot;3&quot;<br>services:<br>  app:<br>    build: ./build-dir<br>    ports:<br>      - &quot;6060:6060&quot;</pre><p>Once you’ve updated the files you’ll be able to access the endpoints by using your browser and to go to <a href="http://localhost:8888/tree">http://localhost:6060/debug/pprof/</a>, or you can use go tool pprof:</p><pre># Heap profile<br>#<br># optional flags:<br>#   –alloc_space tells you how many megabytes have been allocated.<br>#   –inuse_space tells you know how many are still in use.<br>$ go tool pprof <a href="http://localhost:6060/debug/pprof/heap">http://localhost:6060/debug/pprof/heap</a></pre><pre># CPU profile<br>$ go tool pprof <a href="http://localhost:6060/debug/pprof/profile">http://localhost:6060/debug/pprof/profile</a></pre><pre># Using trace tool<br>$ curl <a href="http://localhost:6060/debug/pprof/trace?seconds=5">http://localhost:6060/debug/pprof/trace?seconds=5</a> &gt; trace.out<br>$ go tool trace trace.out</pre><pre># Create a heap dump and analyze it locally<br>$ curl <a href="http://localhost:6060/debug/pprof/heap">http://localhost:6060/debug/pprof/heap</a> &gt; heap.out<br>$ go tool pprof -runtime --inuse_space [your-binary-here] heap.out</pre><p>One thing to remember is: if you’re making cpu profiles that take a certain amount of time you need to specify that your server is able to handle those long request times. You typically want to add the following to your http.Server:</p><pre>srv := &amp;http.Server{<br>    WriteTimeout: 30 * time.Second,<br>}</pre><h4>sources</h4><ul><li><a href="https://golang.org/pkg/net/http/pprof/">Go — Package profile</a></li><li><a href="https://blog.golang.org/profiling-go-programs">Go Blog — Profiling Go Programs</a></li><li><a href="http://blog.ralch.com/tutorial/golang-performance-and-memory-analysis/">Svet Ralchev — Performance and memory analysis of Golang programs</a></li><li><a href="http://stackoverflow.com/q/19591065">Stack Overflow — Profiling Go web application built with Gorilla’s mux with net/http/pprof</a></li><li><a href="https://github.com/bradfitz/talk-yapc-asia-2015/blob/master/talk.md">Brad Fritzpatrick — Profiling &amp; Optimizing in Go</a></li><li><a href="https://making.pusher.com/go-tool-trace/">Pusher — go tool trace</a></li><li><a href="https://youtu.be/Xq5HDH8y0CE">Pusher — Introduction to go tool trace</a></li><li><a href="https://youtu.be/mmqDlbWk_XA">Rhys Hiltner — Go’s execution tracer</a></li><li><a href="https://deferpanic.com/blog/goroutine-tracing/">Defer Panic — Goroutine Tracing</a></li><li><a href="https://medium.com/square-corner-blog/always-be-closing-3df5da0e00da">Alec Holmes — always be closing</a></li></ul><h3>gcvis</h3><p>To use gcvis to profile our applications we need to first install it:</p><pre>go get -u github.com/davecheney/gcvis</pre><p>Now update your docker-compose.yaml file, important is to set the GODEBUG environment variable:</p><pre>// docker-compose.yaml<br>version: &quot;3&quot;<br>services:<br>  app:<br>    build: ./build-dir<br>    environment:<br>      - GODEBUG=gctrace=1</pre><p>Once you’ve updated the docker-compose.yaml file, run your container with the command below, and gcvis will start a browser for you automatically.</p><pre>$ docker-compose up app | gcvis</pre><h4>sources</h4><ul><li><a href="https://github.com/davecheney/gcvis">Github — gcvis</a></li><li><a href="https://dave.cheney.net/2014/07/11/visualising-the-go-garbage-collector">Dave Cheney — Visualising the Go garbage collector</a></li></ul><h3>go-torch</h3><p>When using go-torch, first update your code to enable the pprof endpoints. Reference the section on how to do that. Next, you need to get go-torch:</p><pre>$ go get -u github.com/uber/go-torch<br>$ git clone <a href="/service/mailto:git@github.com">git@github.com</a>:brendangregg/FlameGraph.git<br>$ export PATH=$PATH:/path/to/FlameGraph</pre><p>And you can run it as follows:</p><pre>$ go-torch -u <a href="http://localhost:6060/">http://localhost:6060/</a></pre><h4>sources</h4><ul><li><a href="https://github.com/uber/go-torch">Github — go-torch</a></li></ul><p><em>Originally published at </em><a href="https://bruinsslot.jp/post/profiling-golang-docker/"><em>https://bruinsslot.jp</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=461466645356" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A minimal REST API Django setup as a microservice]]></title>
            <link>https://medium.com/@0x4a50/a-minimal-rest-api-django-setup-as-a-microservice-3199917519e4?source=rss-759fb6cac80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3199917519e4</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jan Pieter Bruins Slot]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 13:18:52 GMT</pubDate>
            <atom:updated>2019-11-19T13:09:45.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RAhuqfVfwn93JHe_" /><figcaption>Photo by <a href="https://unsplash.com/@victoire_jonch?utm_source=medium&amp;utm_medium=referral">Victoire Joncheray</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post I will set out on how to set up a Django project that can be used as a REST API microservice. To see the end result, you can investigate the code <a href="https://github.com/erroneousboat/minimal-django">here</a>. An important disclaimer: the code presented here is to be used in a development environment, review security practices for the framework(s) when you want to use it in production or expose it to the internet.</p><h3>1. Project structure</h3><p>We will be using the following stack:</p><pre>| Name           | Version    |<br>|----------------|------------|<br>| Docker         | 18.03.1-ce |<br>| Python         | 3.8        |<br>| Django         | 2.2.7      |<br>| PostgreSQL     | 12.0       |<br>| Gunicorn       | 20.0.0     |<br>| DRF            | 3.10.3     |</pre><p>Let’s first start with the project structure and create some files and folders. Create the following files and folders:</p><pre>$ tree -L 1 --dirsfirst . <br>├── config/ <br>├── docker-compose.yml <br>├── Dockerfile <br>└── README.md</pre><p>First update our Dockerfile:</p><pre>$ cat Dockerfile<br>FROM python:3.8<br>COPY . /srv/minimal-django<br>RUN pip3 install -r /srv/minimal-django/config/requirements.txt<br>CMD [ &quot;gunicorn&quot;, &quot;--config&quot;, \<br>    &quot;/srv/minimaldjango/config/gunicorn.py&quot;, \<br>    &quot;minimal_django.wsgi&quot; \<br>]</pre><p>We will use a Python base image, and of course you can choose your own base image as you like. In the Dockerfile we’ll define that we need to copy the code, and install the Python package requirements. Lastly, we use Gunicorn as the WSGI application server.</p><p>Now, for convenience sake we’re using docker-compose to orchestrate our docker containers. So we will add the following contents to our docker-compose.yml file:</p><pre>$ cat docker-compose.yml<br>version: &quot;3&quot;<br>  volumes:<br>   postgres:<br>     driver: local<br>  services:<br>     postgres:<br>       image: postgres:12.0<br>       environment:<br>         - POSTGRES_NAME=postgres<br>         - POSTGRES_USER=postgres<br>         - POSTGRES_PASSWORD=mysecretpassword<br>         - PGDATA=pgdata<br>       volumes:<br>         - postgres:/var/lib/postgresql/data/pgdata<br>     minimal_django:<br>       build:<br>         context: .<br>       ports:<br>         - &quot;4001:4001&quot;<br>       volumes:<br>         - .:/srv/minimal_django<br>       depends_on:<br>         - postgres</pre><p>We will be using PostgreSQL as our datastore in this example, and we will calling our Django application minimal_django.</p><p>Next, we need to add the configuration files in the folder config/, and we will add the following files:</p><pre>$ ls config/<br>gunicorn.py requirements.txt</pre><p>But first, let’s add the python packages we will using in the Django application, and we will be adding those in the requirements.txt file.</p><pre>$ cat config/requirements.txt<br>django==2.2.7<br>gunicorn==19.9.0<br>psycopg2-binary==2.8.4<br>djangorestframework==3.10.3</pre><p>As you can see we will be using <a href="https://www.django-rest-framework.org/">Django REST Framework</a> for the REST API. Next up we will create the Django project.</p><h3>2. Create the Django project</h3><p>Now, that we have the basic structure set up. We need to create an actual Django project, and we will be using the Docker container for this. This way we don’t necessarily install Django on our host system.</p><p>First, build the minimal_django container.</p><pre>$ docker-compose build minimal_django</pre><p>Second, we will start an interactive shell in the minimal_django container.</p><pre>$ docker-compose run minimal_django sh</pre><p>Third, we will create the Django project by executing the following command in the attached shell:</p><pre># cd /srv/minimal-django # django-admin startproject minimal_django</pre><p>We’ve created the project ‘inside’ the container, and because we’ve attached a volume to the location of the files. So now we need to fix the file permissions on our host system, because they have been created as the root account. So, exit from the shell in the docker container, and change the owner of the folder that we’ve just created.</p><pre>$ chown -R $USER:$USER minimal_django/</pre><p>Because this will be a minimal Django implementation we will updating the settings.py file, and remove the non-essential elements.</p><ol><li>Update ALLOWED_HOSTS</li></ol><p>ALLOWED_HOSTS = [&quot;*&quot;]</p><p>2. Update INSTALLED_APPS</p><p>INSTALLED_APPS = [ &#39;rest_framework&#39;, &#39;api&#39;, ]</p><p>3. Remove MIDDLEWARE, and its contents</p><p>4. Remove TEMPLATES, and its contents</p><p>5. Update the DATABASES dict</p><pre>DATABASES = {<br>     &#39;default&#39;: {<br>         &#39;ENGINE&#39;: &#39;django.db.backends.postgresql_psycopg2&#39;,<br>         &#39;NAME&#39;: &quot;postgres&quot;,<br>         &#39;USER&#39;: &quot;postgres&quot;,<br>         &#39;PASSWORD&#39;: &quot;mysecretpassword&quot;,<br>         &#39;HOST&#39;: &quot;postgres&quot;,<br>         &#39;PORT&#39;: &quot;5432&quot;,<br>     }<br>}</pre><p>6. Remove AUTH_PASSWORD_VALIDATORS, and its contents</p><p>7. Remove STATIC_URL, and its contents</p><p>8. Remove LANGUAGE_CODE, USE_I18N, USE_L10N, and its contents</p><p>9. Add the following Django REST Framework configuration</p><pre>REST_FRAMEWORK = {<br>     &quot;DEFAULT_RENDERER_CLASSES&quot;: [<br>         &#39;rest_framework.renderers.JSONRenderer&#39;,<br>     ],<br>     &quot;DEFAULT_AUTHENTICATION_CLASSES&quot;: [],<br>     &quot;DEFAULT_PERMISSION_CLASSES&quot;: [],<br>     &quot;UNAUTHENTICATED_USER&quot;: None,<br>     &#39;PAGE_SIZE&#39;: 10,<br>     &#39;DEFAULT_PAGINATION_CLASS&#39;: \<br>         &#39;rest_framework.pagination.LimitOffsetPagination&#39;,<br>     &#39;DEFAULT_FILTER_BACKENDS&#39;: [<br>         &#39;rest_framework.filters.OrderingFilter&#39;<br>     ],<br> }</pre><p>10. Adding logging configuration, this is optional and you can edit/update it to your preferences.</p><pre>LOGGING = {<br>     &#39;version&#39;: 1,<br>     &#39;disable_existing_loggers&#39;: True,<br>     &#39;formatters&#39;: {<br>         &#39;verbose&#39;: {<br>             &#39;format&#39;:<br>             &#39;%(pathname)s:%(lineno)d (%(funcName)s) &#39;<br>             &#39;%(levelname)s %(message)s&#39;,<br>         },<br>         &#39;simple&#39;: {<br>             &#39;format&#39;: &#39;%(levelname)s %(message)s&#39;<br>         },<br>     },<br>     &#39;handlers&#39;: {<br>         &#39;null&#39;: {<br>             &#39;level&#39;: &#39;DEBUG&#39;, &#39;class&#39;: &#39;logging.NullHandler&#39;,<br>         },<br>         &#39;stderr&#39;: {<br>             &#39;level&#39;: &#39;DEBUG&#39;,<br>             &#39;formatter&#39;: &#39;simple&#39;,<br>             &#39;class&#39;: &#39;logging.StreamHandler&#39;,<br>         },<br>     },<br>     &#39;loggers&#39;: {<br>         &#39;django&#39;: {<br>             &#39;handlers&#39;: [&#39;stderr&#39;],<br>             &#39;propagate&#39;: True,<br>             &#39;level&#39;: &#39;WARNING&#39;,<br>         },<br>     },<br> }</pre><p><strong>NOTE</strong>: Again, this is not a production ready configuration!</p><h3>4. Configuring the Django api app</h3><p>Now we are ready to create the Django app. We will call it api, and within it we will create a simple REST API. First, create a folder in which it will be contained.</p><pre>$ mkdir minimal_django/api/</pre><p>Inside this folder create the following files:</p><pre>$ ls minimal_django/api/<br>__init__.py models.py serializers.py urls.py views.py</pre><p>We will start with the file models.py, and we will create a very simple model.</p><pre># minimal_django/api/models.py<br>from django.db import models<br></pre><pre>class Pet(models.Model):<br>     name = models.CharField(max_length=64)</pre><p>Next, update the views.py file where we will add the Django Rest Framework ViewSet.</p><pre># minimal_django/api/views.py<br>from rest_framework import viewsets<br>from api.models import Pet<br>from api.serializers import PetSerializer</pre><pre>class PetViewSet(viewsets.ModelViewSet):<br>    queryset = Pet.objects.all()<br>    serializer_class = PetSerializer</pre><p>Create and update the serializers.py file that will be used in our application.</p><pre># minimal_django/api/serializers.py<br>from rest_framework import serializers<br>from api.models import Pet<br></pre><pre>class PetSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Pet<br>        fields = (&#39;name&#39;, )</pre><p>Update theurls.py file, and we will use the Django Rest Framework default routers.</p><pre># minimal_django/api/urls.py<br>from django.conf.urls import include, url<br>from rest_framework.routers import DefaultRouter</pre><pre>from api import views</pre><pre>router = DefaultRouter()<br>router.register(r&#39;pets&#39;, views.PetViewSet)</pre><pre>urlpatterns = [url(https://medium.com/r&#39;^&#39;,%20include(router.urls))]</pre><p>Also update theurls.py file, of the Django project itself and remove the paths to the admin environment.</p><pre># minimal_django/urls.py<br>from django.conf.urls import url, include</pre><pre>urlpatterns = [ url(https://medium.com/r&#39;^&#39;,%20include(&#39;api.urls&#39;)), ]</pre><h3>5. Configuring Gunicorn</h3><p>We will be using <a href="https://gunicorn.org/">Gunicorn</a> as the WSGI application server. Create and update the gunicorn.py file with the following content. Refer to the <a href="http://docs.gunicorn.org/en/latest/settings.html">configuration documentation</a> for more configuration options.</p><pre># config/gunicorn.py</pre><pre># Documentation at: <a href="http://docs.gunicorn.org/en/latest/index.html">http://docs.gunicorn.org/en/latest/index.html</a><br>django_project_name = &quot;minimal_django&quot;</pre><pre># Chdir to specified directory before apps loading<br>chdir = &quot;/srv/minimal-django/minimal_django&quot;</pre><pre># The socket to bind to<br>bind = &quot;:4001&quot;</pre><pre># The class of worker processes for handling requests<br>worker_class = &quot;sync&quot;</pre><pre># Is a number of OS processes for handling requests<br>workers = 4</pre><pre># Is a maximum count of active greenlets grouped in a pool that will be<br># allowed in each process<br>worker_connections = 1000</pre><pre># The maximum number of requests a worker will process before restarting<br>max_requests = 5000</pre><pre># Workers silent for more than this many seconds are killed and restarted<br>timeout = 120</pre><pre># Set environment variable<br>raw_env = \<br>    [&quot;DJANGO_SETTINGS_MODULE={}.settings&quot;.format(django_project_name)]</pre><pre># The access log file to write to, &quot;-&quot; means to stderr<br>accesslog = &quot;-&quot;</pre><pre># The error log file to write to, &quot;-&quot; means to stderr<br>errorlog = &quot;-&quot;</pre><h3>6. Start it up</h3><p>Before we can run the application, we need to make initial migrations and propagate the model definition into our database schema. We will be using our Docker container to create those migrations, and again as a result we need to change the folder permissions in the end.</p><pre># First start the postgresql container<br>$ docker-compose up -d postgres</pre><pre># Create the migrations<br>$ docker-compose run minimal_django \<br>    /srv/minimal-django/minimal_django/manage.py \<br>    makemigrations api</pre><pre># Actually migrate the schema<br>$ docker-compose run minimal_django \<br>    /srv/minimal-django/minimal_django/manage.py \<br>    migrate</pre><pre># Reset the folder permissions of the created migrations folder<br>$ chown -R $USER:$USER minimal_django</pre><p>With that done we’re able to run our application, since we already started our postgresql container we will able to execute the following command.</p><pre>$ docker-compose up minimal_django</pre><p>Now, the application should be running and you’ll be able to access the API with curl or any other method.</p><pre>$ curl <a href="http://localhost:4001/pets/">http://localhost:4001/pets/</a></pre><p><em>Originally published at </em><a href="https://bruinsslot.jp/post/minimal-django/"><em>https://bruinsslot.jp</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3199917519e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>