<?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 Sandeep Dinesh on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Dinesh on Medium]]></description>
        <link>https://medium.com/@SandeepDinesh?source=rss-bba63600816e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Duqualbt7up5yFp39tlUgQ.jpeg</url>
            <title>Stories by Sandeep Dinesh on Medium</title>
            <link>https://medium.com/@SandeepDinesh?source=rss-bba63600816e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:06:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SandeepDinesh/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[Eliminating Next.js ISR Builds with Client Side Rendering]]></title>
            <link>https://medium.com/@SandeepDinesh/eliminating-next-js-isr-builds-with-client-side-rendering-2c30ee198831?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c30ee198831</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[continuous-deployment]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[optimism]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 15:02:36 GMT</pubDate>
            <atom:updated>2021-03-07T15:02:36.699Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the best Next.js features is <a href="https://blog.logrocket.com/incremental-static-regeneration-with-next-js/">Incremental Static Regeneration</a>. ISR combines the performance benefits of static generation with the flexibility of server rendered content. In a nutshell, ISR lets you create new static pages on the fly. As new requests come in, content on the page is refreshed on the server and the cached static page is updated. The first time an ISR page is visited, the user is shown a static “fallback” page until the first version of the page is built. After that, users are served a static page that automatically updates in the background!</p><p>At <a href="https://www.kbee.app?ref=blog">Kbee</a>, we let users turn their Google Docs into an ultra fast wiki. A big part in making it fast is making sure our users are served static html from a CDN. Our users might have thousands of documents and Kbee doesn’t know when content changes, so Kbee uses ISR to build static snapshots of the docs and dynamically refreshes content as new requests come in.</p><p>It’s a perfect fit for ISR, and <a href="https://vercel.com/">Vercel</a> makes all of this as simple as a git push! The rest of this blog post assumes you are using Vercel as other providers might have different quirks and nuances.</p><p>(<a href="https://www.producthunt.com/posts/kbee">Note: We are live on ProductHunt today! Come check it out!</a>)</p><h3>The Downside of ISR</h3><p>But like all good things in life, there is a price to pay for this magical experience. The initial load time or ISR content is <strong>significantly </strong>slower than SSR or even CSR content. Like <strong>orders of magnitude</strong> slower!</p><p>Here you can see two versions of the same page loading. One is SSR, the other the initial ISR page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*P-5b8WHDQUqJ-HkR5olibQ.gif" /><figcaption>WOW!</figcaption></figure><h4>Wow that’s a HUGE difference!</h4><p>Like HUGE!</p><p>At this point, you might be thinking: “Yes, but with ISR pages only have to be built once! After that they are cached and are super fast!”</p><p>Unfortunately, Vercel completely wipes the cache on every deployment. If you had thousands, tens of thousands, or even millions of pages of static pages, all those pages need to be rebuilt. If you are deploying multiple times per day, users are definitely going to run into slow loads all the time!</p><h3>Solution attempt #1: Deploy time builds</h3><p>The solution to this problem is to rebuild these pages at deploy time and pre-cache them. To do this, you use <a href="https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation">getStaticPaths</a> to query your database, get all the current pages, and build them all. Now pages that have already been built stay fast, and new pages go through the normal ISR process!</p><p>So we are done right? Well not so fast. This might be fine if you have a few hundred pages, but if you have millions of pages or pages that are expensive to render, your build times can quickly balloon to hours.</p><p>For us, builds went from 6 minutes (which is slow but not terrible) to 20 minutes! And we only had a handful of customers!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*krmkDFsZ9YkeGJ8W" /></figure><p>This method was not going to scale. We had to do something different.</p><h3>Why is it slow?</h3><p>To make something fast, we need to understand why it is slow. The obvious place to look was the actual building of the pages. Kbee makes multiple calls to Google Drive and Docs APIs to build the page, all of which can add up to 100s of milliseconds. Still, each page was taking a maximum of half a second to build. This was in line with the SSR load times, but the ISR load times were significantly slower.</p><p>Even stranger, calls to navigational pages which only made a single fast query into <a href="https://firebase.google.com/docs/firestore">Firestore </a>were still taking multiple seconds to render in ISR mode.</p><p>So why is ISR so slow? The clue was a single line in the build logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*9OI0R9CPuxlgeeI7" /></figure><p>This uploading step was taking longer and longer the more pages were statically built at deploy time. And then it all made sense. The initial ISR load time was slow because of this upload step!</p><p>With <strong>server side rendering</strong>, the process looks something like this:<br>1. Client makes request<br>2. Server renders page<br>3. Client displays page</p><p>With <strong>client side rendering</strong>, the process looks something like this:<br>1. Client makes request<br>2. Server sends static html<br>3. Client runs javascript to fetch data</p><p>4 Page is rendered</p><p>With <strong>ISR</strong>, the initial process looks like this (I am making an educated guess here):<br>1. Client makes request</p><p>2. Server sends fallback page<br>3. Server renders page<br>4. Server uploads page to CDN</p><p>5. Server tells client the CDN is ready<br>6. Client makes request to CDN<br>7. Client replaces fallback with content from the CDN</p><p>So it’s not the building of the page that’s slow, it’s the back and forth with the CDN!</p><h3>Solution attempt #2: Client Side Rendering on Fallback</h3><p>If the fetching of the data is relatively fast, can we build the page faster on the client side than waiting for the CDN dance to complete?</p><p><strong>The answer is a resounding yes.</strong></p><p>The way this works is you create an API route that returns the same data as the <a href="https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation">getStaticProps </a>method used to get the data for the ISR path. If the page is in fallback mode, you call the API route and render the page using traditional client side rendering. Once the CDN dance is complete, the page will automatically switch to the static html. Any new requests will load data from the CDN directly and not do any client side rendering.</p><p>For Kbee, I split the data fetching into two calls. The first one quickly gets metadata like the style, theme, and logos stored in Firestore to build the page scaffolding, and the other makes the slower request for the actual Google Docs content.</p><p>Here is a basic reproduction of the code to render a page like this:</p><pre>import { useRouter } from &#39;next/router&#39;</pre><pre>import { useEffect, useState } from &#39;react&#39;</pre><pre><br>export async function getStaticPaths() {</pre><pre>    return { paths: [], fallback: true }</pre><pre>}</pre><pre>export async function getStaticProps({ params }) {</pre><pre>    // Run your data fetching code here<br>    const data = &#39;something cool&#39;</pre><pre>    return { props: { data }, revalidate: 30, }</pre><pre>}</pre><pre>export default function Page({ data }) {</pre><pre>    const [clientData, setClientData] = useState(null)</pre><pre>    const { isFallback } = useRouter()<br></pre><pre>    useEffect(() =&gt; {</pre><pre>       if (isFallback &amp;&amp; !clientData) {</pre><pre>           // Get Data from API<br>           fetch(&#39;/api/getPageData&#39;).then(async resp =&gt; {</pre><pre>               setClientData(await resp.json())</pre><pre>           })</pre><pre>       }</pre><pre>     }, [clientData, isFallback])<br></pre><pre>    if (isFallback || !data) return &lt;RenderPage data={clientData} /&gt;</pre><pre>    else return &lt;RenderPage data={data} /&gt;</pre><pre>}</pre><p>There is a price to pay here because you are loading the same data twice. Once for the ISR page, and once for the CSR page. In my opinion, this is a small price to pay, and much smaller than the price you would pay for traditional SSR.</p><p>But there is still an issue, there always is 🙄</p><p>Next.js has a really cool <a href="https://nextjs.org/docs/api-reference/next/link">&lt;Link&gt; component</a> that looks and feels like a traditional anchor tag (think &lt;a href=’’&gt;) but instead of doing a full page reload, it does SPA style client side routing which makes it super fast and efficient. It also pre-fetches pages which lets you “warm up” the cache before the user visits the page which is awesome.</p><p>Except for one small problem. When routing to an ISR page, Next.js <strong>does not show the fallback</strong> and instead waits for the CDN dance to finish before showing the new page!</p><p>As pages take 5–6 seconds to load, the user thinks clicking the link did nothing and the website is broken! You can see folks complaining about this in <a href="https://github.com/vercel/next.js/issues/13751">this Github issue</a>.</p><h3>Solution attempt #3: The Fast SPA Abort</h3><p>The first thing to do here is to let the user know that something is happening and the website isn’t broken. The easiest way to do this is to add a loading bar, and you can follow the steps in this <a href="https://stackoverflow.com/a/55655850/1315987">Stack Overflow answer</a> to add a <a href="https://ricostacruz.com/nprogress/">nprogress</a> loading bar to your pages.</p><p>While a progress bar looks nice, it still takes a <strong>long </strong>time to navigate to the new page. What we really want to do is force Next.js to show the fallback page.</p><p>The naive solution is to replace all the &lt;Links&gt; with standard &lt;a&gt; tags. This will remove the client side routing and force a full page reload on every navigation. This solution really sucks, especially for folks that don’t have great internet. It feels janky and slow, and you lose one of the really powerful features of Next.js</p><p>So, I came up with a wacky solution I’m calling the “Fast SPA Abort”. It’s super simple. If a page navigation takes longer than 100ms to complete, abort the SPA routing and do a full page refresh. That’s it!</p><p>In your _app.js, add the following code:</p><pre>import NProgress from &#39;nprogress&#39;</pre><pre>import Router from &#39;next/router&#39;<br></pre><pre>Router.onRouteChangeStart = (url) =&gt; {</pre><pre>    if (url !== window.location.pathname) {</pre><pre>        window.routeTimeout = setTimeout(() =&gt; <br>             window.location = url, 100)</pre><pre>        NProgress.start()</pre><pre>    }</pre><pre>}</pre><pre>Router.onRouteChangeComplete = (url) =&gt; {</pre><pre>    clearTimeout(window.routeTimeout)</pre><pre>    NProgress.done()</pre><pre>}</pre><p>When the route starts to change, we create a timeout that will refresh the page in 100ms. When the route change finishes, we cancel this timeout. 99% of the time when doing a SPA navigation, the ISR pages are cached in the CDN so the routing will be instant and this timeout will never get called. However, if the page is not cached in the CDN, then the routing will be aborted and the page will be refreshed, showing the fallback!</p><p>Boom, now you get the best of all worlds. Fast SPA routing, dynamic static pages with ISR, and zero deploy-time builds with CSR!</p><p>P.S. If you read this far, <a href="https://www.producthunt.com/posts/kbee">check out Kbee on ProductHunt</a>! I’d love your support ♥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c30ee198831" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Copying Google Drive Folders with the Google Drive API]]></title>
            <link>https://medium.com/@SandeepDinesh/copying-google-drive-folders-with-the-google-drive-api-3473f09d4f3d?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3473f09d4f3d</guid>
            <category><![CDATA[process-automation]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[google-drive]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 15:42:30 GMT</pubDate>
            <atom:updated>2020-11-10T15:42:30.404Z</atom:updated>
            <content:encoded><![CDATA[<h4>Note: If you just want to copy folders, I’ve made the tool publicly available at <a href="https://drive.tools/copy-folders">https://drive.tools/copy-folders</a></h4><figure><img alt="No copy option :(" src="https://cdn-images-1.medium.com/max/837/1*Qxy-qlmVN11XlxSUMKQeAw.gif" /><figcaption>No option to copy folders :(</figcaption></figure><p>Recently we needed to copy a folder in Google Drive. To my surprise, this was… impossible?</p><p>Looking online, there were a bunch of people creating workarounds using things like <a href="https://developers.google.com/apps-script">Apps Script</a> or even the Google Drive desktop app to copy the folder locally and reupload it!</p><p>As a fun challenge, I wanted to see if I could build a tool in 24 hours that let you copy a folder without jumping through hoops.</p><p><strong>Note: This is not a step-by-step tutorial, I’m going to be focusing on the parts I found challenging / confusing so other folks trying similar things won’t be caught in the same way.</strong></p><h3>Getting Started</h3><p>The big goal for this app is that I wanted everything to run in the browser. This would both be faster and more secure as the Google Drive credentials never need to be stored or used by any server side code.</p><p>The first thing I did was look at the <a href="https://developers.google.com/drive/api/v3/quickstart/js">Google Drive Browser Quickstart</a>. There are some things to keep in mind though, especially around project and OAuth client creation. The buttons on that page seem to create a new Google Cloud project, which is less useful if you already have a project you want to use.</p><p>Instead I create a project in <a href="https://firebase.google.com">Firebase</a> instead of Google Cloud because it automatically creates an OAuth client and API key for you, saving a few steps.</p><p>After you have this project, you need to enable the Drive API and add the Drive scope to the OAuth client.</p><p><strong>You NEED to enable the API before adding the scope, otherwise it won’t show up!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNmssML4FQkeC1I2cJnG3Q.gif" /><figcaption>Enable Drive API</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAEjGKuPW25-J32DxVcvcA.gif" /><figcaption>Add Google Drive Scope</figcaption></figure><p>Unfortunately, Google Drive is a restricted scope and will require your app to go through review. If you just want to use the tool, I’ve already gone through the review and you can use it here: <a href="https://drive.tools/copy-folder">drive.tools/copy-folder</a></p><h3>Listing Folders</h3><p>The first thing our app needs to do is let you pick the folder you want to copy, and then pick the destination for where the folder should be copied to.</p><p>If you look at the sample code provided in the quickstart, it finds all the files in your Google Drive and prints them out:</p><pre>gapi.client.drive.files.list({<br>  &#39;pageSize&#39;: 10,<br>  &#39;fields&#39;: &quot;nextPageToken, files(id, name)&quot;<br>}).then(function(response) { do something with response })</pre><p>How do we change this to show only folders? If you look at the <a href="https://developers.google.com/drive/api/v3/reference/files/list">API docs for the “list” command</a>, you might notice there is a parameter called “q” that let’s you write a query with some examples listed <a href="https://developers.google.com/drive/api/v3/search-files#query_string_examples">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*XS89RCp4pNDsG64rKfN51w.png" /></figure><p>So using this, we can tell the query to only look for folders and make sure they are not in the trash.</p><pre>gapi.client.drive.files.list({<br>  &#39;q&#39;: `mimeType = &#39;application/vnd.google-apps.folder&#39; and trashed = false`,<br>  &#39;pageSize&#39;: 10,<br>  &#39;fields&#39;: &quot;nextPageToken, files(id, name)&quot;<br>}).then(function(response) { do something with response })</pre><p>Now it should be listing only folders, but they seem to be random and all over the place. We want to be able to navigate the folder tree like we do on the Google Drive interface. To do that, we can pass in a Parent ID:</p><pre>let parentID = &#39;root&#39;</pre><pre>gapi.client.drive.files.list({<br>  &#39;q&#39;: `&#39;${parentID}&#39; in parents and mimeType = &#39;application/vnd.google-apps.folder&#39; and trashed = false`,<br>  &#39;pageSize&#39;: 10,<br>  &#39;fields&#39;: &quot;nextPageToken, files(id, name)&quot;<br>}).then(function(response) { do something with response })</pre><p>You can see that we are using a special ID called “root” that will give us the top level of Google Drive. Once you select a folder, you can re-run this list command with the selected folder’s ID to get the next level of folders. If the list is empty, there are no more folders to explore into.</p><p>After wiring up the UI code, you should have both the ID of the folder you want to copy and the ID of the destination folder.</p><h3>Copying Files</h3><p>Copying files with Drive is pretty straight forward, but moving them to a new location can be a bit tricky.</p><pre>const oldFolderId = &lt;something&gt;<br>const newFolderId = &lt;something else&gt;</pre><pre>async file =&gt; {</pre><pre>// Create Copy of File<br>  const cloned = (await gapi.client.drive.files.copy({<br>   fileId: file.id<br>  })).result<br>  <br>  // Move copy to new folder<br>  await gapi.client.drive.files.update({<br>   fileId: cloned.id,<br>   addParents: newFolderId,<br>   removeParents: oldFolderId,<br>   resource: { name: file.name },<br>   fields: &#39;id, parents&#39;<br>  })<br>}</pre><h3>Copying Folders</h3><p>Copying folders takes everything we learned so far and combines it. It basically breaks down into five steps:</p><ol><li>Get the source folder and the destination folder</li><li>Make a new folder with the same name as the source folder in the destination folder</li><li>List all the files in the source folder, copy them, and move them to the new folder you created</li><li>List all the folders in the source folder</li><li>For folder you listed, run this process for each one.</li></ol><p>This is a classic recursion problem. Using async/await syntax, we can write the code in a pretty straightforward way.</p><pre>async function cloneFolder(from, to){</pre><pre> // Create new folder<br> const newFolder = (await gapi.client.drive.files.create({<br>  resource: {<br>    name: from.name,<br>    mimeType: &#39;application/vnd.google-apps.folder&#39;,<br>    parents: [to.id]<br>  }<br> })).result</pre><pre> // Find all sub-folders<br> const folders = (await gapi.client.drive.files.list({<br>  q: `&#39;${from.id}&#39; in parents and mimeType =  &#39;application/vnd.google-apps.folder&#39; and trashed = false`,<br>  pageSize: 100,<br>  fields: &#39;nextPageToken, files(id, name)&#39;<br> })).result.files</pre><pre> // Find all files <br> const files = (await gapi.client.drive.files.list({<br>  q: `&#39;${from.id}&#39; in parents and mimeType !=   &#39;application/vnd.google-apps.folder&#39; and trashed = false`,<br>  pageSize: 100,<br>  fields: &#39;nextPageToken, files(id, name)&#39;<br> })).result.files</pre><pre> files.forEach(async file =&gt; {<br>  // Create Copy of File<br>  const cloned = (await gapi.client.drive.files.copy({<br>    fileId: file.id<br>  })).result</pre><pre>  // Move copy to new folder<br>  await gapi.client.drive.files.update({<br>    fileId: cloned.id,<br>    addParents: newFolder.id,<br>    removeParents: from.id,<br>    resource: { name: file.name },<br>    fields: &#39;id, parents&#39;<br>  })<br> })</pre><pre> // Recursion<br> folders.forEach(folder =&gt; cloneFolder(folder, newFolder, false))</pre><pre>}</pre><h3>Final Words</h3><p>The majority of the work required to make <a href="https://drive.tools/copy-folder">drive.tools/copy-folder</a> was creating the UI. I used Tailwind CSS and React, but you could use anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*pdgQuixA7iRn0VV5qV7xNA.png" /></figure><p>I highly recommend <a href="https://www.npmjs.com/package/gapi-script">gapi-script package</a> from NPM to load the Google API instead of doing the callback method the quickstart uses. This lets you use the Google APIs in a way much more consistent with most other JavaScript packages and APIs.</p><p>Finally, while the example I give uses recursion, you can easily make this iterative as well. This may make things like updating the UI/State easier depending on how you are doing things!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3473f09d4f3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving EZSchool.com to Google Cloud Platform]]></title>
            <link>https://medium.com/@SandeepDinesh/moving-ezschool-com-to-google-cloud-platform-bbb845ccbc97?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb845ccbc97</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[migration]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Mon, 15 Jul 2019 22:00:08 GMT</pubDate>
            <atom:updated>2019-07-18T21:04:25.668Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot of the time, people like myself blog about greenfield apps, best practices, and the latest and greatest cutting edge technology. However, the reality is most real apps are never that easy or that clean.</p><p>Many people are not ready to go full-in on cloud-native hype technology, or they just don’t know where to start. The truth is, you can adopt a little at a time where it makes sense for you to do so.</p><p>In this blog post, I’ll share the story of how I moved EZSchool.com from a traditional LAMP stack running on a VPS to a containerized system running on GCE and Cloud SQL. I’ll share my thought process and the tradeoffs I had to make in a real world scenario.</p><p><strong>TL;DR:</strong> EZSchool is a monolithic PHP app with a MySQL database. Ops were challenging due to lack of best practices. Moved self hosted MySQL to Google Cloud SQL to benefit from a managed solution. Dockerized the PHP and Nginx layers to simplify operations. Considered Kubernetes, but found the cost of entry too high. Considered serverless, but found the change in developer workflow too high. Settled on running containers on a single GCE VM controlled with Docker Compose and startup scripts.</p><p><strong>Lesson Learned:</strong> You don’t have to use cutting edge tools and best practices to start your modernization journey. You can modernize slowly and only the pieces which make sense at the time.</p><h4>Shared PHP Hosting</h4><p><em>Skip to the </em><a href="https://blog.sandeepdinesh.com/posts/moving-ezschool/#modernization"><em>Modernization</em></a><em> section if you don’t want the long history lesson.</em></p><p>In 1998, my mom launched <a href="https://www.ezschool.com/">EZSchool.com</a>. EZSchool was one of the first “cloud-based” educational platforms, where teachers could manage all aspects of a classroom online. From assigning homework, give tests, and ensuring students were on the right track, the vision for EZSchool was ambitious.</p><p>Of course, being a bootstrapped startup in the early 2000s meant that the whole company ran out of two servers in the closet. One server ran Oracle DB, and the other ran Java Web Server 1.1 and has two (2!) physical CPU cores. Dual core baby. Of course, we were in the middle of <a href="https://en.wikipedia.org/wiki/California_electricity_crisis">Californina’s rolling blackouts</a>, so we also had a <a href="https://en.wikipedia.org/wiki/Uninterruptible_power_supply">UPS</a> that could power both servers for about 30 minutes before falling over. I vividly remember the noise they would make when activated; a power cut to the database server could potentially corrupt everything so when the UPS activated it was a mad scramble to cleanly shut everything down before it lost all power, even at 2am.</p><p>When the dot-com crash happened and funding dried up, all hopes of raising money vanished overnight. It looked like the end, but my mom was determined to push forward even if it would be a one-woman operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TS62l5LoEShQ4d3N.jpg" /><figcaption>My dad posing with EZSchool in the background!</figcaption></figure><p>At this point, it was clear EZSchool wouldn’t have the money to get space and servers in a <a href="https://en.wikipedia.org/wiki/Colocation_centre">colo facility</a>, and having servers at home that went down all the time was putting massive strain on everyone. So what was the solution?</p><p>Around this time, the concept of shared PHP Hosting was becoming more and more popular. For a few dollars a month, you basically got access to a folder on a server that had Apache and CPanel installed. From here, you could FTP HTML and PHP files over to the folder, and bam you have a running website. Of course, there were tons of limitations, the biggest of which was no database support. This meant all the “cloud based” ideas like an online classroom were cut and EZSchool pivoted to a free content platform (games, worksheets, tutorials, etc) that made money from display ads. These were the days that the online advertising market was taking off, and you could make good money from modest amounts of traffic.</p><p>So let’s recap:</p><ul><li>Deployments done with FTPing individual files</li><li>No source control</li><li>Shared hosting with limited functionality</li><li>No database</li><li>No local or test environment</li></ul><p>This also meant throwing away the existing Java codebase and starting from scratch in PHP.</p><h4>The VPS Era</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*5wlBnahYNJ8VFXMc.png" /></figure><p>Eventually, EZSchool got enough traffic that even the biggest shared hosting plan couldn’t support it. Remember, there was no way to isolate customers from each other in this model, it was all based on good faith. Our provider gave two choices, move to a “Virtual Private Server” or leave.</p><p>So once again, we had to migrate.</p><p>A VPS was a fully isolated Virtual Machine that was provisioned just for you. You got full root access to the machine and could do anything you wanted with it. Unlike shared PHP hosting, the resources for your VPS were pre-provisioned and dedicated for you.</p><p>Moving to a VPS had it’s pros and cons. More control means more flexibility, but it also means managing the OS updates and running Apache ourselves. Nothing too hard, especially since my mom was already familiar with Linux and bare metal servers.</p><h4>Nginx and MySQL</h4><p>Eventually, the little VPS we were using started to fall over as well. The biggest problem was Apache’s habit of spinning up individual processes for each request, which caused huge amounts of overhead. I started reading about a new web server called “nginx” that claimed to be a lot more performant with a lot less overhead. So along with upgrading to a bigger VPS, we moved from Apache to Nginx.</p><p>At the end of the day, we now had more computing power than we needed, and could start to do more. At this point, display ad revenue was getting worse and worse, so we decided to let people pay for memberships that would remove advertisements from the website. Because we had a VPS with full control, my mom spun up MySQL, created a PayPal integration, and implemented a membership program.</p><p>So let’s recap:</p><ul><li>Deployments done with FTPing individual files</li><li>No source control</li><li>VPS manually set up by running commands copied from blogs</li><li>Self managed NGINX webserver, configured by modifying nginx.conf in production</li><li>Self managed MySQL, manual backups</li><li>No local or test environment</li><li>“Ops” meant SSHing into the server, running commands, and crossing your fingers</li></ul><h4>Homecoming</h4><p>Now we had memberships and a fully functional database, it was time to come full circle and go back to the original vision of a “cloud based” learning platform. Of course by this time, this wasn’t a unique proposition anymore, but it still seemed like the right direction to go. I had just finished college, and I had a summer free before starting a full time job.</p><p>Over those three months, we designed a database driven platform, where all content was stored in MySQL or dynamically generated and then rendered by PHP and JavaScript. It was a big success, and over the next few years we moved everything to this model.</p><p>This let us remove hundreds of folders and thousands of static HTML and PHP files that were mostly all copies of each other and removed a bunch of manual, repetitive, and error prone work.</p><p>However, this “centralization” had some negative side effects. I remember a nasty hours-long outage where we overwrote a critical routing component, forcing us to literally rewrite it from scratch using ‘vim’ on the server, because we had no backups. So we finally adopted Git, yay! Still just pushed everything to master, but it was better than nothing! Another negative was increased resource usage, with more and more functions going through the database and PHP routers.</p><p>A huge issue was MySQL would randomly die, probably due to a spike in traffic causing memory issues. I say probably because monitoring consisted of looking at the default CPU/Memory graphs and our nginx logs and squinting really hard.</p><p>We also started running into ops issues. The “server setup” guide was a poorly updated Google Doc with commands copied from random blog posts I had found. While this initially worked, the production server had experienced config drift, and was getting more and more out of sync every day.</p><p>So let’s recap:</p><ul><li>Local development support by running a VM with the same setup as the server locally.</li><li>Deployments by running “git pull” on the server</li><li>Self managed NGINX web server, configured by modifying nginx.conf in production</li><li>Self managed MySQL, manual backups, that sometimes randomly shuts down</li><li>“Ops” meant SSHing into the server, running commands, and crossing your fingers</li></ul><h3>Modernization</h3><p>You still with me? Here is where things get interesting.</p><p>At this point, I had been working at Google Cloud for some time, and whenever I helped my mom with EZSchool it was like a blast from the ugly past. I knew we could be using a lot of new technology to simplify our lives, but my mom just didn’t have the cycles to learn and implement it.</p><p>Lucky for me, our contract with our VPS provider was coming to a close, and we were having some reliability issues with them. So, this was a good opportunity to both modernize and migrate EZSchool to GCP.</p><p>There were multiple goals for this project:</p><ol><li>Remove the guesswork and manual ops toil</li><li>Move to a managed MySQL service</li><li>Upgrade to PHP 7</li><li>Keep costs the same or lower them</li></ol><p>I won’t focus much on upgrading to PHP 7, except for saying that the massive improvement in performance over PHP 5 was amazing, and it was mostly backwards compatible with our PHP 5 code.</p><h4>To Docker or not to Docker</h4><p>One decision I made from the start was to move everything into containers. Using containers brings a lot of benefits. Upgrading the version of Nginx or PHP is much easier and safer than using the OS package manager. They also make it easy to add the nginx config into source control, as they can be mounted into the right place in the Nginx container easily. They also make running near identical stacks in prod and dev possible. Restarting everything is just one command, and support for auto-restart makes it even easier.</p><h4>Moving MySQL</h4><p>The first challenge was moving the MySQL server over to Google Cloud SQL. <a href="https://cloud.google.com/sql/docs/mysql/create-instance">Creating the instance was easy enough</a>, but how would weto move the data over?</p><p>One way would be to follow the <a href="https://cloud.google.com/sql/docs/mysql/migrate-data#migrating-to-sql">migration guide in the documentation</a>. This involves setting up our current server as an external master for Cloud SQL, waiting for all data to be replicated over, <strong>turning off the app</strong>, promoting Cloud SQL to master, and finally restarting the app to point to Cloud SQL.</p><p>So it seems pretty complicated, and you still have to experience downtime. The downtime would be super minimal, but it’s a lot of moving pieces. Can we trade off a little more downtime for a simpler migration?</p><p>Because we only had a few GB of data, I came up with a much simpler solution.</p><p>→ Run mysql-dump to dump the data into a .sql file</p><p>→ Compress .sql file with gzip</p><p>→ Upload compressed file to Google Cloud Storage with <a href="https://cloud.google.com/storage/docs/gsutil">gsutil</a></p><p>→ run ‘ <a href="https://cloud.google.com/sdk/gcloud/reference/sql/import/sql">gcloud sql import sql</a> ‘ command to load the data into the database</p><p>All in all, these steps took about 5 minutes to finish. Not bad! I then put these four commands into a bash script, and we were good to go.</p><h4>Cloud SQL Proxy</h4><p>There are many ways to connect to Cloud SQL from your application. I would highly recommend using the <a href="https://cloud.google.com/sql/docs/mysql/private-ip">Private IP</a> for better performance and security. On top of that, I would also use the <a href="https://cloud.google.com/sql/docs/mysql/connect-admin-proxy">Cloud SQL Proxy</a> to set up the connection.</p><p>I like the proxy for a few reasons:</p><ol><li>Emulates a connection on ‘localhost’ so it’s easier to keep Dev/Prod aligned</li><li>Does all the SSL management for you, so you get better security for free</li><li>If you are using Public IPs, the proxy lets you connect without whitelisting IPs</li><li>No need to hardcode IP addresses in config files or things like that, it uses the instance name which is much easier to reason about</li></ol><h3>The old architecture</h3><p>To come up with the new architecture, it was important to understand the current architecture and the issues it had.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*jGgxstswGrmnYJq_.png" /></figure><p>Pretty simple design, with some pretty big flaws.</p><p>So what were the goals for the new architecture:</p><ol><li>Ensure the day-to-day dev workflow was as close to the old system as possible</li><li>Maximize dev/prod parity</li><li>Automate ops (restarting the server in case of an issue, updating the base OS, etc)</li></ol><h3>The new architecture</h3><h4>Kubernetes?</h4><p>Because my day job was working with Kubernetes, the first thought I had was to move everything to Kubernetes. It would then look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*YbzkGYluufpsxWGA.png" /></figure><p>At this point I took a step back and weighed the pros and cons of this new architecture:</p><p>Good:</p><ul><li>Everything is declarative and stored in YAML files</li><li>Everything can be checked into source control</li></ul><p>Bad:</p><ul><li>A lot more moving pieces</li><li>Harder to debug</li></ul><p>Ugly:</p><ul><li>Cost goes from $20 for a single VPS to $50 — $60 a month (load balancer, f1-micro sql instance, 2 g1-small GKE nodes)</li><li>I have to teach my mom Kubernetes.</li><li>Completely different dev workflow</li></ul><p>It really seemed that Kubernetes was out of the picture for this project. The killer feature of Kubernetes, namely managing multiple microservices at scale, was basically unnecessary. We had a small monolith that really only needed one replica. We would be paying the cost of entry that Kubernetes brings of managing a complex system with none of the benefits.</p><h3>Serverless?</h3><p>My next thought was to use something serverless. These days, I would recommend <a href="https://cloud.google.com/run/">Cloud Run</a>, but that wasn’t an option when I was doing the migration. <a href="https://cloud.google.com/functions/">Google Cloud Functions</a> doesn’t support PHP, so that was out. That left <a href="https://cloud.google.com/appengine/docs/standard/">App Engine Standard</a> and <a href="https://cloud.google.com/appengine/docs/flexible/">App Engine Flex.</a></p><p>App Engine Standard seemed to be an ideal choice. It should dramatically reduce ops work and give us new features like traffic splitting and rolling updates. However, there was a fundamental problem with using App Engine, and that was Nginx. We had thousands of lines of routing rules in the form of HTTP 301 and 302 redirects. built up over years of operation, Unfortunately, App Engine requires rewriting them in a proprietary format which would be very time consuming. We also do some other interesting things in Nginx to get all the routing working the way we want, have a seperate non-public directory for dynamic question generation, and use <a href="http://www.brain-dump.org/projects/ciopfs/">CIOPFS</a> to make the website case insensitive due to legacy reasons.</p><p>App Engine Flexible was out due to the high price, which you can read more about <a href="https://medium.com/google-cloud/three-simple-steps-to-save-costs-when-prototyping-with-app-engine-flexible-environment-104fc6736495">here</a>.</p><p>If we were doing the migration these days, <a href="https://cloud.google.com/run/">Cloud Run</a> would be a great choice. Because it allows us to run arbitrary Docker containers, we have the option to run Nginx and keep all the routing rules and customizations we need. Let’s look at the pros and cons for <strong>Cloud Run</strong></p><p>Good:</p><ul><li>Zero ops overhead</li><li>Everything can be checked into source control</li><li>HTTPs for free (currently using CloudFlare and LetsEncrypt)</li><li>Costs should be much lower</li></ul><p>Bad:</p><ul><li>Harder to debug in production / perform hotfixes</li></ul><p>Ugly:</p><ul><li>Different dev workflow</li></ul><p>Cloud Run seems like a great solution with limited downsides. However, it does require a new dev workflow, which is the biggest hurdle to adoption. It would require a new container to be built and deployed on each change and would remove the ability to SSH into the machine to make hotfixes. Now, both of these things are actually features and good things to have, but it is different and thus harder for my mom to adopt. The biggest thing is it didn’t really exist when I was doing the migration! So I’m going to ignore it for now, but might take another look in a later post.</p><h3>The Solution</h3><p>So is it possible to take the positives from the Kubernetes world and use it without the downsides? We wanted to reduce the ops overhead, but didn’t need scalability. Running on a single VM was fine.</p><p>The solution I came up with was to use Docker Compose. Docker Compose gives some of the advantages of using Kubernetes when it comes to using multiple Docker Containers together on a single machine, is super simple to set up, and just requires a simple “docker compose up” to start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*m6NJEjViMvVz-ysy.png" /></figure><p>Good:</p><ul><li>Minimal ops overhead</li><li>Everything can be checked into source control</li><li>Same dev workflow</li><li>Dev/Prod parity</li></ul><p>Bad:</p><ul><li>No autoscaling</li></ul><p>Ugly:</p><ul><li>Hacky and not following best practices</li></ul><p>The biggest issue with this setup is that it doesn’t follow best practices. Containers are best when they are “immutable”. This would mean adding all the files into the container image when building it, and every time there is a change you should rebuild and retag the container and do a redeploy. Instead, we are just using a Docker Volume Mount to add in the appropriate Nginx config and the source code. However, I’m not trying to win any awards for the cleanest setup, my goal is to decrease ops toil and this hits the sweet spot perfectly.</p><h3>The details</h3><p>Coming up with this exact architecture took a little bit of time. After looking for a combination Nginx/PHP Docker container for quite a while and only finding a bunch of half baked images, I decided to run separate containers for Nginx and PHP and then link them together with Compose.</p><p>The PHP container’s Dockerfile is as follows:</p><pre>FROM php:7-fpm-alpine3.7 <br>RUN apk update &amp;&amp; docker-php-ext-install pdo pdo_mysql</pre><p>These were the options we needed, but obviously your application will be different. Check out the <a href="https://docs.docker.com/samples/library/php/">official documentation</a> for more configuration options.</p><p>For Nginx and MySQL, the official containers worked without any modification!</p><p>Now came the interesting part, using Docker Compose to maintain Dev/Prod parity. I wanted an easy way for the prod service to use Cloud SQL, but dev to use a local MySQL instance.</p><p>To do this, I used the <a href="https://docs.docker.com/compose/extends/">extension</a> feature of Compose to have two different MySQL configurations, but a base nginx and php configuration.</p><p>The base configuration looked like this:</p><pre>version: &#39;2&#39;<br><br>services:<br>   web:<br>       image: nginx:latest<br>       ports:<br>           - &quot;80:80&quot;<br>       volumes:<br>           - ./www:/home/ezschool/www<br>           - ./site.conf:/etc/nginx/conf.d/default.conf<br>           - ./nginx.conf:/etc/nginx/nginx.conf<br>           - ./nginx-logs:/var/log/nginx/<br>       networks:<br>           - code-network<br>   php:<br>       image: ezphp:1.0<br>       volumes:<br>           - ./www:/home/ezschool/www<br>           - ./php-fpm.conf:/usr/local/etc/php-fpm.d/custom-fpm.conf<br>           - ./custom-logs:/home/ezschool/www/Log<br>       networks:<br>           - code-network<br>networks:<br>   code-network:<br>       driver: bridge</pre><p>As you can see, Compose runs two containers with a shared bridge network. This is very similar to a Pod in Kubernetes, which is exactly what I want!</p><p>We mount in the config files using volume mounts, and make sure logs are saved outside the container. In an ideal world, we would not be doing these things. Containers work best when they are immutable, so ideally we should be running a build step that adds in all relevant files to the container and tags it with a unique ID. However, this means we need a CI/CD pipeline and more which we don’t have. This is a great topic for a future project. Similarly, logs shouldn’t be written to disk, but rather a logging service like <a href="https://cloud.google.com/logging/">Stackdriver</a>. However, because we only have one host, it was easy to set up <a href="https://cloud.google.com/logging/docs/agent/">fluentd</a> to send logs to stackdriver.</p><p>Now for the MySQL configuration. First, we have the local config stored as a file called “docker-compose.override.yaml”</p><pre>version: &#39;2&#39;<br><br>services:<br>    sql:<br>      image: mysql<br>      command: mysqld --user=root --verbose<br>      volumes:<br>        - ./mysql_init:/docker-entrypoint-initdb.d<br>      ports:<br>        - &quot;3306:3306&quot;<br>      environment:<br>        MYSQL_DATABASE: &quot;xxxx&quot;<br>        MYSQL_USER: &quot;xxxx&quot;<br>        MYSQL_PASSWORD: &quot;xxxx&quot;<br>        MYSQL_ROOT_PASSWORD: &quot;xxxx&quot;<br>        MYSQL_ALLOW_EMPTY_PASSWORD: &quot;yes&quot;<br>      networks:<br>          - code-network</pre><p>This file is a pretty standard MySQL setup. The only difference is the volume mount, which let’s us pre-populate the database with a snapshot of the data from prod in the form of a .sql file.</p><p>For production, we instead use the CloudSQL Proxy. In a file called “docker-compose.prod.yaml”:</p><pre>version: &#39;2&#39;<br><br>services:<br>   sql:<br>       image: gcr.io/cloudsql-docker/gce-proxy:1.11<br>       volumes:<br>           - /cloudsql:/cloudsql<br>       command: /cloud_sql_proxy -instances=ezschool-servers:us-central1:ezdatabase=tcp:0.0.0.0:3306<br>       networks:<br>           - code-network</pre><p>In this case, we are using the CloudSQL Proxy docker container instead of the standard MySQL one, and use the command section to configure it to connect to the correct database. You might also notice that we are not exposing the MySQL port anymore, which makes sense. In development, you might want to connect directly to the database, but in production you can use the <a href="https://cloud.google.com/sdk/gcloud/reference/sql/connect">gcloud cli</a> to connect to Cloud SQL.</p><h3>Finishing Up</h3><p>Finally, I created a few scripts to automate basic tasks. I created the following Makefile:</p><pre>restart: stop-server start-server<br>	@echo &quot;Server Restarted&quot;<br><br>start-server:<br>	docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d<br><br>start-local-server: stop-server<br>	docker-compose up -d<br>	@echo Waiting for MySQL to start...<br>	@sleep 30<br><br>stop-server:<br>	docker-compose down<br><br>sync-db:<br>	gcloud sql export sql ezdatabase gs://ezschool-database-backups/current.sql<br>	gsutil cp gs://ezschool-database-backups/current.sql ./mysql_init/data.sql</pre><p>Most of the commands are self-explanatory. The sync-db command is neat as it creates a new sql backup using gcloud, then copies it into the mysql_init folder using gsutil. This means you can get a fresh snapshot for local use by running “make sync-db start-local-server”</p><p>We pulled the code onto the new GCE server, and everything worked! Of course, I am glossing over the changes we had to make here and there due to slight differences in configuration and moving to PHP7, but all in all it was very minimal.</p><p>The last part was <a href="https://cloud.google.com/compute/docs/startupscript">creating a startup script</a> that would automatically start the containers on boot.</p><p>Now that everything was running, it was time to migrate. Like I said before, we were willing to deal with some downtime. So we SSH’d into the old server and stopped Nginx, ran the db migration script I had previously created, and then switched DNS to point to the new server. All in all, it took just 5 minutes!</p><h3>Conclusion</h3><p>At the end of the day, this was a great lesson in finding low hanging fruit. Did we follow all the best practices? Did we create the most optimized infrastructure? Do we have amazing automation and autoscaling? No, no and no. What we did do is cut our costs, increase our uptime, simplify ops, and establish dev/prod parity. I call that a job done well enough :P</p><p>Future Posts:</p><ol><li>Using Cloud Build to make immutable containers and a CD pipeline</li><li>Moving to Cloud Run</li></ol><p><em>Originally published at </em><a href="https://blog.sandeepdinesh.com/posts/moving-ezschool/"><em>https://blog.sandeepdinesh.com</em></a><em> on July 15, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb845ccbc97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get THREE times the capacity for your Kubernetes Cluster for FREE! Too good to be true?]]></title>
            <link>https://medium.com/swlh/get-three-times-the-capacity-for-your-kubernetes-cluster-for-free-too-good-to-be-true-6f0c3032c296?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f0c3032c296</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Thu, 08 Nov 2018 20:55:46 GMT</pubDate>
            <atom:updated>2018-11-14T06:33:12.982Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago, I read a <a href="https://news.ycombinator.com/item?id=17241412">conversation on Hacker News</a>. One poster postulated that you could run multiple nodes in a <a href="http://g.co/gke">Google Kubernetes Engine </a>cluster for the same price as one if you used <a href="https://cloud.google.com/preemptible-vms/">Preemptible VMs</a>.</p><p><a href="https://cloud.google.com/products/calculator/#id=7b38b894-861c-4720-a477-15025f89f6d0">Doing the math</a>, you can get 3 times the capacity for a lower price, and because Kubernetes takes care of rescheduling pods, you don’t have to worry about instances being preempted. Sounds amazing right?</p><p>From my personal experience and speaking with multiple advanced GKE users, it seemed like this method to save costs definitely works. I actually met a large GKE customer (500+ nodes) who runs all their stateless production workloads on 100% PVMs. They have reported no problems and are super happy with the cost savings.</p><p>So is everything is good to go? Well, the next comment attacked the idea and said <strong>“Your message obviously implies that you have no experience with what you are suggesting, hence why you don’t realize the downsides.”</strong></p><p>Wow, so harsh! Was this person right? Is it totally crazy to run your workloads purely on PVMs? Or could you actually get 3x the capacity with no downsides? Arguing on the internet only takes you so far, so I decided to actually run a test to see for myself.</p><p><strong><em>TL;DR:</em></strong><em> It works </em><strong><em>surprisingly well</em></strong><em>, but there are many caveats and I would only recommend this for advanced Kubernetes users in specific situations. </em><strong><em>In general, if you are not using PVMs to some degree in your GKE cluster, you are probably leaving money on the table.</em></strong></p><h3>The data we need</h3><p>To do this test in the most robust way possible, I wanted to collect:</p><ol><li>The average number of pods running at any given time,</li><li>The average number of nodes that are in the cluster</li><li>The lowest number of pods</li><li>The lowest number of nodes</li></ol><p>If you can run 10 pods on a regular GKE cluster, then you should be able to run 30 of those same pods on a Preemptible GKE cluster for the same price. But if the PVMs shut down so often that the average number of pods is less than 10 or even if the lowest number of pods drops below 10, then there will be disruptions. Same for Nodes: if it drops below 1, the PVMs will cause disruptions.</p><h3>The cluster(s)</h3><p>In order to give my cluster the best chance to do well, I decided to use a <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/regional-clusters">GKE Regional Cluster</a>. These are really cool, because they automatically spread over all three zones in a region and give you multiple masters for high availability. More importantly, it protects against PVM node stock-outs in a particular zone, which can happen if the Google Compute Engine system needs more VMs for standard nodes in that zone.</p><p>I created two clusters so I could test two different scenarios.</p><p>The first was a three-node PVM cluster, which is the default size of a cluster in GKE. But because they are all PVMs, this cluster is cheaper than a single n1-standard-1 instance. I’d say this setup is perfect for folks who want to kick the tires or are running test workloads, but want a cluster running 24/7.</p><p>The second is a six-node PVM cluster. This is double the size of a three-node cluster, but still 30% cheaper than a three-node cluster of standard VMs. I feel this is a much more realistic test for production systems because you can theoretically double your capacity and lower your costs at the same time.</p><h3>Data collection</h3><p>To collect the data, I knew I had to put together a few different services.</p><p>First, I needed to actually collect stats from the Kubernetes API. In order to do this, I created a DaemonSet that exposed a REST endpoint. This DaemonSet would use the Kubernetes APIs to find out how many nodes and pods were running in the cluster. I chose to use a DaemonSet because that was an easy way to ensure that there was always a copy running on each node, so unless all nodes were down I could ping at least one of them.</p><p>Second, I needed something off cluster to actually ping this DaemonSet and collect the data. To do this, I used <a href="https://cloud.google.com/appengine">Google App Engine</a> and the <a href="https://cloud.google.com/scheduler/">Google Cloud Scheduler</a> service. I used the cron service to run my App Engine function once a minute, but I needed more granularity. So, I just ran a loop inside my App Engine function that executed once a second 60 times. Not super scientific, but it works and is simple to set up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*OzX1Ph1h40P_eTMjnLjUyw.png" /></figure><p>Now for the pods. I wants to run 10 pods per node, so I just used a simple nginx deployment and set the replicats = #Nodes x 10.</p><p>Finally, I needed a place to store and query this data. Even though it would only be a few 100 MB in size, I used <a href="https://cloud.google.com/bigquery">Google BigQuery</a> because it is serverless, needs zero setup, and is easy to use. My schema was very simple, for each call to the DaemonSet, I would store the number of pods, nodes, and the latency it took for the call to return. The latency number depends a lot on random network conditions, but I expected the number to be in the very low second range most of the time.</p><p>Now came the boring part. Waiting. I needed at least a month of data before I could make any sort of claim. So I deployed everything and forgot about it for a while. A long while…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fgiphy.com%2Fembed%2FtXL4FHPSnVJ0A%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fgiphy.com%2Fgifs%2Fkim-novak-tXL4FHPSnVJ0A&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fmedia.giphy.com%2Fmedia%2FtXL4FHPSnVJ0A%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="287" frameborder="0" scrolling="no"><a href="https://medium.com/media/417ec13e55809e9bc5429dd206f8450e/href">https://medium.com/media/417ec13e55809e9bc5429dd206f8450e/href</a></iframe><h3>The results</h3><p>Lucky for you, I already did the waiting part!</p><p>First, let’s see what the average and minimum number of pods and nodes are. We can do that with a simple SQL query:</p><pre>SELECT <br>  avg(nodes) as avgnodes, <br>  avg(pods) as avgpods, <br>  min(nodes) as minnodes, <br>  min(pods) as minpods<br>FROM &lt;DATASET&gt;.&lt;TABLE&gt;</pre><p>For the three node cluster, the results are as follows:</p><pre>╔════════════════════╦═══════════════════╦══════════╦═════════╗<br>║      avgnodes      ║      avgpods      ║ minnodes ║ minpods ║<br>╠════════════════════╬═══════════════════╬══════════╬═════════╣<br>║ 2.9984359359062274 ║ 29.99116207854014 ║        1 ║       0 ║<br>╚════════════════════╩═══════════════════╩══════════╩═════════╝</pre><p>And for the six node cluster:</p><pre>╔═══════════════════╦═══════════════════╦══════════╦═════════╗<br>║     avgnodes      ║      avgpods      ║ minnodes ║ minpods ║<br>╠═══════════════════╬═══════════════════╬══════════╬═════════╣<br>║ 5.996882929477012 ║ 60.00895171877486 ║        5 ║      30 ║<br>╚═══════════════════╩═══════════════════╩══════════╩═════════╝</pre><p>You can see some interesting things from these numbers. First of all, the average numbers are super close to the max numbers. This shows us the GKE is very fast to recover from PVM nodes shutting down. Remember, PVMs always shut down after 24 hours, so these shutdown events are happening all the time.</p><p><em>Note: The avgpods for the six node cluster is slightly above the max. I think this is because of consistency issues and pods being in the pending status or something. Not 100% sure.</em></p><p>The next thing is the min numbers. First of all, it is clear that PVMs cause some huge churn. For the smaller cluster, we dropped to 0 which is not good. For the larger cluster, we dropped to half the max, which isn’t that bad at all. Remember, we are running 2x the capacity for 30% less cost!</p><p>These numbers only tell us half the story. Averages and absolute minimums can be very deceiving. What we really care about is the distribution of requests, and things like p50, p90, and p99 latency. So let’s write a new SQL query that can give us these numbers.</p><pre>SELECT <br>  latency, <br>  count(*) as occurrences <br>FROM (<br>  SELECT <br>    pods, <br>    TIMESTAMP_DIFF(time, <br>                   LAG(time) OVER (ORDER BY time ASC), <br>                   SECOND<br>    ) as latency <br>  FROM &lt;DATASET&gt;.&lt;TABLE&gt; <br>  ORDER BY time<br>)<br>GROUP BY delta <br>ORDER BY delta DESC</pre><p>Ok this query is a LOT more complicated (thank you coworkers from the BigQuery team for helping with this!), but it gives us results like this:</p><pre>+---------+-------------+<br>| latency | occurrences |<br>+---------+-------------+<br>|      10 |          28 |<br>|       9 |          39 |<br>|       8 |          40 |<br>|       7 |          54 |<br>|       6 |          64 |<br>|       5 |         100 |<br>|       4 |         145 |<br>|       3 |         258 |<br>|       2 |         594 |<br>|       1 |     2409521 |<br>|       0 |     1812774 |<br>+---------+-------------+</pre><p>What this tells us is the number of requests that had a latency of zero seconds, one second, etc.</p><p>Here is all the data and some graphs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_xcGwEGW5gMf97efR3-aw.png" /><figcaption><a href="https://docs.google.com/spreadsheets/d/e/2PACX-1vS_lGkkZnmHVMoCGQ35MtEfYrb9eLLbDysSC7_M3m3DO-1SDRw-vWUAn_fXAtvK8onqYU3QWEUpumHQ/pubhtml?gid=0&amp;single=true">See the data here</a></figcaption></figure><p>We can see that the VAST majority of requests are in the sub-two second range, which is great.</p><p>However, there is a long tail of requests for the smaller cluster that take over 200 seconds to complete. This is obviously when the cluster fell to zero nodes.</p><p><strong>Here is the really cool part. The P99.9 latency for both clusters is still sub-two second!</strong></p><h3>Conclusion</h3><p>The performance of PVMs in GKE was much better than I expected. I thought they would be pretty good, but have extended periods where they were all down at once. While this did happen for the smaller cluster, the larger cluster was basically big enough that it could shrug off node churn quite well.</p><p>Because a single node going down in a large cluster has less effect than in a small cluster, I’m led to believe that the larger the cluster, the less likely that this churn will affect your workloads.</p><p>Using PVMs also creates a natural <a href="https://en.wikipedia.org/wiki/Chaos_Monkey">chaos monkey</a> in your system. Because nodes are constantly churning, you code is always being tested for resiliency. This is awesome because your infra is more prepared for a real outage.</p><p>Of course, running a stateful workload (like a database) would be much more complicated or impossible. Also, running something that needs the highest uptime possible would also be more challenging on PVMs because of the implicit risk. For both of these scenarios, you can easily use <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/node-pools">GKE Node Pools</a> to create a mix of Preemptible and Standard VMs to fit your needs.</p><p>A core promise of the cloud has always been lower costs due to automation and economies of scale. I really feel if you aren’t taking advantage of PVMs with GKE, you are missing out on that promise.</p><p>It’s a single flag or button click to create a cluster with PVMs, so what are you waiting for?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ly9_u9lPP9xydaCX" /><figcaption>“group of people doing fist bumps” by <a href="https://unsplash.com/@rawpixel?utm_source=medium&amp;utm_medium=referral">rawpixel</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>A final word</h3><p>For this test, I only cared about the number of pods that were running. In real life, you would have multiple microservices each with their own pods. If all the pods from a single microservice goes down, this is bad news. You can use PodAffinity rules to make sure this doesn’t happen.</p><p>This blog post has some good details on PodAffinity:</p><p><a href="https://medium.com/kokster/scheduling-in-kubernetes-part-2-pod-affinity-c2b217312ae1">https://medium.com/kokster/scheduling-in-kubernetes-part-2-pod-affinity-c2b217312ae1</a></p><p>Similarly, some microservices can’t tolerate the constant churn that PVMs create. You should use NodeAffinity to ensure these microservices are not scheduled on PVMs.</p><p>This blog post has some good details on NodeAffinity for PVMs:</p><p><a href="https://medium.com/google-cloud/using-preemptible-vms-to-cut-kubernetes-engine-bills-in-half-de2481b8e814">Using preemptible VMs to cut Kubernetes Engine bills in half</a></p><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqDjlKFwScoQYQ62DWEdig.png" /></a></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by +388,456 people.</h4><h4>Subscribe to receive <a href="http://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouK9XR4xuNWtCes-TIUNAw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f0c3032c296" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/get-three-times-the-capacity-for-your-kubernetes-cluster-for-free-too-good-to-be-true-6f0c3032c296">Get THREE times the capacity for your Kubernetes Cluster for FREE! Too good to be true?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No localhost? No problem! Using Google Cloud Shell as my full time development environment.]]></title>
            <link>https://medium.com/google-cloud/no-localhost-no-problem-using-google-cloud-shell-as-my-full-time-development-environment-22d5a1942439?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/22d5a1942439</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Tue, 26 Jun 2018 00:19:46 GMT</pubDate>
            <atom:updated>2018-06-26T00:19:46.498Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently switched to a Chromebook full time (the awesome <a href="https://store.google.com/product/google_pixelbook">Pixelbook</a>), and the first question I get asked is “How do you do any development work on it?”</p><p>While Chromebooks are getting more powerful local development (a la <a href="https://techcrunch.com/2018/05/08/you-can-now-run-linux-apps-on-chrome-os/">Crostini</a>), I’ve actually been using <a href="https://cloud.google.com/shell/">Google Cloud Shell</a> as my primary development environment. In fact, I haven’t opened a local shell for months now.</p><p>So far, the experience has been awesome, and I’ve learned a bunch along the way. I wanted to share some tips, here they are!</p><h3>What is Google Cloud Shell</h3><p>Cloud Shell is a free terminal that you can use for whatever you want, and it runs 100% in a web browser.</p><blockquote>Click this link to open Cloud Shell: <a href="https://console.cloud.google.com/cloudshell">https://console.cloud.google.com/cloudshell</a></blockquote><p>Seeing how most of my work requires the internet, I’m completely fine with being tied to a browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTarHCEVG_vD3pWkQs4JHA.png" /></figure><h4>What does it come with?</h4><p>Cloud Shell comes with most of the tools I use on a daily basis right out of the box. These include <strong>gcloud, node, kubectl, docker, go, python, git, vim</strong>, and more.</p><p>There is 5GB of persistent storage that is tied to your $HOME directory, and this is also completely free.</p><p>The other really nice thing is that you are automatically authenticated to the current Google Cloud project you’re working in. This makes setup super easy, everything just works!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unQ6jcZ3E0KFuAHm78ywDg.png" /></figure><h3>Tips and Tricks</h3><h4>1. Running a web server (with auto-HTTPS for FREE!)</h4><p>Most people developing cloud apps usually run a web server of some sort. Usually, you would run it locally and just type in “localhost” into your web browser to access it.</p><p>This is not possible with Cloud Shell, so the team created a neat “web preview” function that creates a URL on the fly to point to your local server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WiC7L2mV_x16geFpwoYkQ.gif" /></figure><p>You can open up any port from 2000 to 65000, and your web traffic will come through!</p><blockquote><strong>Warning</strong>: There is some transparent auth done behind the scenes, so the URL the Cloud Shell opens might not work if you give it to someone else. I’d recommend a tool like ngrok if you want to share your “localhost” connection remotely.</blockquote><h4>2. Get extra power with “boost mode”</h4><p>By default, Cloud Shell runs on a g1-small VM, which can be under-powered for some tasks. You can easily upgrade to a n1-standard-1 by enabling “boost mode.” It’s like the TURBO button on an old PC, but this time it actually works :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gUIHGIccf4BCdFS3Kx-UA.gif" /></figure><h4>3. Edit your files with a GUI</h4><p>Yes yes, vim and emacs and nano are great and all. But sometimes you just want a nice, comfortable GUI to work with.</p><p>Cloud Shell ships with a customized version of the Orion editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luFiLc62ue2Unob4jVbwaA.gif" /></figure><p>While its not as good as VS Code or Eclipse, its actually a fully featured editor and I feel quite productive with it!</p><h4>4. Upload/Download files</h4><p>If you have files locally you want to upload to cloud shell, just click the “Upload” button in the menu and choose your file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vG9zeb2ZI6XcWyxJPsrVuQ.gif" /></figure><p>To download files, run this inside Cloud Shell:</p><pre>$ cloudshell dl &lt;FILENAME&gt;</pre><p>And it will download the file!</p><h4>5. Persist binary/program installations</h4><p>Because Cloud Shell only persists your $HOME directory, if you install things that don’t come out of the box with Cloud Shell, chances are it will be gone the next time you use it.</p><p>If you install things with <strong>apt-get</strong>, there really is no good solution. However, if you are downloading the binary directly or are compiling from source, you can create a path in your $HOME directory (for example, /home/sandeepdinesh/bin) and add that to your PATH. Any binaries in this folder will run like normal, and they will be persisted between reboots.</p><h4>Bonus: Open in Cloud Shell</h4><p>If you have a git repository in a public place (like a public GitHub repo), you can actually create a link that will open the end user’s Cloud Shell and automatically clone the repo to their $HOME directory.</p><p><a href="https://cloud.google.com/shell/docs/open-in-cloud-shell">Open in Cloud Shell | Cloud Shell | Google Cloud</a></p><p>Because it is all free, it is a great way to get someone up and running with your project without having to worry about their local machine!</p><h3>Conclusion</h3><p>I’ve had a ton of success using Cloud Shell as my primary dev environment. If you are using a Chromebook or if you just want a free Linux shell that you can access from any browser, I’d definitely check out Cloud Shell.</p><p>There are a ton of new features coming down the line as well, I’ll be sure talk about them when they come out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22d5a1942439" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/no-localhost-no-problem-using-google-cloud-shell-as-my-full-time-development-environment-22d5a1942439">No localhost? No problem! Using Google Cloud Shell as my full time development environment.</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Best Practices — Season One]]></title>
            <link>https://medium.com/google-cloud/kubernetes-best-practices-season-one-11119aee1d10?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/11119aee1d10</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Tue, 19 Jun 2018 14:43:56 GMT</pubDate>
            <atom:updated>2018-06-19T14:44:16.951Z</atom:updated>
            <content:encoded><![CDATA[<p>Kubernetes is complicated, and is getting more complicated each day. If you are getting started with Kubernetes or if you have been running it in production for a while, its hard to keep up with the rapid pace of development that’s going on. It’s even harder when you have a team of people building on Kubernetes, as you have to make sure each person is up-to-date and productive.</p><p>While there is a ton of content out there on the “Hello World” experience, using Kubernetes is a lot more involved that running a Deployment and exposing it with a Service. Kubernetes itself provides a blank slate where you can basically do whatever you want, but it can be really hard to know where to start!</p><p>With that in mind, I began working on a talk titled “Kubernetes Best Practices” (Here are the <a href="https://speakerdeck.com/thesandlord/kubernetes-best-practices">slides</a> and <a href="https://www.youtube.com/watch?v=BznjDNxp4Hs">video</a>) based on questions and feedback I received from talking to everyday people out in the wild. This talk was so popular that I decided to deep dive into the individual topics. I ended up with seven episodes for this initial run (<a href="https://cloudplatform.googleblog.com/2016/07/from-Google-to-the-world-the-Kubernetes-origin-story.html">which is quite appropriate</a>), and I really think they can help you and your team quickly ramp up on Kubernetes.</p><p>So here are all seven episodes for your viewing pleasure! I’m working on the next batch of videos right now, and would love your feedback on what you want to see. Leave a comment or send me a message <a href="https://twitter.com/SandeepDinesh">on Twitter</a> with your suggestions!</p><h3>Season One Episodes</h3><ul><li><a href="https://www.youtube.com/playlist?list=PLIivdWyY5sqL3xfXz5xJvwzFW_tlQB_GB">All Videos</a></li></ul><h4>How and why to build small containers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K0GIlb657-3AF8XC.jpg" /></figure><p>Before you can use Kubernetes, you gotta build some containers. Docker makes it super easy to build containers, but this also means it is easy to build inefficient and insecure containers as well. Building smaller containers can be an easy way to get more from you Kubernetes cluster without a lot of work.</p><ul><li><a href="https://cloudplatform.googleblog.com/2018/04/Kubernetes-best-practices-how-and-why-to-build-small-container-images.html">Blog Post</a></li><li><a href="https://youtu.be/wGz_cbtCiEA">Video</a></li></ul><h4>Organizing with Namespaces</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oE_d_44cAUSJ_wmg.jpg" /></figure><p>Once you go beyond “hello world,” you will probably run into organizational issues when trying to manage your microservices running on Kubernetes. This gets even worse when your team(s) grow and you need more visibility and control. Namespaces provide a powerful way to manage resources in Kubernetes, and provide the foundation for policies and management.</p><ul><li><a href="https://cloudplatform.googleblog.com/2018/04/Kubernetes-best-practices-Organizing-with-Namespaces.html">Blog Post</a></li><li><a href="https://youtu.be/xpnZX3if9Tc">Video</a></li></ul><h4>Health checks with readiness and liveness probes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rtpkUtv66zDCEUUX.jpg" /></figure><p>Health checks are required to create robust and reliable services. While Kubernetes has default built in health checks, they can be insufficient for many apps. Readiness and Liveness probes give you the power to easily customize these health checks for your applications.</p><ul><li><a href="https://cloudplatform.googleblog.com/2018/05/Kubernetes-best-practices-Setting-up-health-checks-with-readiness-and-liveness-probes.html">Blog Post</a></li><li><a href="https://youtu.be/mxEvAPQRwhw">Video</a></li></ul><h4>Resource requests and limits</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tiEgL6ffA_sqY7Ub.jpg" /></figure><p>Memory leaks, infinite loops, bad actors, over-provisioning, oh my! Kubernetes gives you a powerful platform to run your services, but if you don’t define rules around resources, eventually you are going to be in for a bad time. Thankfully, Kubernetes gives you a lot of control over resources and how they are used.</p><ul><li><a href="https://cloudplatform.googleblog.com/2018/05/Kubernetes-best-practices-Resource-requests-and-limits.html">Blog Post</a></li><li><a href="https://youtu.be/xjpHggHKm78">Video</a></li></ul><h4>Terminating with grace</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CkNz3GlnZGhyycfY.jpg" /></figure><p>Pods and Containers in Kubernetes need to deal with termination gracefully. Kubernetes can decide to terminate a perfectly healthy Pod for a variety for reasons, and shutting down cleanly is key to providing your users with a good experience.</p><ul><li><a href="https://cloudplatform.googleblog.com/2018/05/Kubernetes-best-practices-terminating-with-grace.html">Blog Post</a></li><li><a href="https://youtu.be/Z_l_kE1MDTc">Video</a></li></ul><h4>Mapping external services</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXOE0v4yChNM2i9s.jpg" /></figure><p>Chances are you have services that live outside your Kubernetes cluster. Some of them may be 3rd party services, and others might be services that your team or company run. Regardless, living in the hybrid world brings its complications. Kubernetes gives you the power to map these external services to make them look and feel like native Kubernetes services, making it easier to bridge the gap between worlds.</p><ul><li><a href="https://cloudplatform.googleblog.com/2018/05/Kubernetes-best-practices-mapping-external-services.html">Blog Post</a></li><li><a href="https://youtu.be/fvpq4jqtuZ8">Video</a></li></ul><h4>Upgrading your clusters with zero downtime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UdMc07JcvGnbtudO.jpg" /></figure><p>One of the most important things you need to do is keep your cluster up to date. Using managed services like GKE can make this a lot easier, but there are still methods you can use to make the upgrade process smoother.</p><ul><li><a href="https://cloudplatform.googleblog.com/2018/06/Kubernetes-best-practices-upgrading-your-clusters-with-zero-downtime.html">Blog Post</a></li><li><a href="https://youtu.be/ajbC1yTW2x0">Video</a></li></ul><p><em>Thanks to all the folks that made this possible, from people who reviewed the content to the video and blog editing teams who made this series a reality!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11119aee1d10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/kubernetes-best-practices-season-one-11119aee1d10">Kubernetes Best Practices — Season One</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes NodePort vs LoadBalancer vs Ingress? When should I use what?]]></title>
            <link>https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/922f010849e0</guid>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[services]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Sun, 11 Mar 2018 19:31:31 GMT</pubDate>
            <atom:updated>2019-10-04T22:13:01.622Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, someone asked me what the difference between NodePorts, LoadBalancers, and Ingress were. They are all different ways to get external traffic into your cluster, and they all do it in different ways. Let’s take a look at how each of them work, and when you would use each.</p><p><strong><em>Note: </em></strong><em>Everything here applies to </em><a href="https://cloud.google.com/gke"><em>Google Kubernetes Engine.</em></a><em> If you are running on another cloud, on prem, with minikube, or something else, these will be slightly different. I’m also not going into deep technical details. If you are interested in learning more, the </em><a href="https://kubernetes.io/docs/concepts/services-networking/service/"><em>official documentation</em></a><em> is a great resource!</em></p><h3>ClusterIP</h3><p>A ClusterIP service is the default Kubernetes service. It gives you a service inside your cluster that other apps inside your cluster can access. There is no external access.</p><p>The YAML for a ClusterIP service looks like this:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:  <br>  name: my-internal-service<br>spec:<br>  selector:    <br>    app: my-app<br>  type: ClusterIP<br>  ports:  <br>  - name: http<br>    port: 80<br>    targetPort: 80<br>    protocol: TCP</pre><p>If you can’t access a ClusterIP service from the internet, why am I talking about it? Turns out you can access it using the Kubernetes proxy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*I4j4xaaxsuchdvO66V3lAg.png" /><figcaption>Thanks to <a href="https://medium.com/u/2cac56571879">Ahmet Alp Balkan</a> for the diagrams</figcaption></figure><p>Start the Kubernetes Proxy:</p><pre>$ kubectl proxy --port=8080</pre><p>Now, you can navigate through the Kubernetes API to access this service using this scheme:</p><p>http://localhost:8080/api/v1/proxy/namespaces/&lt;NAMESPACE&gt;/services/&lt;SERVICE-NAME&gt;:&lt;PORT-NAME&gt;/</p><p>So to access the service we defined above, you could use the following address:</p><p>http://localhost:8080/api/v1/proxy/namespaces/default/services/my-internal-service:http/</p><h4>When would you use this?</h4><p>There are a few scenarios where you would use the Kubernetes proxy to access your services.</p><ol><li>Debugging your services, or connecting to them directly from your laptop for some reason</li><li>Allowing internal traffic, displaying internal dashboards, etc.</li></ol><p>Because this method requires you to run kubectl as an authenticated user, you should NOT use this to expose your service to the internet or use it for production services.</p><h3>NodePort</h3><p>A NodePort service is the most primitive way to get external traffic directly to your service. NodePort, as the name implies, opens a specific port on all the Nodes (the VMs), and any traffic that is sent to this port is forwarded to the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdyUtG-8CfGu2oFC5s0KwA.png" /><figcaption>This isn’t the most technically accurate diagram, but I think it illustrates the point of how a NodePort works</figcaption></figure><p>The YAML for a NodePort service looks like this:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:  <br>  name: my-nodeport-service<br>spec:<br>  selector:    <br>    app: my-app<br>  type: NodePort<br>  ports:  <br>  - name: http<br>    port: 80<br>    targetPort: 80<br>    nodePort: 30036<br>    protocol: TCP</pre><p>Basically, a NodePort service has two differences from a normal “ClusterIP” service. First, the type is “NodePort.” There is also an additional port called the nodePort that specifies which port to open on the nodes. If you don’t specify this port, it will pick a random port. Most of the time you should let Kubernetes choose the port; as <a href="https://medium.com/u/d399b620658f">thockin</a> says, there are many caveats to what ports are available for you to use.</p><h4>When would you use this?</h4><p>There are many downsides to this method:</p><ol><li>You can only have one service per port</li><li>You can only use ports 30000–32767</li><li>If your Node/VM IP address change, you need to deal with that</li></ol><p>For these reasons, I don’t recommend using this method in production to directly expose your service. If you are running a service that doesn’t have to be always available, or you are very cost sensitive, this method will work for you. A good example of such an application is a demo app or something temporary.</p><h3>LoadBalancer</h3><p>A LoadBalancer service is the standard way to expose a service to the internet. On GKE, this will spin up a <a href="https://cloud.google.com/compute/docs/load-balancing/network/">Network Load Balancer</a> that will give you a single IP address that will forward all traffic to your service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*P-10bQg_1VheU9DRlvHBTQ.png" /><figcaption>Thanks to <a href="https://medium.com/u/2cac56571879">Ahmet Alp Balkan</a> for the diagrams</figcaption></figure><h4>When would you use this?</h4><p>If you want to directly expose a service, this is the default method. All traffic on the port you specify will be forwarded to the service. There is no filtering, no routing, etc. This means you can send almost any kind of traffic to it, like HTTP, TCP, UDP, Websockets, gRPC, or whatever.</p><p>The big downside is that each service you expose with a LoadBalancer will get its own IP address, and you have to pay for a LoadBalancer per exposed service, which can get expensive!</p><h3>Ingress</h3><p>Unlike all the above examples, Ingress is actually NOT a type of service. Instead, it sits in front of multiple services and act as a “smart router” or entrypoint into your cluster.</p><p>You can do a lot of different things with an Ingress, and there are many types of Ingress controllers that have different capabilities.</p><p>The default GKE ingress controller will spin up a <a href="https://cloud.google.com/compute/docs/load-balancing/http/">HTTP(S) Load Balancer</a> for you. This will let you do both path based and subdomain based routing to backend services. For example, you can send everything on foo.yourdomain.com to the foo service, and everything under the yourdomain.com/bar/ path to the bar service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIVa4hUVZxg-8Ncabo8pdg.png" /><figcaption>Thanks to <a href="https://medium.com/u/2cac56571879">Ahmet Alp Balkan</a> for the diagrams</figcaption></figure><p>The YAML for a Ingress object on GKE with a <a href="https://cloud.google.com/compute/docs/load-balancing/http/">L7 HTTP Load Balancer</a> might look like this:</p><pre>apiVersion: extensions/v1beta1<br>kind: Ingress<br>metadata:<br>  name: my-ingress<br>spec:<br>  backend:<br>    serviceName: other<br>    servicePort: 8080<br>  rules:<br>  - host: foo.mydomain.com<strong><br></strong>    http:<br>      paths:<br>      - backend:<br>          serviceName: foo<br>          servicePort: 8080<strong><br></strong>  - host: mydomain.com<br>    http:<br>      paths:<br>      - path: /bar/*<br>        backend:<br>          serviceName: bar<br>          servicePort: 8080</pre><h4>When would you use this?</h4><p>Ingress is probably the most powerful way to expose your services, but can also be the most complicated. There are many types of Ingress controllers, from the <a href="https://cloud.google.com/kubernetes-engine/docs/tutorials/http-balancer">Google Cloud Load Balancer</a>, <a href="https://github.com/kubernetes/ingress-nginx">Nginx</a>, <a href="https://github.com/heptio/contour">Contour</a>, <a href="https://istio.io/docs/tasks/traffic-management/ingress.html">Istio</a>, and more. There are also plugins for Ingress controllers, like the <a href="https://github.com/jetstack/cert-manager">cert-manager</a>, that can automatically provision SSL certificates for your services.</p><p>Ingress is the most useful if you want to expose multiple services under the same IP address, and these services all use the same L7 protocol (typically HTTP). You only pay for one load balancer if you are using the native GCP integration, and because Ingress is “smart” you can get a lot of features out of the box (like SSL, Auth, Routing, etc)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922f010849e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0">Kubernetes NodePort vs LoadBalancer vs Ingress? When should I use what?</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Callbacks, Promises and Async/Await]]></title>
            <link>https://medium.com/front-end-weekly/callbacks-promises-and-async-await-ad4756e01d90?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4756e01d90</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Wed, 10 Jan 2018 22:37:11 GMT</pubDate>
            <atom:updated>2019-08-30T20:34:56.329Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my attempt to explain how to use asynchronous code in Javascript at a very high level.</p><p><em>Note: I’m going to be using arrow functions in this blog post. Basically I’ll be replacing anonymous functions like so:</em></p><pre><em>function() {}     function(a) {}      function(a,b) {}</em></pre><p><em>can be replaced with</em></p><pre><em>() =&gt; {}          a =&gt; {}            (a,b) =&gt; {}</em></pre><p><a href="https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26"><em>Read more about arrow functions here</em></a></p><p>Let’s say you have a function that will print a string after a random amount of time:</p><pre>function printString(string){<br>  setTimeout(<br>    () =&gt; {<br>      console.log(string)<br>    }, <br>    Math.floor(Math.random() * 100) + 1<br>  )<br>}</pre><p>Let’s try to print the letters A, B, C in that order:</p><pre>function printAll(){<br>  printString(&quot;A&quot;)<br>  printString(&quot;B&quot;)<br>  printString(&quot;C&quot;)<br>}</pre><pre>printAll()</pre><p>You will notice that A, B, and C print in a different and random order each time you call <em>printAll</em>!</p><p>This is because these functions are asynchronous. Each function gets executed in order, but each one is independent with it’s own setTimeout. They won’t wait for the last function to finish before they start.</p><p>This is super annoying, so let’s fix it with a callback.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><h4>Callbacks</h4><p>A callback is a function that is passed to another function. When the first function is done, it will run the second function.</p><pre>function printString(string, callback){<br>  setTimeout(<br>    () =&gt; {<br>      console.log(string)<br>      callback()<br>    }, <br>    Math.floor(Math.random() * 100) + 1<br>  )<br>}</pre><p>You can see that is is super easy to modify the original function to work with callbacks.</p><p>Again, let’s try to print the letters A, B, C in that order:</p><pre>function printAll(){<br>  printString(&quot;A&quot;, () =&gt; {<br>    printString(&quot;B&quot;, () =&gt; {<br>      printString(&quot;C&quot;, () =&gt; {})<br>    })<br>  })<br>}</pre><pre>printAll()</pre><p>Well, the code is a lot uglier now, but at least it works! Each time you call printAll, you get the same result.</p><p>The problem with callbacks is it creates something called “Callback Hell.” Basically, you start nesting functions within functions within functions, and it starts to get really hard to read the code.</p><h4>Promises</h4><p>Promises try to fix this nesting problem. Let’s change our function to use Promises</p><pre>function printString(string){<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(<br>      () =&gt; {<br>       console.log(string)<br>       resolve()<br>      }, <br>     Math.floor(Math.random() * 100) + 1<br>    )<br>  })<br>}</pre><p>You can see that it still looks pretty similar. You wrap the whole function in a Promise, and instead of calling the callback, you call resolve (or reject if there is an error). The function returns this Promise object.</p><p>Again, let’s try to print the letters A, B, C in that order:</p><pre>function printAll(){<br>  printString(&quot;A&quot;)<br>  .then(() =&gt; {<br>    return printString(&quot;B&quot;)<br>  })<br>  .then(() =&gt; {<br>    return printString(&quot;C&quot;)<br>  })<br>}</pre><pre>printAll()</pre><p>This is called a Promise Chain. You can see that the code returns the result of the function (which will be a Promise), and this gets sent to the next function in the chain.</p><p>The code is no longer nested but it still looks messy!</p><p>By using features of arrow functions, we can remove the “wrapper” function. The code becomes cleaner, but still has a lot of unnecessary parenthesis:</p><pre>function printAll(){<br>  printString(&quot;A&quot;)<br>  .then(() =&gt; printString(&quot;B&quot;))<br>  .then(() =&gt; printString(&quot;C&quot;))<br>}</pre><pre>printAll()</pre><h4>Await</h4><p>Await is basically syntactic sugar for Promises. It makes your asynchronous code look more like synchronous/procedural code, which is easier for humans to understand.</p><p>The <em>printString</em> function doesn’t change at all from the promise version.</p><p>Again, let’s try to print the letters A, B, C in that order:</p><pre>async function printAll(){<br>  await printString(&quot;A&quot;)<br>  await printString(&quot;B&quot;)<br>  await printString(&quot;C&quot;)<br>}</pre><pre>printAll()</pre><p>Yeah…. MUCH better!</p><p>You might notice that we use the “async” keyword for the wrapper function <em>printAll</em>. This let’s JavaScript know that we are using async/await syntax, and is necessary if you want to use Await. This means you can’t use Await at the global level; it always needs a wrapper function. Most JavaScript code runs inside a function, so this isn’t a big deal.</p><h3>BUT WAIT THERE&#39;S MORE</h3><p>The <em>printString</em> function doesn’t return anything and is independent, all we cared about was the order. But what if you wanted to take the output of the first function, do something with it in the second function, and then pass it to the third function?</p><p>Instead of printing the string each time, let’s make a function that will concatenate the string and pass it on.</p><h4>Callbacks</h4><p>Here it is in callback style:</p><pre>function addString(previous, current, callback){<br>  setTimeout(<br>    () =&gt; {<br>      callback((previous + &#39; &#39; + current))<br>    }, <br>    Math.floor(Math.random() * 100) + 1<br>  )<br>}</pre><p>And in order to call it:</p><pre>function addAll(){<br>  addString(&#39;&#39;, &#39;A&#39;, result =&gt; {<br>    addString(result, &#39;B&#39;, result =&gt; {<br>      addString(result, &#39;C&#39;, result =&gt; {<br>       console.log(result) // Prints out &quot; A B C&quot;<br>      })<br>    })<br>  })<br>}</pre><pre>addAll()</pre><p>Not so nice.</p><h4>Promises</h4><p>Here it is in Promise style:</p><pre>function addString(previous, current){<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(<br>      () =&gt; {<br>        resolve(previous + &#39; &#39; + current)<br>      }, <br>      Math.floor(Math.random() * 100) + 1<br>    )<br>  })<br>}</pre><p>And in order to call it:</p><pre>function addAll(){  <br>  addString(&#39;&#39;, &#39;A&#39;)<br>  .then(result =&gt; {<br>    return addString(result, &#39;B&#39;)<br>  })<br>  .then(result =&gt; {<br>    return addString(result, &#39;C&#39;)<br>  })<br>  .then(result =&gt; {<br>    console.log(result) // Prints out &quot; A B C&quot;<br>  })<br>}</pre><pre>addAll()</pre><p>Using arrow functions means we can make the code a little nicer:</p><pre>function addAll(){  <br>  addString(&#39;&#39;, &#39;A&#39;)<br>  .then(result =&gt; addString(result, &#39;B&#39;))<br>  .then(result =&gt; addString(result, &#39;C&#39;))<br>  .then(result =&gt; {<br>    console.log(result) // Prints out &quot; A B C&quot;<br>  })<br>}</pre><pre>addAll()</pre><p>This is definitely more readable, especially if you add more to the chain, but still a mess of parenthesis.</p><h4>Await</h4><p>The function stays the same as the Promise version.</p><p>And in order to call it:</p><pre>async function addAll(){<br>  let toPrint = await addString(&#39;&#39;, &#39;A&#39;)<br>  toPrint = await addString(toPrint, &#39;B&#39;)<br>  toPrint = await addString(toPrint, &#39;C&#39;)<br>  console.log(toPrint) // Prints out &quot; A B C&quot;<br>}</pre><pre>addAll()</pre><p>Yeah. SO MUCH BETTER.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4756e01d90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/callbacks-promises-and-async-await-ad4756e01d90">Callbacks, Promises and Async/Await</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Google APIs with Firebase Auth and Firebase UI on the Web]]></title>
            <link>https://medium.com/google-cloud/using-google-apis-with-firebase-auth-and-firebase-ui-on-the-web-46e6189cf571?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e6189cf571</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[google-api]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Wed, 03 Jan 2018 19:41:03 GMT</pubDate>
            <atom:updated>2020-12-03T00:13:19.134Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>2021 Update: I no longer recommend this method. While it still technically works, when using it in a </strong><a href="http://kbee.app"><strong>recent project</strong></a><strong>, we ran into a lot of stale login issues.</strong></p><p><strong>Instead, you should go the other way around and use the gapi login to pass credentials to Firebase.</strong></p><p><strong>I recommend following the instructions here: </strong><a href="https://github.com/msukmanowsky/gapi-firebase"><strong>https://github.com/msukmanowsky/gapi-firebase</strong></a></p><p><strong>I also recommend using this helper module to load gapi: </strong><a href="https://www.npmjs.com/package/gapi-script"><strong>https://www.npmjs.com/package/gapi-script</strong></a></p><h3>Original Post:</h3><p>If you are building an web app that needs to interact with a user’s Google account, chances are you are going to discover the pain that is OAuth. You need to get a OAuth token and pass that to the Google API library before you can do anything useful.</p><p>Thankfully, doing all the login stuff with Firebase Auth is super easy, and <a href="https://github.com/firebase/firebaseui-web">Firebase UI</a> makes it even easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*zBpmnu_GmOuagTE9ahrFsQ.png" /><figcaption>Niceeeeee</figcaption></figure><p><a href="https://github.com/firebase/firebaseui-web">Firebase UI</a> is basically a drop in library that does all the UI (buttons, etc) and redirect logic for you automatically for all supported Firebase OAuth providers (Google, Facebook, GitHub, etc).</p><p>The problem is, when you want to do more than just log in, things get murky. Let’s say you wanted to create an app that manages a user’s calendar. How do you specify the scopes you need to access other Google services? How do you get the OAuth token from Firebase UI to use in the Google API Client?</p><p>Thankfully,<a href="https://medium.com/@vanderlin"> Todd Vanderlin</a> wrote a <a href="https://medium.com/@vanderlin/google-api-firebase-auth-1b18416b4e74">great post</a> that fixes many of these issues. Using that as a basis, let’s see how you can get Firebase UI and the Google API Client working together!</p><h3>Setup Libraries</h3><p>The first step is to install Firebase and Firebase UI. You can just follow the official instructions, or follow along here.</p><p>Add the following to your &lt;head&gt; section in the HTML:</p><pre>&lt;script src=&quot;https://www.gstatic.com/firebasejs/4.8.1/firebase.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.js&quot;&gt;&lt;/script&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.css&quot; /&gt;</pre><p>This will load all the dependencies from Google’s CDN.</p><h3>Setup Config</h3><p>First, make sure you enable Google Login in the Firebase Console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCHOrXXJRJXkx65z-28DQw.gif" /></figure><p>Go to the Firebase Console and get the Config data for your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDY3jCWNK8My0z2EhtrPzQ.gif" /><figcaption>Copy this config object</figcaption></figure><p>It should look something like this:</p><pre>var config = {<br>    apiKey: &quot;RANDOM_STRING&quot;,<br>    authDomain: &quot;APPNAME.firebaseapp.com&quot;,<br>    databaseURL: &quot;https://APPNAME.firebaseio.com&quot;,<br>    projectId: &quot;APPNAME&quot;,<br>    storageBucket: &quot;APPNAME.appspot.com&quot;,<br>    messagingSenderId: &quot;1234567890&quot;<br>  };</pre><p>We are going to use this config object to configure the Google APIs as well as Firebase. To do this, you need to add some more fields to this object.</p><h4>ClientID</h4><p>The first thing you need to do is get your OAuth Client ID. To do this, you need to go to the Google Developer Console.</p><p><a href="http://console.developers.google.com/apis/credentials">console.developers.google.com/apis/credentials</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*I3Zx6lIbrG-xrPXVW-HEcg.png" /><figcaption>Copy the full ClientID</figcaption></figure><p>Now add this to your config object</p><pre>var config = {<br>    apiKey: &quot;RANDOM_STRING&quot;,<br>    authDomain: &quot;APPNAME.firebaseapp.com&quot;,<br>    databaseURL: &quot;https://APPNAME.firebaseio.com&quot;,<br>    projectId: &quot;APPNAME&quot;,<br>    storageBucket: &quot;APPNAME.appspot.com&quot;,<br>    messagingSenderId: &quot;1234567890&quot;,</pre><pre>    clientId: &quot;RANDOM_STRING.apps.googleusercontent.com&quot;</pre><pre>  };</pre><h4>Scopes</h4><p>Next, you need to add in the scopes you need for the services you want to modify. In this example, I want to get the user’s profile information (email, name, etc) and have the ability to modify and read their calendar.</p><p>To find the right scope name, there is a list of all available Google Scopes here:</p><p><a href="https://developers.google.com/identity/protocols/googlescopes">https://developers.google.com/identity/protocols/googlescopes</a></p><p>Now search for the scopes you need. Some services (like Gmail) have very specific scopes that give you the minimum access you need to complete a task. Always make sure to use the least amount of permissions you need!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsHuTWPw02TMulsgABHQxQ.gif" /></figure><p>So in this example, there are three scopes to include: “email”, “profile”, and “https://www.googleapis.com/auth/calendar”</p><p>Create an array in the config object with these values:</p><pre>var config = {<br>    apiKey: &quot;RANDOM_STRING&quot;,<br>    authDomain: &quot;APPNAME.firebaseapp.com&quot;,<br>    databaseURL: &quot;https://APPNAME.firebaseio.com&quot;,<br>    projectId: &quot;APPNAME&quot;,<br>    storageBucket: &quot;APPNAME.appspot.com&quot;,<br>    messagingSenderId: &quot;1234567890&quot;,</pre><pre>    clientId: &quot;RANDOM_STRING.apps.googleusercontent.com&quot;,</pre><pre>    scopes: [<br>             &quot;email&quot;,<br>             &quot;profile&quot;,<br>             &quot;https://www.googleapis.com/auth/calendar&quot;<br>    ]<br>};</pre><h4>Discovery Docs</h4><p>Time for the last step. In order for the Google API client to know which libraries to load, you need to pass in the corresponding discovery docs. Email and Profile are built into Firebase, but we want to be able to modify the Calendar with the Google API client, so we need the discovery doc for it.</p><p>To find the right discovery doc, you can use this service:</p><p><a href="https://developers.google.com/discovery/v1/reference/apis/list?apix=true">https://developers.google.com/discovery/v1/reference/apis/list?apix=true</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9wzQU2LdjJMlFEUHWhVuvA.gif" /></figure><p>Again, create an array and add in all the discovery docs you need</p><pre>var config = {<br>    apiKey: &quot;RANDOM_STRING&quot;,<br>    authDomain: &quot;APPNAME.firebaseapp.com&quot;,<br>    databaseURL: &quot;https://APPNAME.firebaseio.com&quot;,<br>    projectId: &quot;APPNAME&quot;,<br>    storageBucket: &quot;APPNAME.appspot.com&quot;,<br>    messagingSenderId: &quot;1234567890&quot;,</pre><pre>    clientId: &quot;RANDOM_STRING.apps.googleusercontent.com&quot;,</pre><pre>    scopes: [<br>             &quot;email&quot;,<br>             &quot;profile&quot;,<br>             &quot;https://www.googleapis.com/auth/calendar&quot;<br>    ],<br>    discoveryDocs: [<br>    &quot;<a href="https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest">https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest</a>&quot;<br>    ]<br>};</pre><p>Finally done with all the config madness!</p><h3>Setting up Firebase UI</h3><p><em>Note: </em><a href="https://gist.github.com/thesandlord/4740bfaca43d67fe6865c097db2a4016"><em>You can see the completed code here</em></a></p><p>Follow the official setup for Firebase UI. The one difference is in the “signInOptions” field. Change it to include the scopes you specified in the config object:</p><pre>var uiConfig = {<br> signInSuccessUrl: “&lt;url-to-redirect-to-on-success&gt;”,<br> signInOptions: [{<br>   provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,<br>   scopes: config.scopes<br> }],<br> // Terms of service url.<br> tosUrl: “&lt;your-tos-url&gt;”<br>};</pre><h3>Setting up the Google API Client</h3><p>Firebase UI will take care of all the login flow details. After the login is complete, Firebase will automatically trigger a function. Inside this function, we are going to load the Google API client.</p><pre>// This function will trigger when there is a login event<br>firebase.auth().onAuthStateChanged(function(user) {</pre><pre>  // Make sure there is a valid user object<br>  if(user){<br>    var script = document.createElement(&#39;script&#39;);<br>    script.type = &#39;text/javascript&#39;;<br>    script.src = &#39;<a href="https://apis.google.com/js/api.js&#39;">https://apis.google.com/js/api.js&#39;</a>;</pre><pre>    // Once the Google API Client is loaded, you can run your code<br>    script.onload = function(e){</pre><pre>     // Initialize the Google API Client with the config object<br>     gapi.client.init({<br>       apiKey: config.apiKey,<br>       clientId: config.clientID,<br>       discoveryDocs: config.discoveryDocs,<br>       scope: config.scopes.join(&#39; &#39;),<br>     })</pre><pre>     // Loading is finished, so start the app<br>     .then(function() {</pre><pre>      // Make sure the Google API Client is properly signed in<br>      if (gapi.auth2.getAuthInstance().isSignedIn.get()) {<br>        startApp(user);<br>      } else {<br>        firebase.auth().signOut(); // Something went wrong, sign out<br>      }</pre><pre>     })</pre><pre>    }</pre><pre>    // Add to the document<br>    document.getElementsByTagName(&#39;head&#39;)[0].appendChild(script);  <br>  }<br>})</pre><h3>Tying it all together</h3><p>All the “boilerplate” is finished. You can now use the Google API Client without any issues!</p><p><strong>Note:</strong> It is important that you either check if the OAuth token is still valid before making the call, or refresh the token before calling the APIs. This is because Firebase will automatically refresh the token, but the Google API Client won’t.</p><pre>// Print out the User and the 10 latest calendar events<br>function startApp(user) {<br>  console.log(user);<br>  firebase.auth().currentUser.getToken()<br>  .then(function(token) {<br>    return gapi.client.calendar.events.list({<br>     calendarId: &quot;primary&quot;,<br>     timeMin: new Date().toISOString(),<br>     showDeleted: false,<br>     singleEvents: true,<br>     maxResults: 10,<br>     orderBy: &quot;startTime&quot;<br>    })  <br>   })<br>  .then(function(response) {<br>    console.log(response);  <br>  });<br>}</pre><h3>Full Code:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee8c17d8b2a5b4918a7fb13e0e02f8f4/href">https://medium.com/media/ee8c17d8b2a5b4918a7fb13e0e02f8f4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e6189cf571" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/using-google-apis-with-firebase-auth-and-firebase-ui-on-the-web-46e6189cf571">Using Google APIs with Firebase Auth and Firebase UI on the Web</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes ConfigMaps and Secrets Part 2]]></title>
            <link>https://medium.com/google-cloud/kubernetes-configmaps-and-secrets-part-2-3dc37111f0dc?source=rss-bba63600816e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dc37111f0dc</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Sandeep Dinesh]]></dc:creator>
            <pubDate>Tue, 08 Aug 2017 21:28:45 GMT</pubDate>
            <atom:updated>2017-08-08T22:52:39.328Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a continuation from <a href="https://medium.com/google-cloud/kubernetes-configmaps-and-secrets-68d061f7ab5b">Part 1</a>.</p><p>While environment variables are great for small bits of information, sometimes you might have a lot of data that needs to be passed to your app. A common solution is to group this data into a file, and have your app read from this file.</p><p>Kubernetes let’s you mount ConfigMaps and Secrets as files. Unlike environment variables, if these files change the new files will be pushed to the running pods without needing a restart, so they are a lot more powerful. You can also map multiple files to a single ConfigMap or Secret, and mount them all at once as a directory!</p><h3>Read from a file</h3><p>Let’s modify our code from <a href="https://medium.com/google-cloud/kubernetes-configmaps-and-secrets-68d061f7ab5b">Part 1</a> to read from files instead of environment variables.</p><p>First, create a two subdirectories called “config” and “secret”, and config.json and secret.json files with the data we used in part one:</p><pre>mkdir config &amp;&amp; mkdir secret</pre><pre>echo &#39;{&quot;LANGUAGE&quot;:&quot;English&quot;}&#39; &gt; ./config/config.json</pre><pre>echo &#39;{&quot;API_KEY&quot;:&quot;123-456-789&quot;}&#39; &gt; ./secret/secret.json</pre><p>Now, edit the code so it reads in these files instead of environment variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*W8w_K5sRCZo9XJGq33QK-w.png" /><figcaption><a href="https://gist.github.com/thesandlord/6e297d7ceb807e6f0243255ab7885d83#file-file-js">https://gist.github.com/thesandlord/6e297d7ceb807e6f0243255ab7885d83#file-file-js</a></figcaption></figure><blockquote><strong>Important: </strong>This code will re-read the file on every request. If you read the file once when the program starts, updates to the file will not be captured and you will need to restart the container to update the files. A common pattern that is more efficient that re-reading the file every time is to use a file watcher that will reload the file only when it changes.</blockquote><h3>Mount the files using Docker volumes</h3><p>The first step is to test everything works by using Docker volumes to simulate the ConfigMaps and Secrets.</p><p>Rebuild the container:</p><pre>docker build -t envtest .</pre><p>After building the container, run it with the following command:</p><pre>docker run -p 3000:3000 -ti \<br>  -v $(pwd)/secret/:/usr/src/app/secret/ \<br>  -v $(pwd)/config/:/usr/src/app/config/ \<br>  envtest</pre><p>This will run the Docker container, and mount the data folders into the container.</p><blockquote><strong>Note:</strong> the <a href="https://github.com/nodejs/docker-node/blob/master/6.11/onbuild/Dockerfile#L4">onbuild</a> container that is used for the base image puts the code into the /usr/src/app directory. That is why the folders are mounted there.</blockquote><p>If you visit <a href="localhost:3000">localhost:3000</a> the container should be serving traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*qqUtUpXoe9DRiMUtcrf0kw.png" /></figure><p>Because the file is mounted into the container and the code re-reads the file on every request, you can change the files and see the change without restarting anything!</p><p>For example:</p><pre>echo &#39;{&quot;LANGUAGE&quot;:&quot;Spanish&quot;}&#39; &gt; ./config/config.json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*j_sIOIcnmgevdo7zI__XEA.png" /></figure><h3>Creating the ConfigMap and Secret</h3><p>Create the Secret from the file</p><pre>kubectl create secret generic my-secret \<br>  --from-file=./secret/secret.json</pre><p>Then create the ConfigMap from the other file</p><pre>kubectl create configmap my-config --from-file=./config/config.json</pre><p>You can check that these are created with the following commands:</p><pre>kubectl get secret</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*3njqq9Jd_ZGOqFjavK_xrQ.png" /></figure><p>And</p><pre>kubectl get configmap</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*e0kcgWCdGy8gMqxz5JTAUw.png" /></figure><h3>Using ConfigMaps and Secrets as files</h3><p>The final step is using creating a deployment that will use the ConfigMap and Secret as a file instead of an environment variable</p><p><strong>Note:</strong> Remember you need to update and push the Docker image in your registry to use the new code. You can do that with this command if you are using Google Cloud.</p><pre>gcloud container builds submit --tag gcr.io/$(gcloud config list project --format=text | awk &#39;{print $2}&#39;)/envtest:file .</pre><p>In your deployment YAML, you can use the ConfigMap and Secret as a volume. This will automatically mount them as a directory in your container, just like with Docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*_pSYEK_iysSJ30ugoVXvHQ.png" /><figcaption><a href="https://gist.github.com/thesandlord/6e297d7ceb807e6f0243255ab7885d83#file-file-yaml">https://gist.github.com/thesandlord/6e297d7ceb807e6f0243255ab7885d83#file-file-yaml</a></figcaption></figure><p>Notice that the Secret and ConfigMap are mapped to volumes, and these volumes are used in the volumeMount section of the container spec.</p><h3>Updating with no downtime!</h3><p>Unlike <a href="https://medium.com/google-cloud/kubernetes-configmaps-and-secrets-68d061f7ab5b">Part </a>1’s environment variables, volumes can be dynamically remounted into running containers. This means that new ConfigMap and Secret values will be available to the container without needed to restart the running processes.</p><p>For example, change the language to Klingon and update the ConfigMap.</p><pre>echo &#39;{&quot;LANGUAGE&quot;:&quot;Klingon&quot;}&#39; &gt; ./config/config.json</pre><pre>kubectl create configmap my-config \<br>  --from-file=./config/config.json \<br>  -o yaml --dry-run | kubectl replace -f -</pre><p>In a few seconds (up to a minute depending on the cache) the new file will be pushed to the running containers automatically!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*wGebNWPZ_I_x0ruXA0ttrQ.gif" /></figure><p>If you want to update the secret, you can follow the same process:</p><pre>echo &#39;{&quot;API_KEY&quot;:&quot;0987654321&quot;}&#39; &gt; ./secret/secret.json</pre><pre>kubectl create secret generic my-secret \<br>  --from-file=./secret/secret.json \<br>  -o yaml --dry-run | kubectl replace -f -</pre><blockquote><strong>Note:</strong> These updates are eventually consistent. It is possible that some containers get the update before others, creating inconsistencies in your deployments. If this is an issue, do not use the auto-update feature. Instead, create a new ConfigMap or Secret, and update or create a new Deployment to use the new one.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dc37111f0dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/kubernetes-configmaps-and-secrets-part-2-3dc37111f0dc">Kubernetes ConfigMaps and Secrets Part 2</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>